BugFix: keep libloader exception-free so a bad config cannot crash the JVM

- loader: libloader is reflectively loaded, so its unwind tables are never registered with the OS and a C++ exception thrown inside it cannot be caught - it crashed the target JVM with EXCEPTION_ILLEGAL_INSTRUCTION when config.toml was missing a required key. Replace the throwing config reads with contains() + get(key, default) + early return, and drop the ineffective try/catch in entrypoint()

- config: parse config.toml without exceptions (toml++ parse_result) and remove the throwing get()/getPath()/getArray() overloads

- build: compile libloader with -fno-exceptions (+ SPDLOG_NO_EXCEPTIONS) so exception-capable code fails the build instead of crashing at runtime
This commit is contained in:
xiaozhou233 committed 2026-10-16 12:59:26 +08:00
1 parent 124c656400
commit 3cd28c9bcb
4 files changed
+90 -155

No files matched your search

+23 -115
View File
@@ -3,7 +3,6 @@
#include <filesystem>
#include <optional>
#include <toml++/toml.h>
#include <stdexcept>
#include <string>
#include <vector>
#include <cstddef>
@@ -33,40 +32,36 @@ public:
_config_path = _runtime_dir / "config.toml";
// Load the config file
// Load the config file.
//
// This must never throw: when libloader runs from the reflectively
// loaded DLL its unwind tables are not registered, so a C++ exception
// raised here could not be caught and would crash the target process.
// toml++ switches to non-throwing mode (parse_result) automatically
// when exceptions are disabled.
#if TOML_EXCEPTIONS
try {
_config = toml::parse_file(_config_path.string());
_valid = true;
} catch (const toml::parse_error& e) {
spdlog::error("Failed to parse config file: {}", e.what());
spdlog::error("Failed to parse config file: {}", e.description());
_last_error = e;
}
#else
toml::parse_result result = toml::parse_file(_config_path.string());
if (result.succeeded()) {
_config = std::move(result).table();
_valid = true;
} else {
spdlog::error("Failed to parse config file: {}", result.error().description());
_last_error = result.error();
}
#endif
}
template<typename T>
T get(const std::string& path) const {
const auto* node = _config.at_path(path).node();
if (!node) {
spdlog::error("Configuration key not found: {}", path);
throw std::runtime_error(
"Configuration key not found: " + path
);
}
auto value = node->value<T>();
if (!value) {
spdlog::error("Configuration type mismatch: {}", path);
throw std::runtime_error(
"Configuration type mismatch: " + path
);
}
return *value;
}
// Non-throwing lookup: returns defaultValue when the key is missing or has
// the wrong type. There is deliberately no throwing overload - callers that
// require a key must check contains() first.
template<typename T>
T get(const std::string& path, T defaultValue) const {
const auto* node = _config.at_path(path).node();
@@ -88,16 +83,6 @@ public:
return *value;
}
std::string getPath(const std::string& key) const {
const std::string value = get<std::string>(key);
if (value.empty()) {
return {};
}
return getPath(key, value);
}
std::string getPath(
const std::string& key,
const std::string& defaultValue
@@ -128,83 +113,6 @@ public:
return value.lexically_normal().string();
}
template<typename T>
std::vector<T> getArray(const std::string& path) const {
const auto* node = _config.at_path(path).node();
if (!node) {
throw std::runtime_error(
"Configuration key not found: " + path
);
}
const auto* array = node->as_array();
if (!array) {
throw std::runtime_error(
"Configuration type mismatch: expected array: " + path
);
}
std::vector<T> result;
result.reserve(array->size());
for (std::size_t i = 0; i < array->size(); ++i) {
const auto& element = (*array)[i];
auto value = element.value<T>();
if (!value) {
throw std::runtime_error(
"Configuration array element type mismatch: "
+ path + "[" + std::to_string(i) + "]"
);
}
result.push_back(*value);
}
return result;
}
template<typename T>
std::vector<T> getArray(
const std::string& path,
std::vector<T> defaultValue
) const {
const auto* node = _config.at_path(path).node();
if (!node) {
return defaultValue;
}
const auto* array = node->as_array();
if (!array) {
throw std::runtime_error(
"Configuration type mismatch: expected array: " + path
);
}
std::vector<T> result;
result.reserve(array->size());
for (std::size_t i = 0; i < array->size(); ++i) {
const auto& element = (*array)[i];
auto value = element.value<T>();
if (!value) {
throw std::runtime_error(
"Configuration array element type mismatch: "
+ path + "[" + std::to_string(i) + "]"
);
}
result.push_back(*value);
}
return result;
}
bool contains(const std::string& path) const {
return _config.at_path(path).node() != nullptr;
}
@@ -231,4 +139,4 @@ public:
}
};
} // namespace JuiceAgent::Config
} // namespace JuiceAgent::Config
+8
View File
@@ -16,6 +16,14 @@ endif()
add_library(loader SHARED ${loader_sources})
# libloader is reflectively loaded (manually mapped), so the OS never registers
# its unwind tables: a C++ exception thrown here cannot be caught and would crash
# the target process. Disable exceptions so such code fails the build instead.
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(loader PRIVATE -fno-exceptions)
target_compile_definitions(loader PRIVATE SPDLOG_NO_EXCEPTIONS)
endif()
target_include_directories(loader PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
+25 -31
View File
@@ -1,40 +1,34 @@
#include <exception>
#include <Loader.hpp>
#include <JvmAttach.hpp>
#include <JuiceAgent/Logger.hpp>
void JuiceAgent::Loader::entrypoint(const char* path) {
// This runs from DllMain inside the target JVM process, so a C++ exception
// escaping here would take the target process down. Contain everything as a
// last line of defence; a bad config.toml is reported and logged instead.
try {
// Attach to the JVM
JuiceAgent::Loader::JvmAttach jvmAttach;
// Called from DllMain inside the target JVM process. NOTE: libloader is
// reflectively loaded, so a C++ exception thrown here cannot be unwound and
// would crash the target process - this code must not throw (see the note
// in Loader::preload).
if(!jvmAttach.attach()) {
spdlog::error("Failed to attach to JVM!");
return;
}
// Attach to the JVM
JuiceAgent::Loader::JvmAttach jvmAttach;
// Get JNIEnv
JNIEnv* env = jvmAttach.get_env();
if(!env) {
spdlog::error("Failed to get JNIEnv!");
return;
}
// Get JVMTI environment
jvmtiEnv* jvmti = jvmAttach.get_jvmti();
if(!jvmti) {
spdlog::error("Failed to get JVMTI environment!");
return;
}
JuiceAgent::Loader::preload(path, env, jvmti);
} catch (const std::exception& e) {
spdlog::error("[Entry] Unhandled exception in entrypoint: {}", e.what());
} catch (...) {
spdlog::error("[Entry] Unhandled unknown exception in entrypoint");
if(!jvmAttach.attach()) {
spdlog::error("Failed to attach to JVM!");
return;
}
// Get JNIEnv
JNIEnv* env = jvmAttach.get_env();
if(!env) {
spdlog::error("Failed to get JNIEnv!");
return;
}
// Get JVMTI environment
jvmtiEnv* jvmti = jvmAttach.get_jvmti();
if(!jvmti) {
spdlog::error("Failed to get JVMTI environment!");
return;
}
JuiceAgent::Loader::preload(path, env, jvmti);
}
+34 -9
View File
@@ -9,6 +9,11 @@
// Preload section
// Check parameters and load the runtime
//
// NOTE: libloader is reflectively loaded, so its unwind tables are never
// registered with the OS - a C++ exception thrown here could not be caught and
// would crash the target process. Everything below must stay exception-free and
// report problems with spdlog plus an early return.
void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) {
std::string runtime_dir_new;
@@ -33,27 +38,42 @@ void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv*
}
// Check config version
int version = cfg.get<int>("JuiceAgent.Version");
if(!cfg.contains("JuiceAgent.Version")) {
spdlog::error("[PreLoad] Missing required config key: JuiceAgent.Version");
return;
}
const int version = cfg.get<int>("JuiceAgent.Version", -1);
if(version != CONFIG_VERSION) {
spdlog::error("[PreLoad] Config version mismatch! Expected: {}, Got: {}, Please update your config!", CONFIG_VERSION, version);
return;
}
// JarLoader mode check and load jars
std::string jar_loader_mode = cfg.get<std::string>("JarLoader.Mode");
if(!cfg.contains("JarLoader.Mode")) {
spdlog::error("[PreLoad] Missing required config key: JarLoader.Mode");
return;
}
const std::string jar_loader_mode = cfg.get<std::string>("JarLoader.Mode", "");
if(jar_loader_mode == "BuiltIn") {
spdlog::info("[PreLoad] JarLoader mode: BuiltIn");
if(!load_builtin(jvmti)) {
spdlog::error("[PreLoad] Failed to load built-in jars!");
return;
}
} else if(jar_loader_mode == "CustomJar") {
spdlog::info("[PreLoad] JarLoader mode: CustomJar");
std::string jar_path = cfg.getPath("JarLoader.JarPath");
const std::string jar_path = cfg.getPath("JarLoader.JarPath", "");
if(jar_path.empty()) {
spdlog::error("[PreLoad] Missing required config key: JarLoader.JarPath (CustomJar mode)");
return;
}
if(!load_custom(jvmti, jar_path.c_str())) {
spdlog::error("[PreLoad] Failed to load custom jar: {}", jar_path);
return;
}
} else {
spdlog::error("[PreLoad] Invalid JarLoader mode: {}", jar_loader_mode);
@@ -64,7 +84,7 @@ 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<std::string>("JarLoader.Mode");
const std::string jar_loader_mode = cfg.get<std::string>("JarLoader.Mode", "");
if(jar_loader_mode == "BuiltIn") {
const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap";
@@ -74,7 +94,7 @@ void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiE
ser.add_kv("Version", cfg.get<int>("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);
@@ -86,8 +106,13 @@ void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiE
} else if(jar_loader_mode == "CustomJar") {
spdlog::info("[Initialize] JarLoader mode: CustomJar");
std::string entry_class = cfg.get<std::string>("JarLoader.EntryClass");
std::string entry_method = cfg.get<std::string>("JarLoader.EntryMethod");
const std::string entry_class = cfg.get<std::string>("JarLoader.EntryClass", "");
const std::string entry_method = cfg.get<std::string>("JarLoader.EntryMethod", "");
if(entry_class.empty() || entry_method.empty()) {
spdlog::error("[Initialize] Missing required config key: JarLoader.EntryClass / JarLoader.EntryMethod (CustomJar mode)");
return;
}
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) {
@@ -100,4 +125,4 @@ void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiE
}
spdlog::info("JuiceAgent initialized!");
}
}