Compare commits

..
Author SHA1 Message Date
xiaozhou233 f5912f8040 [Doc] Update Version & Example Config 2026-04-20 16:48:29 +08:00
xiaozhou233 95f5604bfe Merge pull request #9 from xiaozhou233/refactor
Enhance configuration handling and implement module system
2026-04-20 14:06:38 +08:00
xiaozhou233 1ae65dd516 [Doc] TODO 2026-04-20 14:05:14 +08:00
xiaozhou233 50773f5456 Feat: Call Java Implementation 2026-04-20 14:04:53 +08:00
xiaozhou233 ccb332cb42 [Feat] Serializer 2026-04-20 13:18:58 +08:00
xiaozhou233 9a2dd217f1 [Refactor] Update configuration handling in JarLoader and enhance Config class 2026-04-19 22:26:51 +08:00
xiaozhou233 3fe9f5a573 Feat: Modules System 2026-04-19 19:03:48 +08:00
xiaozhou233 6858a35754 Feat: Simple module system 2026-04-19 18:57:32 +08:00
xiaozhou233 e7ce54188b [Refactor] Enhance Config class with type-safe get method and value reading 2026-04-19 18:44:59 +08:00
xiaozhou233 9f366645c9 Feat: libagent can now read the config 2026-04-19 18:36:26 +08:00
xiaozhou233 6a7e5a1d38 [Refactor] Config and Loader
[Add] toml11 library
[Refactor] Config
[Refactor] Data Struct
[Refactor] Loader
2026-04-19 16:41:39 +08:00
xiaozhou233 17bc993296 Example: empty example config 2026-04-19 15:44:06 +08:00
xiaozhou233 c348529e65 Style: Rename 2026-04-18 19:53:59 +08:00
xiaozhou233 cc52a25db4 Style: Rename 2026-04-18 19:28:47 +08:00
xiaozhou233 8b0bf8f211 Style: move LocalRef to header / move check_and_clear_exception to header 2026-04-18 19:24:49 +08:00
26 changed files with 2890 additions and 753 deletions

No files matched your search

+11 -13
View File
@@ -5,7 +5,7 @@ JuiceAgent is a JVMTI-based injection library for loading external JARs and tran
**Notice:** Currently, only **Windows** is supported. **Linux** support may be added in the future.
**Notice:** The current repository version is **Version 3.1 Build 3**.
**Notice:** The current repository version is **Version 3.3 Build 1**.
**Warning:** This project is still experimental and is not recommended for production use. Use it at your own risk.
@@ -42,22 +42,20 @@ Create a file named `config.toml` in `YourDir`.
```toml
[JuiceAgent]
# Default value: YourDir/JuiceAgent-API.jar
Version = 1
[JuiceAgent.Loader]
JuiceAgentAPIJarPath = ""
# Default value: YourDir/libagent.dll
JuiceAgentNativePath = ""
JuiceAgentNativeLibraryPath = ""
[Entry]
# Default value: YourDir/Entry.jar
EntryJarPath = ""
# Default value: com.example.Entry
EntryClass = ""
# Default value: start
EntryMethod = "start"
[JuiceAgent.Modules]
[Runtime]
# Default value: YourDir/injection
[JuiceAgent.Modules.JarLoader]
Enabled = true
InjectionDir = ""
JarPath = ""
EntryClass = ""
EntryMethod = ""
```
### 3. Run the Injector
+11 -13
View File
@@ -5,7 +5,7 @@ JuiceAgent 是一个基于 JVMTI 的注入库,用于加载外部 JAR 并对 Ja
**注意:** 当前仅支持 **Windows**,未来可能会支持 **Linux**。
**注意:** 当前仓库版本为 **Version 3.1 Build 3**。
**注意:** 当前仓库版本为 **Version 3.3 Build 1**。
**警告:** 本项目仍处于实验阶段,不建议在生产环境中使用。使用风险请自行承担。
@@ -42,22 +42,20 @@ JuiceAgent 是一个基于 JVMTI 的原生注入框架。它通过向目标 JVM
```toml
[JuiceAgent]
# 默认值: YourDir/JuiceAgent-API.jar
Version = 1
[JuiceAgent.Loader]
JuiceAgentAPIJarPath = ""
# 默认值: YourDir/libagent.dll
JuiceAgentNativePath = ""
JuiceAgentNativeLibraryPath = ""
[Entry]
# 默认值: YourDir/Entry.jar
EntryJarPath = ""
# 默认值: com.example.Entry
EntryClass = ""
# 默认值: start
EntryMethod = "start"
[JuiceAgent.Modules]
[Runtime]
# 默认值: YourDir/injection
[JuiceAgent.Modules.JarLoader]
Enabled = true
InjectionDir = ""
JarPath = ""
EntryClass = ""
EntryMethod = ""
```
### 3. 执行注入
+6 -4
View File
@@ -7,11 +7,13 @@
- [x] 在 `includes/JuiceAgent` 文件夹下实现 `Config.hpp` 配置系统
- [ ] ~~新建测试 读取配置文件 (放弃)~~
- [x] 重构 `libloader` 的配置系统
- [ ] 重构 `libloader` 的配置系统
## 2026-04-17
- [ ] 重构项目为模块化项目
- [x] 重构项目为模块化项目
- [x] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管
- [x] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作
- [x] 替换toml库
- [x] 重构 `libloader` 的配置系统
## 2026-04-19
- [x] 在 `JuiceAgent/Utils.hpp`做序列化操作
- [x] 统一调用 module的Java实现
+1 -1
View File
@@ -1 +1 @@
VERSION = Version 3.2 Build 1 PreRelease
VERSION = Version 3.1 Build 3
+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 = ""
+125 -145
View File
@@ -1,184 +1,164 @@
#pragma once
#include <filesystem>
#include <sstream>
#include <string>
#include <vector>
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/JuiceAgent.hpp>
#include <toml.hpp>
#include <filesystem>
#include <string>
#include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Config {
class Config {
private:
std::filesystem::path _runtime_dir;
toml::value _config;
bool _valid = false;
private:
std::filesystem::path config_dir_;
toml::value data_;
bool valid_ = false;
private:
// Split "A.B.C" -> {"A", "B", "C"}
static std::vector<std::string> split_path(const std::string& path) {
std::vector<std::string> result;
std::stringstream stream(path);
std::string token;
while (std::getline(stream, token, '.')) {
if (!token.empty()) {
result.push_back(token);
}
}
return result;
}
// Find node by dot path
const toml::value* find(const std::string& path) const {
const toml::value* current = &data_;
for (const auto& key : split_path(path)) {
if (!current->is_table()) {
return nullptr;
}
if (!current->contains(key)) {
return nullptr;
}
current = &current->at(key);
}
return current;
}
// Load and parse config file
void load() {
if (!std::filesystem::exists(config_dir_)) {
PLOGE << "Config directory not found: " << config_dir_;
config_dir_ = std::filesystem::current_path();
PLOGW << "Using runtime directory: " << std::filesystem::current_path();
}
const auto path = config_dir_ / "config.toml";
if (!std::filesystem::exists(path)) {
PLOGE << "Config file not found: " << path;
return;
}
try {
data_ = toml::parse(path);
valid_ = true;
} catch (const std::exception& e) {
PLOGE << "Failed to parse config: " << e.what();
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");
}
}
public:
explicit Config(std::filesystem::path dir)
: config_dir_(std::move(dir)) {
load();
}
explicit Config(const std::filesystem::path& runtime_dir = {})
{
_runtime_dir = runtime_dir.empty()
? std::filesystem::current_path()
: runtime_dir;
public:
bool is_valid() const {
return valid_;
}
const auto result = toml::try_parse(_runtime_dir / "config.toml");
bool contains(const std::string& path) const {
return find(path) != nullptr;
}
if (result.is_ok()) {
_config = result.unwrap();
_valid = true;
} else {
PLOGE << "Failed to parse config.toml";
template<typename T>
T get(const std::string& path) const {
const auto* node = find(path);
if (!node) {
throw std::runtime_error("Config key not found: " + path);
for (const auto& err : result.unwrap_err()) {
PLOGE << toml::format_error(err);
}
}
}
return toml::get<T>(*node);
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(const std::string& path, const T& default_value) const {
const auto* node = find(path);
if (!node) {
T get(const std::string& path, const T& default_value, bool is_path = false) const {
if (!_valid) {
return default_value;
}
try {
auto result = toml::get<T>(*node);
if (result.empty())
return default_value;
return result;
} catch (...) {
return default_value;
}
}
const toml::value* current = &_config;
std::size_t start = 0;
std::string get_path_or_default(const std::string& path, const std::string& default_value) const {
std::string result = get_or<std::string>(path, default_value);
if(result.starts_with(".")) {
result.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
);
// Check if string starts with '/'
// MUST REMOVE '/', or it will cause path error (root directory)
if (result.starts_with('/')) {
result.erase(0, 1);
}
current = &current->at(key);
result = (config_dir_ / result).string();
}
return result;
}
InjectionInfo get_injection_info() const {
InjectionInfo info;
auto get_default_path = [&](const std::string& name) {
return (std::filesystem::path(config_dir_) / name).string();
};
info.JuiceAgentAPIJarPath = get_path_or_default("Loader.JuiceAgentAPIJarPath", get_default_path("JuiceAgentAPI.jar"));
info.JuiceAgentNativeLibraryPath = get_path_or_default("Loader.JuiceAgentNativeLibraryPath", get_default_path("libagent.dll"));
info.ConfigDir = config_dir_.string();
return info;
}
static std::string serialize(InjectionInfo info) {
auto escape = [](const std::string& value) -> std::string {
std::string result;
result.reserve(value.size());
for (char ch : value) {
if (ch == ';' || ch == '=' || ch == '\\') {
result += '\\';
if (end == std::string::npos) {
break;
}
result += ch;
start = end + 1;
}
return result;
};
T value = _read_value<T>(*current);
return
"JuiceAgentAPIJarPath=" + escape(info.JuiceAgentAPIJarPath) + ";" +
"JuiceAgentNativeLibraryPath=" + escape(info.JuiceAgentNativeLibraryPath) + ";" +
"ConfigDir=" + escape(info.ConfigDir);
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;
}
}
};
void print_injection_info(const InjectionInfo& info) {
PLOGI << "JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath;
PLOGI << "JuiceAgentNativeLibraryPath: " << info.JuiceAgentNativeLibraryPath;
PLOGI << "ConfigDir: " << info.ConfigDir;
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 JuiceAgent::Config
+2 -2
View File
@@ -2,9 +2,9 @@
#include <string>
struct InjectionInfo {
struct LoaderConfig {
std::string JuiceAgentAPIJarPath;
std::string JuiceAgentNativeLibraryPath;
std::string ConfigDir;
std::string RuntimeDir;
};
+267
View File
@@ -0,0 +1,267 @@
#pragma once
#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
inline bool check_and_clear_exception(JNIEnv* env, const char* context) {
if (env->ExceptionCheck()) {
PLOGE << "JNI Exception occurred at: " << context;
env->ExceptionDescribe();
env->ExceptionClear();
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
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
Copyright (c) 2014, MAYAH
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+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;
}
}
@@ -1,40 +1,13 @@
#include <JuiceAgent/Logger.hpp>
#include <libloader.hpp>
#include <Loader.hpp>
#include <JuiceAgent/Config.hpp>
#include <jvm.hpp>
#include <JvmManager.hpp>
#include <JuiceAgent/Utils.hpp>
namespace libloader {
namespace {
// Check for JNI exceptions and clear them
bool check_and_clear_exception(JNIEnv* env, const char* context) {
if (env->ExceptionCheck()) {
PLOGE << "JNI Exception occurred at: " << context;
env->ExceptionDescribe();
env->ExceptionClear();
return true;
}
return false;
}
// RAII wrapper for local JNI references
template<typename T>
class LocalRef {
private:
JNIEnv* env;
T ref;
public:
LocalRef(JNIEnv* env, T ref) : env(env), ref(ref) {}
~LocalRef() {
if (ref) env->DeleteLocalRef(ref);
}
T get() const { return ref; }
operator T() const { return ref; }
};
}
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";
@@ -54,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
@@ -86,21 +59,24 @@ 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;
}
PLOGI << cfg.get_path_or_default("Loader.JuiceAgentAPIJarPath", "NONE");
// 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()) {
PLOGE << "JuiceAgentAPIJarPath is empty, abort injection";
return;
}
if (config.JuiceAgentAPIJarPath.empty()) {
PLOGE << "JuiceAgentAPIJarPath is empty, abort injection";
return;
}
// Attach to JVM
jvm::Jvm jvm;
JuiceAgent::Loader::JvmManager::Jvm jvm;
if (!jvm.attach()) {
PLOGE << "Attach to JVM failed";
return;
@@ -115,18 +91,18 @@ 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";
}
}
} // namespace libloader
} // namespace JuiceAgent::Loader
-246
View File
@@ -1,246 +0,0 @@
#include <jvm/jni.h>
#include <jvm/jvmti.h>
#include <stdio.h>
#include <JuiceAgent/Logger.hpp>
#include <libloader.h>
#include <thread>
#include <tinytoml/toml.h>
#include <JuiceAgent/JuiceAgent.h>
struct _JuiceAgent {
bool isAttached;
JavaVM *jvm;
jvmtiEnv *jvmti;
JNIEnv *env;
} JuiceAgent = {false, NULL, NULL, NULL};
InjectionInfoType InjectionInfo;
static int ReadConfig(const char* ConfigDir)
{
// ConfigDir/config.toml
std::string path = std::string(ConfigDir) + "\\config.toml";
std::ifstream ifs(path);
if (!ifs) return -1;
// Parse toml
toml::ParseResult pr = toml::parse(ifs);
if (!pr.valid()) return -2;
const toml::Value& tbl = pr.value;
// Helper function: get string from toml
auto get_str = [&](const char* key, const char* def, char* out) {
const toml::Value* v = tbl.find(key);
if (v && v->is<std::string>()) {
std::string s = v->as<std::string>();
if (!s.empty()) {
strncpy(out, s.c_str(), INJECT_PATH_MAX - 1);
PLOGD << "Found parameter: " << key << " = " << s.c_str();
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Parameter " << key << " is empty, use default: " << def;
}
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Not found parameter: " << key << ", use default: " << def;
}
out[INJECT_PATH_MAX - 1] = '\0';
};
// Default values
std::string defaultJuiceLoader = std::string(ConfigDir) + "\\JuiceLoader.jar";
std::string defaultJuiceLoaderLibrary = std::string(ConfigDir) + "\\libjuiceloader.dll";
std::string defaultEntryJar = std::string(ConfigDir) + "\\Entry.jar";
std::string defaultInjectionDir = std::string(ConfigDir) + "\\injection";
get_str("JuiceLoaderJarPath", defaultJuiceLoader.c_str(), InjectionInfo.JuiceLoaderJarPath);
get_str("JuiceLoaderLibraryPath", defaultJuiceLoaderLibrary.c_str(), InjectionInfo.JuiceLoaderLibraryPath);
get_str("InjectionDir", defaultInjectionDir.c_str(), InjectionInfo.InjectionDir);
get_str("EntryJarPath", defaultEntryJar.c_str(), InjectionInfo.EntryJarPath);
get_str("EntryClass", "cn.xiaozhou233.test.Entry", InjectionInfo.EntryClass);
get_str("EntryMethod", "start", InjectionInfo.EntryMethod);
PLOGD << "JuiceLoaderJarPath: " << InjectionInfo.JuiceLoaderJarPath;
PLOGD << "JuiceLoaderLibraryPath: " << InjectionInfo.JuiceLoaderLibraryPath;
PLOGD << "InjectionDir: " << InjectionInfo.InjectionDir;
PLOGD << "EntryJarPath: " << InjectionInfo.EntryJarPath;
PLOGD << "EntryClass: " << InjectionInfo.EntryClass;
PLOGD << "EntryMethod: " << InjectionInfo.EntryMethod;
return 0;
}
static int GetJavaEnv() {
jint res = JNI_ERR;
JavaVM *jvm = NULL;
jvmtiEnv *jvmti = NULL;
JNIEnv *env = NULL;
int max_try = 30;
// Get the JVM
max_try = 30;
do {
res = JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
if (res != JNI_OK || jvm == NULL) {
PLOGE.printf("JNI_GetCreatedJavaVMs failed: %d", res);
PLOGD << "JVM NULL: " << (jvm == NULL);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (jvm != NULL) {
break;
} else {
PLOGI.printf("Waiting for JVM... (%d)", max_try);
}
} while (jvm == NULL && max_try > 0);
if (jvm == NULL) {
PLOGE << "GetJavaEnv failed";
return res;
}
JuiceAgent.jvm = jvm;
PLOGI << "Got the JVM";
// Get the JNIEnv
max_try = 30;
do {
res = jvm->GetEnv((void**)&env, JNI_VERSION_1_8);
if (res != JNI_OK || env == NULL) {
PLOGI << "GetEnv failed, trying to attach.";
PLOGD << "env NULL: " << (env == NULL);
res = jvm->AttachCurrentThread((void**)&env, NULL);
if (res != JNI_OK || env == NULL) {
PLOGE.printf("AttachCurrentThread failed: %d", res);
PLOGD << "env NULL: " << (env == NULL);
return res;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (env != NULL) {
break;
} else {
PLOGI.printf("Waiting for JNI... (%d)", max_try);
}
} while (env == NULL && max_try > 0);
if (env == NULL) {
PLOGE << "Get JNI failed";
return res;
}
JuiceAgent.env = env;
PLOGI << "Got the JNIEnv";
// Get the JVMTI
res = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2);
if (res != JNI_OK || jvmti == NULL) {
PLOGE.printf("GetEnv failed: %d", res);
PLOGD << "jvmti NULL: " << (jvmti == NULL);
return res;
}
JuiceAgent.jvmti = jvmti;
PLOGI << "Got the JVMTI";
return 0;
}
static int InvokeJuiceLoaderInit(const char* ConfigDir) {
// Variables
int result = JNI_ERR;
JNIEnv *env = JuiceAgent.env;
jvmtiEnv *jvmti = JuiceAgent.jvmti;
const char *bootstrap_class = "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap";
const char *method_name = "init";
const char *method_signature = "([Ljava/lang/String;)V";
PLOGI << "Invoke JuiceLoader Init";
PLOGI << "================ JuiceLoader Init =================";
// Find class
jclass cls = env->FindClass(bootstrap_class);
if (cls == NULL) {
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGE << "FindClass failed";
return 1;
}
// Find method
jmethodID mid = env->GetStaticMethodID(cls, method_name, method_signature);
if (mid == NULL) {
PLOGE << "GetStaticMethodID failed";
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return 1;
}
// arguments array
const char* args[] = {
InjectionInfo.EntryJarPath,
InjectionInfo.EntryClass,
InjectionInfo.EntryMethod,
InjectionInfo.InjectionDir,
InjectionInfo.JuiceLoaderLibraryPath
};
int argCount = sizeof(args)/sizeof(args[0]);
jclass stringCls = env->FindClass("java/lang/String");
jobjectArray jArgs = env->NewObjectArray(argCount, stringCls, nullptr);
for (int i = 0; i < argCount; i++) {
env->SetObjectArrayElement(jArgs, i, env->NewStringUTF(args[i]));
}
// Invoke method
env->CallStaticVoidMethod(cls, mid, jArgs);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGI << "================ JuiceLoader Init =================";
PLOGI << "Invoke JuiceLoader Init done";
return 0;
}
extern "C" __declspec(dllexport)
bool InitJuiceAgent(const char* runtime_path) {
PLOGD << "runtime_path: " << runtime_path;
// Read Config
if (ReadConfig(runtime_path) != 0) {
PLOGE << "ReadConfig failed";
return false;
}
PLOGI << "[OK] ReadConfig";
// Get JavaEnv
if (GetJavaEnv() != 0) {
PLOGE << "GetJavaEnv failed";
return false;
}
PLOGI << "[OK] Get JavaEnv";
// Inject JuiceLoader jar
if (JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath) != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed";
return false;
}
PLOGI << "[OK] Inject JuiceLoader jar";
// Invoke JuiceLoader Init
if (InvokeJuiceLoaderInit(runtime_path) != 0) {
PLOGE << "Invoke JuiceLoader Init failed";
return false;
}
PLOGI << "[OK] Invoke JuiceLoader Init";
// Load JuiceLoaderLibrary
PLOGI << "--------> InitJuiceAgent Succeed <--------";
return true;
}
@@ -6,7 +6,7 @@
#include <thread>
#include <chrono>
namespace jvm
namespace JuiceAgent::Loader::JvmManager
{
class Jvm {
private:
@@ -119,4 +119,4 @@ namespace jvm
thread_local JNIEnv* Jvm::env = nullptr;
} // namespace jvm
} // namespace JuiceAgent::Loader::JvmManager
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <JuiceAgent/JuiceAgent.hpp>
#include <string>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
namespace JuiceAgent::Loader
{
void entrypoint(const char* runtime_dir);
bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& info);
} // namespace JuiceAgent::Loader
namespace {
// RAII wrapper for local JNI references
template<typename T>
class LocalRef {
private:
JNIEnv* env;
T ref;
public:
LocalRef(JNIEnv* env, T ref) : env(env), ref(ref) {}
~LocalRef() {
if (ref) env->DeleteLocalRef(ref);
}
T get() const { return ref; }
operator T() const { return ref; }
};
}
-195
View File
@@ -1,195 +0,0 @@
#pragma once
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/JuiceAgent.hpp>
#include <tinytoml/toml.h>
#include <filesystem>
#include <fstream>
#include <string>
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
// 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;
}
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 : "")
{
if (runtime_dir.empty()) {
PLOGW << "runtime_dir is empty";
return;
}
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;
}
try {
auto pr = toml::parse(ifs);
if (!pr.valid()) {
PLOGE << "Invalid TOML file: " << pr.errorReason;
return;
}
config = pr.value;
valid = true;
} catch (const std::exception& e) {
PLOGE << "TOML parse error: " << e.what();
}
}
// Get value by key with default
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;
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);
// Check if string starts with '/'
// MUST REMOVE '/', or it will cause path error (root directory)
if (s.starts_with('/')) {
s.erase(0, 1);
}
// runtime_dir + s
s = (std::filesystem::path(runtime_dir) / s).string();
}
return s;
} else {
return val->as<T>();
}
} catch (...) {
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 config
-14
View File
@@ -1,14 +0,0 @@
#pragma once
#include <JuiceAgent/JuiceAgent.hpp>
#include <string>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
namespace libloader
{
void entrypoint(const char* runtime_dir);
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info);
} // namespace libloader
+2 -2
View File
@@ -1,6 +1,6 @@
#include <windows.h>
#include <JuiceAgent/Logger.hpp>
#include <libloader.hpp>
#include <Loader.hpp>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
switch( fdwReason )
@@ -11,7 +11,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
const char* runtime_dir = (const char*)lpReserved;
libloader::entrypoint(runtime_dir);
JuiceAgent::Loader::entrypoint(runtime_dir);
break;
}