Merge pull request #9 from xiaozhou233/refactor

Enhance configuration handling and implement module system
This commit is contained in:
xiaozhou233 authored and GitHub committed 2026-04-20 14:06:38 +08:00
commit 95f5604bfe
18 files changed
+18924 -250

No files matched your search

+7 -3
View File
@@ -10,6 +10,10 @@
- [ ] 重构 `libloader` 的配置系统
## 2026-04-17
- [ ] 重构项目为模块化项目
- [ ] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管
- [ ] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作
- [x] 重构项目为模块化项目
- [x] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管
- [x] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作
## 2026-04-19
- [x] 在 `JuiceAgent/Utils.hpp`做序列化操作
- [x] 统一调用 module的Java实现
+16
View File
@@ -0,0 +1,16 @@
[JuiceAgent]
Version = 1
[JuiceAgent.Loader]
JuiceAgentAPIJarPath = ""
JuiceAgentNativeLibraryPath = ""
[JuiceAgent.Modules]
[JuiceAgent.Modules.JarLoader]
Enabled = true
InjectionDir = ""
JarPath = ""
EntryClass = ""
EntryMethod = ""
+127 -158
View File
@@ -2,194 +2,163 @@
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/JuiceAgent.hpp>
#include <tinytoml/toml.h>
#include <toml.hpp>
#include <filesystem>
#include <fstream>
#include <string>
#include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Config {
class Config {
private:
std::string runtime_dir; // Runtime directory
toml::Value config{}; // Parsed TOML configuration
bool valid = false; // Whether the config is successfully loaded
std::filesystem::path _runtime_dir;
toml::value _config;
bool _valid = false;
// Escape special characters ';' = '\'
static std::string escape(const std::string& s) {
std::string out;
out.reserve(s.size());
for (char c : s) {
if (c == ';' || c == '=' || c == '\\') {
out += '\\';
}
out += c;
private:
template<typename T>
static T _read_value(const toml::value& v) {
if constexpr (std::is_same_v<T, std::string>) {
return v.as_string();
} else if constexpr (std::is_same_v<T, bool>) {
return v.as_boolean();
} else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
return static_cast<T>(v.as_integer());
} else if constexpr (std::is_floating_point_v<T>) {
return static_cast<T>(v.as_floating());
} else {
static_assert(sizeof(T) == 0, "Unsupported config type");
}
return out;
}
// Append key=value pair to string
static void append_kv(std::string& out, const char* key, const std::string& value, bool& first) {
if (!first) out += ';';
first = false;
out += key;
out += '=';
out += escape(value);
}
// Helper function: find value by dot-separated key
const toml::Value* find_value(const std::string& key) const {
if (!valid) return nullptr;
const toml::Value* current = &config;
size_t start = 0;
while (true) {
size_t dot = key.find('.', start);
std::string part = key.substr(start, dot - start);
if (!current->is<toml::Table>()) return nullptr;
const auto& table = current->as<toml::Table>();
auto it = table.find(part);
if (it == table.end()) return nullptr;
current = &it->second;
if (dot == std::string::npos) break;
start = dot + 1;
}
return current;
}
public:
explicit Config(const char* c_runtime_dir)
: runtime_dir(c_runtime_dir ? c_runtime_dir : "")
explicit Config(const std::filesystem::path& runtime_dir = {})
{
if (runtime_dir.empty()) {
PLOGW << "runtime_dir is empty";
return;
}
_runtime_dir = runtime_dir.empty()
? std::filesystem::current_path()
: runtime_dir;
std::filesystem::path path = std::filesystem::path(runtime_dir) / "config.toml";
std::ifstream ifs(path);
if (!ifs.is_open()) {
PLOGE << "Failed to open config file: " << path;
return;
}
const auto result = toml::try_parse(_runtime_dir / "config.toml");
try {
auto pr = toml::parse(ifs);
if (!pr.valid()) {
PLOGE << "Invalid TOML file: " << pr.errorReason;
return;
if (result.is_ok()) {
_config = result.unwrap();
_valid = true;
} else {
PLOGE << "Failed to parse config.toml";
for (const auto& err : result.unwrap_err()) {
PLOGE << toml::format_error(err);
}
config = pr.value;
valid = true;
} catch (const std::exception& e) {
PLOGE << "TOML parse error: " << e.what();
}
}
// Get value by key with default
bool is_valid() const noexcept {
return _valid;
}
const toml::value& get_config() const noexcept {
return _config;
}
const std::filesystem::path& runtime_dir() const noexcept {
return _runtime_dir;
}
template<typename T>
T get_or_default(const std::string& key, const T& default_value, bool use_default_if_empty = false, bool is_path = false) const {
const toml::Value* val = find_value(key);
if (!val) return default_value;
T get(const std::string& path, const T& default_value, bool is_path = false) const {
if (!_valid) {
return default_value;
}
try {
if constexpr (std::is_same_v<T, std::string>) {
std::string s = val->as<std::string>();
if (use_default_if_empty && s.empty()) return default_value;
// Check if string starts with '.'
if (is_path && s.starts_with('.')) {
// remove '.'
s.erase(0, 1);
const toml::value* current = &_config;
std::size_t start = 0;
// Check if string starts with '/'
// MUST REMOVE '/', or it will cause path error (root directory)
if (s.starts_with('/')) {
s.erase(0, 1);
}
while (start < path.size()) {
const std::size_t end = path.find('.', start);
const std::string key = path.substr(
start,
end == std::string::npos ? std::string::npos : end - start
);
// runtime_dir + s
s = (std::filesystem::path(runtime_dir) / s).string();
current = &current->at(key);
if (end == std::string::npos) {
break;
}
return s;
} else {
return val->as<T>();
start = end + 1;
}
} catch (...) {
T value = _read_value<T>(*current);
if constexpr (std::is_same_v<T, std::string>) {
if (value.empty()) {
return default_value;
}
// Handle relative paths
if (is_path) {
// Check if starts with "."
if (value.starts_with(".")) {
// Remove "."
value = value.substr(1);
// Check if starts with "/"
if (value.starts_with("/")) {
// Remove "/"
value = value.substr(1);
}
// runtime_dir + value
value = (_runtime_dir / value).string();
}
}
}
return value;
}
catch (const std::exception& e) {
PLOGW << "Config get failed: " << path << ", using default value";
return default_value;
}
}
bool is_valid() const {
return valid;
}
// Get InjectionInfo struct from config
InjectionInfo get_injection_info() const {
InjectionInfo info;
auto get_default_path = [&](const std::string& name) {
return (std::filesystem::path(runtime_dir) / name).string();
};
info.JuiceAgentAPIJarPath = get_or_default<std::string>(
"JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent-API.jar"), true, true);
info.JuiceAgentNativePath = get_or_default<std::string>(
"JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true, true);
info.EntryJarPath = get_or_default<std::string>(
"Entry.EntryJarPath", get_default_path("Entry.jar"), true, true);
info.EntryClass = get_or_default<std::string>(
"Entry.EntryClass", "com.example.Entry", true, false);
info.EntryMethod = get_or_default<std::string>(
"Entry.EntryMethod", "start", true, false);
info.InjectionDir = get_or_default<std::string>(
"Runtime.InjectionDir", get_default_path("injection"), true, true);
return info;
}
// Serialize InjectionInfo to key=value; format
static std::string serialize(const InjectionInfo& info) {
std::string result;
result.reserve(256);
bool first = true;
append_kv(result, "Version", "1", first);
append_kv(result, "EntryJarPath", info.EntryJarPath, first);
append_kv(result, "EntryClass", info.EntryClass, first);
append_kv(result, "EntryMethod", info.EntryMethod, first);
append_kv(result, "JuiceAgentAPIJarPath", info.JuiceAgentAPIJarPath, first);
append_kv(result, "JuiceAgentNativePath", info.JuiceAgentNativePath, first);
append_kv(result, "InjectionDir", info.InjectionDir, first);
PLOGD << "Serialized args: " << result;
return result;
}
std::string serialize() const {
return serialize(get_injection_info());
}
};
// Print InjectionInfo (debug)
inline void print_injection_info(const InjectionInfo& info) {
PLOGI << "JuiceAgent Injection Info:";
PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath;
PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath;
PLOGI << " EntryJarPath: " << info.EntryJarPath;
PLOGI << " EntryClass: " << info.EntryClass;
PLOGI << " EntryMethod: " << info.EntryMethod;
PLOGI << " InjectionDir: " << info.InjectionDir;
namespace Utils {
inline LoaderConfig get_loader_config(const Config& config) {
auto cfg = config.get_config().at("JuiceAgent").at("Loader");
LoaderConfig loader_config = LoaderConfig();
loader_config.JuiceAgentAPIJarPath = cfg.at("JuiceAgentAPIJarPath").as_string();
loader_config.JuiceAgentNativeLibraryPath = cfg.at("JuiceAgentNativeLibraryPath").as_string();
loader_config.RuntimeDir = config.runtime_dir().string();
return loader_config;
}
inline void print_loader_config(const LoaderConfig& config) {
PLOGI << "JuiceAgentAPIJarPath: " << config.JuiceAgentAPIJarPath;
PLOGI << "JuiceAgentNativeLibraryPath: " << config.JuiceAgentNativeLibraryPath;
PLOGI << "RuntimeDir: " << config.RuntimeDir;
}
inline std::string serialize_loader_config(const LoaderConfig& config) {
// std::string result = "";
// result += "Version=2;";
// result += "JuiceAgentAPIJarPath=" + config.JuiceAgentAPIJarPath + ";";
// result += "JuiceAgentNativeLibraryPath=" + config.JuiceAgentNativeLibraryPath + ";";
// result += "RuntimeDir=" + config.RuntimeDir + ";";
JuiceAgent::Utils::Serializer ser;
ser.add_kv("Version", 2);
ser.add_kv("JuiceAgentAPIJarPath", config.JuiceAgentAPIJarPath);
ser.add_kv("JuiceAgentNativeLibraryPath", config.JuiceAgentNativeLibraryPath);
ser.add_kv("RuntimeDir", config.RuntimeDir);
return ser.serialize();
}
}
} // namespace config
} // namespace JuiceAgent::Config
+3 -7
View File
@@ -2,13 +2,9 @@
#include <string>
struct InjectionInfo {
struct LoaderConfig {
std::string JuiceAgentAPIJarPath;
std::string JuiceAgentNativePath;
std::string JuiceAgentNativeLibraryPath;
std::string EntryJarPath;
std::string EntryClass;
std::string EntryMethod;
std::string InjectionDir;
std::string RuntimeDir;
};
+253 -2
View File
@@ -3,9 +3,13 @@
#include <jni.h>
#include <jvmti.h>
#include <JuiceAgent/Logger.hpp>
#include <string>
#include <unordered_map>
#include <type_traits>
#include <cstdlib>
// Check for JNI exceptions and clear them
bool check_and_clear_exception(JNIEnv* env, const char* context) {
inline bool check_and_clear_exception(JNIEnv* env, const char* context) {
if (env->ExceptionCheck()) {
PLOGE << "JNI Exception occurred at: " << context;
env->ExceptionDescribe();
@@ -13,4 +17,251 @@ bool check_and_clear_exception(JNIEnv* env, const char* context) {
return true;
}
return false;
}
}
namespace JuiceAgent::Utils
{
inline bool call_java_impl(JNIEnv* env, const char* clazz, const char* method, const char* params) {
if (!env || !clazz || !method) {
PLOGE << "Invalid JNI arguments";
return false;
}
constexpr const char* method_signature = "(Ljava/lang/String;)V";
PLOGD << "Calling Java method: " << clazz << "." << method << " " << method_signature;
jclass cls = env->FindClass(clazz);
if (!cls) {
check_and_clear_exception(env, "FindClass failed");
PLOGE << "Class not found: " << clazz;
return false;
}
jmethodID mid = env->GetStaticMethodID(cls, method, method_signature);
if (!mid) {
check_and_clear_exception(env, "GetStaticMethodID failed");
PLOGE << "Method not found: " << method;
env->DeleteLocalRef(cls);
return false;
}
jstring j_params = env->NewStringUTF(params ? params : "");
if (!j_params) {
PLOGE << "Failed to create jstring";
env->DeleteLocalRef(cls);
return false;
}
env->CallStaticVoidMethod(cls, mid, j_params);
bool success = !env->ExceptionCheck();
check_and_clear_exception(env, "CallStaticVoidMethod failed");
env->DeleteLocalRef(j_params);
env->DeleteLocalRef(cls);
return success;
}
class Serializer {
private:
std::string s;
private:
static std::string escape(const std::string& input) {
std::string out;
out.reserve(input.size());
for (char c : input) {
if (c == '=' || c == ';' || c == '\\') {
out += '\\';
}
out += c;
}
return out;
}
public:
Serializer() = default;
Serializer& add_kv(const std::string& key, const std::string& value) {
s += escape(key);
s += '=';
s += escape(value);
s += ';';
return *this;
}
Serializer& add_kv(const std::string& key, const char* value) {
return add_kv(key, std::string(value));
}
Serializer& add_kv(const std::string& key, int value) {
return add_kv(key, std::to_string(value));
}
Serializer& add_kv(const std::string& key, bool value) {
return add_kv(key, value ? "true" : "false");
}
void clear() {
s.clear();
}
bool empty() const {
return s.empty();
}
const std::string& serialize() const {
return s;
}
};
class Deserializer {
private:
std::unordered_map<std::string, std::string> data;
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;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
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<typename T>
static T convert(const std::string& v, T def) {
if constexpr (std::is_same_v<T, std::string>) {
return v;
}
else if constexpr (std::is_same_v<T, bool>) {
return to_bool(v, def);
}
else if constexpr (std::is_integral_v<T>) {
try {
long long n = std::stoll(v);
return static_cast<T>(n);
} catch (...) {
return def;
}
}
else if constexpr (std::is_floating_point_v<T>) {
try {
long double n = std::stold(v);
return static_cast<T>(n);
} catch (...) {
return def;
}
}
else {
return def;
}
}
public:
Deserializer() = default;
explicit Deserializer(const std::string& input) {
parse(input);
}
void parse(const std::string& input) {
data.clear();
std::string key;
std::string value;
bool reading_key = true;
bool escaped = false;
for (char c : input) {
if (escaped) {
(reading_key ? key : value) += c;
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
if (reading_key && c == '=') {
reading_key = false;
continue;
}
if (c == ';') {
if (!key.empty()) {
data[unescape(key)] = unescape(value);
}
key.clear();
value.clear();
reading_key = true;
continue;
}
(reading_key ? key : value) += c;
}
if (!key.empty()) {
data[unescape(key)] = unescape(value);
}
}
bool has(const std::string& key) const {
return data.find(key) != data.end();
}
template<typename T>
T get(const std::string& key, T def) const {
auto it = data.find(key);
if (it == data.end()) {
return def;
}
return convert<T>(it->second, def);
}
void clear() {
data.clear();
}
bool empty() const {
return data.empty();
}
std::size_t size() const {
return data.size();
}
};
} // namespace JuiceAgent::Utils
+18162
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017 Toru Niina
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+13 -2
View File
@@ -3,11 +3,22 @@
// This function is called by Java to initialize the agent.
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
(JNIEnv *env, jclass loader_class) {
(JNIEnv *env, jclass , jstring j_runtime_dir) {
InitLogger();
PLOGI << "Initializing JuiceAgent...";
// Get runtime directory
const char* c_runtime_dir = env->GetStringUTFChars(j_runtime_dir, nullptr);
std::string runtime_dir(c_runtime_dir);
env->ReleaseStringUTFChars(j_runtime_dir, c_runtime_dir);
if (runtime_dir.empty()) {
PLOGE << "Failed to get runtime directory from argument, runtime_dir is empty";
return JNI_FALSE;
}
PLOGI << "JuiceAgent got runtime directory: " << runtime_dir;
JavaVM* jvm = nullptr;
jvmtiEnv* jvmti = nullptr;
@@ -27,7 +38,7 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
// Invoke EntryPoint
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
agent.init(jvm, env, jvmti);
agent.init(jvm, env, jvmti, runtime_dir);
return JNI_TRUE;
}
@@ -10,10 +10,10 @@ extern "C" {
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: init
* Signature: ()Z
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
(JNIEnv *, jclass);
(JNIEnv *, jclass, jstring);
/*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
+10 -1
View File
@@ -4,13 +4,18 @@
#include <jni.h>
#include <jvmti.h>
#include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp>
#include <modules/ModuleManager.hpp>
namespace JuiceAgent {
class Agent {
private:
JavaVM* jvm;
jvmtiEnv* jvmti;
JNIEnv* env;
EventBus eventbus;
JuiceAgent::Config::Config config;
JuiceAgent::Core::Modules::ModuleManager module_manager;
private:
Agent() = default;
@@ -24,15 +29,19 @@ namespace JuiceAgent {
Agent& operator=(const Agent&) = delete;
// EntryPoint
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti);
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir);
// getters
JavaVM* get_jvm() const { return jvm; }
jvmtiEnv* get_jvmti() const { return jvmti; }
JNIEnv* get_env() const { return env; }
EventBus& get_eventbus() { return eventbus; }
JuiceAgent::Config::Config& get_config() { return config; }
// setters
void set_jvm(JavaVM* jvm) { this->jvm = jvm; }
void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; }
void set_env(JNIEnv* env) { this->env = env; }
void set_config(JuiceAgent::Config::Config& config) { this->config = config; }
};
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <string>
namespace JuiceAgent::Core::Modules {
class IModule {
public:
virtual ~IModule() = default;
virtual std::string name() const = 0;
virtual bool init() = 0;
virtual bool start() = 0;
virtual void stop() = 0;
};
}
@@ -0,0 +1,27 @@
#pragma once
#include <memory>
#include <vector>
#include <string>
#include <modules/IModule.hpp>
namespace JuiceAgent::Core::Modules {
class ModuleManager {
public:
ModuleManager() = default;
~ModuleManager() = default;
void register_module(std::unique_ptr<IModule> module);
bool init_all();
bool start_all();
void stop_all();
IModule* find_module(const std::string& name);
private:
std::vector<std::unique_ptr<IModule>> _modules;
};
}
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <modules/IModule.hpp>
namespace JuiceAgent::Core::Modules {
class JarLoaderModule : public IModule {
public:
JarLoaderModule() = default;
~JarLoaderModule() override = default;
std::string name() const override {
return "JarLoader";
}
bool init() override;
bool start() override;
void stop() override;
private:
bool _initialized = false;
bool _running = false;
};
}
+89 -66
View File
@@ -3,6 +3,8 @@
#include <bytecodes_opt.hpp>
#include <event/event_type.hpp>
#include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp>
#include <modules/Modules.hpp>
namespace JuiceAgent {
// ===== Singleton =====
@@ -11,74 +13,95 @@ namespace JuiceAgent {
return instance;
}
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti) {
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir) {
try {
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
// ======== neccessary environment check ========
if (jvm == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvm is null";
// ======== neccessary environment check ========
if (jvm == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvm is null";
return false;
}
if (env == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: env is null";
return false;
}
if (jvmti == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvmti is null";
return false;
}
JuiceAgent::Config::Config cfg (runtime_dir);
if (!cfg.is_valid()) {
PLOGE << "Failed to initialize JuiceAgent: config is invalid";
return false;
}
set_jvm(jvm);
set_jvmti(jvmti);
set_env(env);
set_config(cfg);
PLOGD << "env: " << env << ", jvmti: " << jvmti;
// Register Modules
module_manager.register_module(std::make_unique<JuiceAgent::Core::Modules::JarLoaderModule>());
// Initialize Modules
module_manager.init_all();
// PreLoad Event
eventbus.post(EventPreLoad{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
// ======== Application ability ========
jvmtiCapabilities caps{};
caps.can_get_bytecodes = 1;
caps.can_redefine_classes = 1;
caps.can_redefine_any_class = 1;
caps.can_retransform_classes = 1;
caps.can_retransform_any_class = 1;
caps.can_generate_all_class_hook_events = 1;
jint result = jvmti->AddCapabilities(&caps);
if (result != JNI_OK) {
PLOGE << "Failed to add capabilities: " << result;
return false;
}
PLOGI << "Abilities added successfully";
// ======== Register callbacks ========
jvmtiEventCallbacks callbacks{};
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
if (result != JNI_OK) {
PLOGE << "Failed to set event callbacks: " << result;
}
// Enable events
result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
if (result != JNI_OK) {
PLOGE << "Failed to enable event notification: " << result;
}
// register bytecodes_opt
JuiceAgent::Bytecodes::register_bytecodes();
// Start Modules
module_manager.start_all();
// Loaded Event
eventbus.post(EventLoaded{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
return true;
} catch (const std::exception& e) {
PLOGE << "Exception: " << e.what();
return false;
}
if (env == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: env is null";
return false;
}
if (jvmti == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvmti is null";
return false;
}
set_jvm(jvm);
set_jvmti(jvmti);
PLOGD << "env: " << env << ", jvmti: " << jvmti;
// PreLoad Event
eventbus.post(EventPreLoad{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
// ======== Application ability ========
jvmtiCapabilities caps{};
caps.can_get_bytecodes = 1;
caps.can_redefine_classes = 1;
caps.can_redefine_any_class = 1;
caps.can_retransform_classes = 1;
caps.can_retransform_any_class = 1;
caps.can_generate_all_class_hook_events = 1;
jint result = jvmti->AddCapabilities(&caps);
if (result != JNI_OK) {
PLOGE << "Failed to add capabilities: " << result;
return false;
}
PLOGI << "Abilities added successfully";
// ======== Register callbacks ========
jvmtiEventCallbacks callbacks{};
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
if (result != JNI_OK) {
PLOGE << "Failed to set event callbacks: " << result;
}
// Enable events
result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
if (result != JNI_OK) {
PLOGE << "Failed to enable event notification: " << result;
}
// register bytecodes_opt
JuiceAgent::Bytecodes::register_bytecodes();
// Loaded Event
eventbus.post(EventLoaded{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
return true;
}
}
+87
View File
@@ -0,0 +1,87 @@
#include <modules/Modules.hpp>
#include <JuiceAgent/Logger.hpp>
#include <libagent.hpp>
#include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Core::Modules {
struct _Config {
bool Enabled = true;
std::string InjectionDir;
std::string JarPath;
std::string EntryClass;
std::string EntryMethod;
} Config;
static JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
static const char* MODULE_CLASS = "cn/xiaozhou233/juiceagent/api/modules/JarLoader";
static const char* MODULE_METHOD = "loadJar";
bool JarLoaderModule::init() {
if (_initialized) return true;
PLOGI << "JarLoader init";
JuiceAgent::Config::Config& cfg = agent.get_config();
Config.Enabled = cfg.get<bool>("JuiceAgent.Modules.JarLoader.Enabled", false);
Config.InjectionDir = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.InjectionDir", (agent.get_config().runtime_dir() / "injection").string(), true);
Config.JarPath = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.JarPath", "./Entry.jar", true);
Config.EntryClass = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.EntryClass", "Example.Main", false);
Config.EntryMethod = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.EntryMethod", "start", false);
PLOGD << ">>> JarLoader Config <<<";
PLOGD << "Enabled: " << Config.Enabled;
PLOGD << "InjectionDir: " << Config.InjectionDir;
PLOGD << "JarPath: " << Config.JarPath;
PLOGD << "EntryClass: " << Config.EntryClass;
PLOGD << "EntryMethod: " << Config.EntryMethod;
PLOGD << ">>> JarLoader Config <<<";
_initialized = true;
return true;
}
bool JarLoaderModule::start() {
if (!_initialized) return false;
if (_running) return true;
PLOGI << "JarLoader start";
if (!Config.Enabled) {
PLOGI << "JarLoader is disabled";
return false;
}
if (Config.InjectionDir.empty() || Config.JarPath.empty() || Config.EntryClass.empty() || Config.EntryMethod.empty()) {
PLOGE << "JarLoader config is invalid";
return false;
}
JuiceAgent::Utils::Serializer ser;
ser.add_kv("InjectionDir", Config.InjectionDir);
ser.add_kv("JarPath", Config.JarPath);
ser.add_kv("EntryClass", Config.EntryClass);
ser.add_kv("EntryMethod", Config.EntryMethod);
std::string serialized = ser.serialize();
PLOGD << "Serialized config: " << serialized;
JNIEnv* env = agent.get_env();
JuiceAgent::Utils::call_java_impl(env, MODULE_CLASS, MODULE_METHOD, serialized.c_str());
PLOGI << "JarLoader is running";
_running = true;
return true;
}
void JarLoaderModule::stop() {
if (!_running) return;
PLOGI << "JarLoader stop";
_running = false;
}
}
+52
View File
@@ -0,0 +1,52 @@
#include <modules/ModuleManager.hpp>
#include <JuiceAgent/Logger.hpp>
namespace JuiceAgent::Core::Modules {
void ModuleManager::register_module(std::unique_ptr<IModule> module) {
if (!module) return;
PLOGI << "Register module: " << module->name();
_modules.push_back(std::move(module));
}
bool ModuleManager::init_all() {
for (auto& module : _modules) {
PLOGI << "Init module: " << module->name();
if (!module->init()) {
PLOGE << "Failed to init module: " << module->name();
return false;
}
}
return true;
}
bool ModuleManager::start_all() {
for (auto& module : _modules) {
PLOGI << "Start module: " << module->name();
if (!module->start()) {
PLOGE << "Failed to start module: " << module->name();
return false;
}
}
return true;
}
void ModuleManager::stop_all() {
for (auto it = _modules.rbegin(); it != _modules.rend(); ++it) {
(*it)->stop();
}
}
IModule* ModuleManager::find_module(const std::string& name) {
for (auto& module : _modules) {
if (module->name() == name) {
return module.get();
}
}
return nullptr;
}
}
+12 -8
View File
@@ -7,7 +7,7 @@
namespace JuiceAgent::Loader {
// Invoke JuiceAgentBootstrap.start(String) via JNI
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) {
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";
@@ -27,7 +27,7 @@ bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) {
}
// Serialize InjectionInfo to string
std::string args = JuiceAgent::Config::Config::serialize(info);
std::string args = JuiceAgent::Config::Utils::serialize_loader_config(config);
PLOGD << "Invoke args: " << args;
// Create Java string
@@ -59,14 +59,18 @@ void entrypoint(const char* runtime_dir) {
JuiceAgent::Config::Config cfg(runtime_dir);
if (!cfg.is_valid()) {
PLOGW << "Invalid config, using default values";
// TODO: Use default values
// Before impl TODO, must return, or crash will happen
return;
}
// Get InjectionInfo
InjectionInfo info = cfg.get_injection_info();
JuiceAgent::Config::print_injection_info(info);
LoaderConfig config = JuiceAgent::Config::Utils::get_loader_config(cfg);
JuiceAgent::Config::Utils::print_loader_config(config);
// Validate essential paths
if (info.JuiceAgentAPIJarPath.empty()) {
if (config.JuiceAgentAPIJarPath.empty()) {
PLOGE << "JuiceAgentAPIJarPath is empty, abort injection";
return;
}
@@ -87,16 +91,16 @@ void entrypoint(const char* runtime_dir) {
}
// Inject JuiceAgent jar into system class loader
jint status = jvmti->AddToSystemClassLoaderSearch(info.JuiceAgentAPIJarPath.c_str());
jint status = jvmti->AddToSystemClassLoaderSearch(config.JuiceAgentAPIJarPath.c_str());
if (status != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed: " << status;
return;
}
PLOGI << "Jar injected successfully: " << info.JuiceAgentAPIJarPath;
PLOGI << "Jar injected successfully: " << config.JuiceAgentAPIJarPath;
// Invoke JuiceAgent initialization
if (!invoke_juiceagent_init(env, info)) {
if (!invoke_juiceagent_init(env, config)) {
PLOGE << "invoke_juiceagent_init failed";
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ namespace JuiceAgent::Loader
{
void entrypoint(const char* runtime_dir);
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info);
bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& info);
} // namespace JuiceAgent::Loader
namespace {