[Refactor] Config and Loader

[Add] toml11 library
[Refactor] Config
[Refactor] Data Struct
[Refactor] Loader
This commit is contained in:
xiaozhou233 committed 2026-04-19 16:41:39 +08:00
1 parent 17bc993296
commit 6a7e5a1d38
6 files changed
+18251 -182

No files matched your search

+52 -166
View File
@@ -2,194 +2,80 @@
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/JuiceAgent.hpp>
#include <tinytoml/toml.h>
#include <toml.hpp>
#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;
}
std::filesystem::path _runtime_dir;
toml::value _config;
bool _valid = false;
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
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 noexcept {
return _valid;
}
bool is_valid() const {
return valid;
const toml::value& get_config() const noexcept {
return _config;
}
// 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());
const std::filesystem::path& runtime_dir() const noexcept {
return _runtime_dir;
}
};
// 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 {
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;
}
void print_loader_config(const LoaderConfig& config) {
PLOGI << "JuiceAgentAPIJarPath: " << config.JuiceAgentAPIJarPath;
PLOGI << "JuiceAgentNativeLibraryPath: " << config.JuiceAgentNativeLibraryPath;
PLOGI << "RuntimeDir: " << config.RuntimeDir;
}
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 + ";";
return result;
}
}
} // 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;
};
+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.
+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 {