From de538e00b671df7bf21f56741a6a8c85df8b9cfb Mon Sep 17 00:00:00 2001 From: Faumaray Date: Sun, 19 Oct 2025 23:18:07 +0300 Subject: [PATCH] Logger api Signed-off-by: Faumaray --- .direnv/bin/nix-direnv-reload | 19 ++++++ .envrc | 1 + .gitignore | 5 +- CMakeLists.txt | 32 ++++++++-- flake.lock | 61 +++++++++++++++++++ flake.nix | 40 +++++++++++++ include/Logging/AsyncWorker.hpp | 35 +++++++++++ include/Logging/CombinedSink.hpp | 21 +++++++ include/Logging/ConsoleSink.hpp | 15 +++++ include/Logging/FileSink.hpp | 33 ++++++++++ include/Logging/LoggerInternal.hpp | 30 ++++++++++ include/Logging/LoggerProvider.hpp | 29 +++++++++ include/Logging/LoggerRegister.hpp | 8 +++ src/Logging/AsyncWorker.cpp | 51 ++++++++++++++++ src/Logging/ConsoleSink.cpp | 34 +++++++++++ src/Logging/FileSink.cpp | 96 ++++++++++++++++++++++++++++++ src/Logging/LoggerProvider.cpp | 48 +++++++++++++++ src/Logging/LoggerRegister.cpp | 13 ++++ src/agent.cpp | 18 +++++- 19 files changed, 579 insertions(+), 10 deletions(-) create mode 100755 .direnv/bin/nix-direnv-reload create mode 100644 .envrc create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 include/Logging/AsyncWorker.hpp create mode 100644 include/Logging/CombinedSink.hpp create mode 100644 include/Logging/ConsoleSink.hpp create mode 100644 include/Logging/FileSink.hpp create mode 100644 include/Logging/LoggerInternal.hpp create mode 100644 include/Logging/LoggerProvider.hpp create mode 100644 include/Logging/LoggerRegister.hpp create mode 100644 src/Logging/AsyncWorker.cpp create mode 100644 src/Logging/ConsoleSink.cpp create mode 100644 src/Logging/FileSink.cpp create mode 100644 src/Logging/LoggerProvider.cpp create mode 100644 src/Logging/LoggerRegister.cpp diff --git a/.direnv/bin/nix-direnv-reload b/.direnv/bin/nix-direnv-reload new file mode 100755 index 0000000..db4ccda --- /dev/null +++ b/.direnv/bin/nix-direnv-reload @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -e +if [[ ! -d "/home/faumaray/Project/personal/VoidLoaderCore" ]]; then + echo "Cannot find source directory; Did you move it?" + echo "(Looking for "/home/faumaray/Project/personal/VoidLoaderCore")" + echo 'Cannot force reload with this script - use "direnv reload" manually and then try again' + exit 1 +fi + +# rebuild the cache forcefully +_nix_direnv_force_reload=1 direnv exec "/home/faumaray/Project/personal/VoidLoaderCore" true + +# Update the mtime for .envrc. +# This will cause direnv to reload again - but without re-building. +touch "/home/faumaray/Project/personal/VoidLoaderCore/.envrc" + +# Also update the timestamp of whatever profile_rc we have. +# This makes sure that we know we are up to date. +touch -r "/home/faumaray/Project/personal/VoidLoaderCore/.envrc" "/home/faumaray/Project/personal/VoidLoaderCore/.direnv"/*.rc diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..8392d15 --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake \ No newline at end of file diff --git a/.gitignore b/.gitignore index 1bea1ea..8e05da9 100644 --- a/.gitignore +++ b/.gitignore @@ -5,13 +5,14 @@ result-* # ---> C++ # Prerequisites *.d - +.direnv +.direnv/* # Compiled Object files *.slo *.lo *.o *.obj - +build # Precompiled Headers *.gch *.pch diff --git a/CMakeLists.txt b/CMakeLists.txt index 6718069..083cbbd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,10 +4,14 @@ project(VoidLoader LANGUAGES CXX) # ============================================================ # Project settings # ============================================================ -set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON) +set(BUILD_SHARED_LIBS OFF) +include(FetchContent) +add_compile_options(-ffunction-sections -fdata-sections) +add_link_options(-Wl,--gc-sections) # ============================================================ # Source / includes # ============================================================ @@ -33,6 +37,15 @@ if (DEFINED ENV{JAVA_HOME}) endif() endif() +FetchContent_Declare( + VoidLoaderApi + GIT_REPOSITORY https://git.faumaray.ru/VoidLoader/VoidLoaderApi.git + GIT_TAG main # release-1.10.0 +) + + +FetchContent_MakeAvailable(VoidLoaderApi) + # ============================================================ # Platform flags # ============================================================ @@ -47,24 +60,31 @@ endif() # ============================================================ add_library(${PROJECT_NAME} SHARED ${SOURCES}) -target_include_directories(${PROJECT_NAME} PRIVATE ${JNI_INCLUDE_DIRS}) -target_link_libraries(${PROJECT_NAME} PRIVATE ${JNI_LIBRARIES}) +target_include_directories(${PROJECT_NAME} PUBLIC ${JNI_INCLUDE_DIRS}) +target_link_libraries(${PROJECT_NAME} PUBLIC JNI::JNI VoidLoaderApi) if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") - target_link_options(${PROJECT_NAME} PRIVATE -static-libstdc++ -static-libgcc) + target_link_options(${PROJECT_NAME} PRIVATE + -Wl,-z,defs # no undefined symbols at link + -Wl,--no-undefined + -Wl,--as-needed + -static-libstdc++ # pull libstdc++ into .so + -static-libgcc # pull libgcc into .so + -Wl,-O1 + -Wl,--gc-sections + ) endif() + # Output name: YourAgent.dll / libYourAgent.so set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" OUTPUT_NAME "VoidLoader" ) - if(UNIX AND NOT APPLE) target_link_options(${PROJECT_NAME} PRIVATE -Wl,--enable-new-dtags -Wl,-rpath,\$ORIGIN) set_target_properties(${PROJECT_NAME} PROPERTIES BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") endif() - # ============================================================ # Dep bundler (Option B: auto-scan & copy non-system deps) # ============================================================ diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..5b83b57 --- /dev/null +++ b/flake.lock @@ -0,0 +1,61 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1760524057, + "narHash": "sha256-EVAqOteLBFmd7pKkb0+FIUyzTF61VKi7YmvP1tw4nEw=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "544961dfcce86422ba200ed9a0b00dd4b1486ec5", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..c04692e --- /dev/null +++ b/flake.nix @@ -0,0 +1,40 @@ +{ + description = "Gradle C++ cross-compile (Linux → Windows/Mac)"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = + { + self, + nixpkgs, + flake-utils, + }: + flake-utils.lib.eachDefaultSystem ( + system: + let + pkgs = import nixpkgs { inherit system; }; + in + { + devShells.default = pkgs.mkShell { + name = "CppShell"; + + nativeBuildInputs = with pkgs; [ + gcc15Stdenv + gcc15 + ninja + jdk + cmake + clang-tools + ]; + + buildInputs = with pkgs; [ + ]; + + shellHook = ''''; + }; + } + ); +} diff --git a/include/Logging/AsyncWorker.hpp b/include/Logging/AsyncWorker.hpp new file mode 100644 index 0000000..2dbd3f5 --- /dev/null +++ b/include/Logging/AsyncWorker.hpp @@ -0,0 +1,35 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vl::logging { + +class AsyncWorker { +public: + static AsyncWorker& instance(); + + struct Item { + std::shared_ptr sink; + Message msg; + }; + + void enqueue(Item&& item); + +private: + AsyncWorker(); + ~AsyncWorker(); + void run(std::stop_token st); + + std::mutex mtx_; + std::condition_variable_any cv_; + std::queue queue_; + std::jthread thread_; +}; + +} // namespace vl::log diff --git a/include/Logging/CombinedSink.hpp b/include/Logging/CombinedSink.hpp new file mode 100644 index 0000000..9c4a959 --- /dev/null +++ b/include/Logging/CombinedSink.hpp @@ -0,0 +1,21 @@ +#pragma once +#include +#include + +namespace vl::logging { + +class CombinedSink final : public Sink { +public: + CombinedSink(std::shared_ptr a, std::shared_ptr b) + : a_(std::move(a)), b_(std::move(b)) {} + + void write(const Message& msg) override { + a_->write(msg); + b_->write(msg); + } + +private: + std::shared_ptr a_, b_; +}; + +} // namespace vl::log diff --git a/include/Logging/ConsoleSink.hpp b/include/Logging/ConsoleSink.hpp new file mode 100644 index 0000000..180be16 --- /dev/null +++ b/include/Logging/ConsoleSink.hpp @@ -0,0 +1,15 @@ +#pragma once +#include +#include + +namespace vl::logging { + +class ConsoleSink final : public Sink { +public: + void write(const Message& msg) override; + +private: + std::mutex coutMutex_; +}; + +} // namespace vl::log diff --git a/include/Logging/FileSink.hpp b/include/Logging/FileSink.hpp new file mode 100644 index 0000000..a825b4d --- /dev/null +++ b/include/Logging/FileSink.hpp @@ -0,0 +1,33 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace vl::logging { + +// File rotation: R3 (daily + index), plus optional size cap +class FileSink final : public Sink { +public: + explicit FileSink(std::string basePath, std::uintmax_t maxBytes); + + void write(const Message& msg) override; + +private: + std::string base_; + std::uintmax_t maxBytes_; + std::ofstream out_; + std::string currentDate_; // YYYY-MM-DD + int index_{1}; + std::uintmax_t written_{0}; + + void ensureOpen(const Message& msg); + void openCurrent(); + void rotateToDate(std::string newDate); + + static std::string dateOf(const std::chrono::system_clock::time_point& tp); + static std::string filenameFor(const std::string& base, std::string_view date, int index); +}; + +} // namespace vl::log diff --git a/include/Logging/LoggerInternal.hpp b/include/Logging/LoggerInternal.hpp new file mode 100644 index 0000000..a7811d5 --- /dev/null +++ b/include/Logging/LoggerInternal.hpp @@ -0,0 +1,30 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace vl::logging { + +class LoggerInternal final : public Logger { +public: + LoggerInternal(std::string prefix, std::shared_ptr sink, Level lvl) + : prefix_(std::move(prefix)), sink_(std::move(sink)), level_(lvl) {} + + std::string_view prefix() const noexcept override { return prefix_; } + void setLevel(Level l) noexcept override { level_ = l; } + Level level() const noexcept override { return level_; } + +protected: + void enqueue(Message&& m) override { + AsyncWorker::instance().enqueue({ sink_, std::move(m) }); + } + +private: + std::string prefix_; + std::shared_ptr sink_; + Level level_; +}; + +} // namespace vl::log diff --git a/include/Logging/LoggerProvider.hpp b/include/Logging/LoggerProvider.hpp new file mode 100644 index 0000000..b71057b --- /dev/null +++ b/include/Logging/LoggerProvider.hpp @@ -0,0 +1,29 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace vl::logging { + +class LoggerProvider final : public Provider { +public: + std::shared_ptr createConsole(std::string prefix, Level lvl) override; + std::shared_ptr createFile(std::string prefix, std::string basePath, + std::uintmax_t maxBytes, Level lvl) override; + std::shared_ptr createCombined(std::string prefix, std::string basePath, + std::uintmax_t maxBytes, Level lvl) override; + + std::shared_ptr get(std::string_view prefix) const override; + bool exists(std::string_view prefix) const override; + +private: + std::shared_ptr emplaceOrGet_(std::string prefix, std::shared_ptr sink, Level lvl); + + mutable std::mutex mtx_; + std::unordered_map> byPrefix_; +}; + +} // namespace vl::log diff --git a/include/Logging/LoggerRegister.hpp b/include/Logging/LoggerRegister.hpp new file mode 100644 index 0000000..4ca98f5 --- /dev/null +++ b/include/Logging/LoggerRegister.hpp @@ -0,0 +1,8 @@ +#pragma once + +namespace vl::logging { + +// Call during VoidLoaderCore startup after it is loaded by JVM/JNI. +void init_voidloader_logger(); + +} // namespace vl::log diff --git a/src/Logging/AsyncWorker.cpp b/src/Logging/AsyncWorker.cpp new file mode 100644 index 0000000..a0f247e --- /dev/null +++ b/src/Logging/AsyncWorker.cpp @@ -0,0 +1,51 @@ +#include + +namespace vl::logging { + +AsyncWorker& AsyncWorker::instance() { + static AsyncWorker w; + return w; +} + +AsyncWorker::AsyncWorker() + : thread_([this](std::stop_token st){ run(st); }) {} + +AsyncWorker::~AsyncWorker() { + thread_.request_stop(); + cv_.notify_all(); +} + +void AsyncWorker::enqueue(Item&& item) { + { + std::scoped_lock lk(mtx_); + queue_.push(std::move(item)); + } + cv_.notify_one(); +} + +void AsyncWorker::run(std::stop_token st) { + while (!st.stop_requested()) { + Item item; + { + std::unique_lock lk(mtx_); + cv_.wait(lk, st, [this]{ return !queue_.empty(); }); + if (st.stop_requested()) break; + item = std::move(queue_.front()); + queue_.pop(); + } + if (item.sink) item.sink->write(item.msg); + } + // drain + for (;;) { + Item item; + { + std::scoped_lock lk(mtx_); + if (queue_.empty()) break; + item = std::move(queue_.front()); + queue_.pop(); + } + if (item.sink) item.sink->write(item.msg); + } +} + +} // namespace vl::log diff --git a/src/Logging/ConsoleSink.cpp b/src/Logging/ConsoleSink.cpp new file mode 100644 index 0000000..e11593d --- /dev/null +++ b/src/Logging/ConsoleSink.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include +#include + +namespace vl::logging { + +static std::string formatTimestamp(const std::chrono::system_clock::time_point& tp) { + const auto tt = std::chrono::system_clock::to_time_t(tp); + std::tm tm{}; +#if defined(_WIN32) + localtime_s(&tm, &tt); +#else + localtime_r(&tt, &tm); +#endif + char buf[32]; + std::strftime(buf, sizeof(buf), "%F %T", &tm); + return std::string{buf}; +} + +void ConsoleSink::write(const Message& msg) { + const auto line = std::format("{} {} {:>5} {}\n", + formatTimestamp(msg.ts), + msg.prefix, + toString(msg.level), + msg.text); + std::scoped_lock lk(coutMutex_); + std::cout << line; + std::cout.flush(); +} + +} // namespace vl::log diff --git a/src/Logging/FileSink.cpp b/src/Logging/FileSink.cpp new file mode 100644 index 0000000..00eaa63 --- /dev/null +++ b/src/Logging/FileSink.cpp @@ -0,0 +1,96 @@ +#include +#include +#include +#include +#include +#include +#include + +namespace vl::logging { +namespace fs = std::filesystem; + +static std::string formatTimestamp(const std::chrono::system_clock::time_point& tp) { + const auto tt = std::chrono::system_clock::to_time_t(tp); + std::tm tm{}; +#if defined(_WIN32) + localtime_s(&tm, &tt); +#else + localtime_r(&tt, &tm); +#endif + char buf[32]; + std::strftime(buf, sizeof(buf), "%F %T", &tm); + return std::string{buf}; +} + +static std::string ymdOf(const std::chrono::system_clock::time_point& tp) { + const auto tt = std::chrono::system_clock::to_time_t(tp); + std::tm tm{}; +#if defined(_WIN32) + localtime_s(&tm, &tt); +#else + localtime_r(&tt, &tm); +#endif + char buf[16]; + std::strftime(buf, sizeof(buf), "%F", &tm); // YYYY-MM-DD + return std::string{buf}; +} + +FileSink::FileSink(std::string basePath, std::uintmax_t maxBytes) + : base_(std::move(basePath)), maxBytes_(maxBytes) { + fs::path p(base_); + if (p.has_parent_path()) fs::create_directories(p.parent_path()); +} + +std::string FileSink::dateOf(const std::chrono::system_clock::time_point& tp) { return ymdOf(tp); } + +std::string FileSink::filenameFor(const std::string& base, std::string_view date, int index) { + // base_YYYY-MM-DD_index.log + return std::format("{}_{}_{}.log", base, date, index); +} + +void FileSink::openCurrent() { + const auto name = filenameFor(base_, currentDate_, index_); + out_.close(); + out_.clear(); + out_.open(name, std::ios::out | std::ios::app | std::ios::binary); + if (!out_) throw std::runtime_error(std::format("FileSink: cannot open '{}'", name)); + try { written_ = fs::file_size(name); } catch (...) { written_ = 0; } +} + +void FileSink::rotateToDate(std::string newDate) { + currentDate_ = std::move(newDate); + index_ = 1; + openCurrent(); +} + +void FileSink::ensureOpen(const Message& msg) { + const auto msgDate = dateOf(msg.ts); + if (!out_.is_open()) { + currentDate_ = msgDate; + index_ = 1; + openCurrent(); + return; + } + if (msgDate != currentDate_) { + rotateToDate(msgDate); + return; + } + if (maxBytes_ > 0 && written_ >= maxBytes_) { + ++index_; + openCurrent(); + } +} + +void FileSink::write(const Message& msg) { + ensureOpen(msg); + const auto line = std::format("{} {} {:>5} {}\n", + formatTimestamp(msg.ts), + msg.prefix, + toString(msg.level), + msg.text); + out_ << line; + written_ += static_cast(line.size()); + out_.flush(); +} + +} // namespace vl::log diff --git a/src/Logging/LoggerProvider.cpp b/src/Logging/LoggerProvider.cpp new file mode 100644 index 0000000..d3d7020 --- /dev/null +++ b/src/Logging/LoggerProvider.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +namespace vl::logging { + +std::shared_ptr LoggerProvider::emplaceOrGet_(std::string prefix, + std::shared_ptr sink, + Level lvl) { + std::scoped_lock lk(mtx_); + if (auto it = byPrefix_.find(prefix); it != byPrefix_.end()) return it->second; // P3 + auto lg = std::make_shared(prefix, std::move(sink), lvl); + byPrefix_.emplace(std::move(prefix), lg); + return lg; +} + +std::shared_ptr LoggerProvider::createConsole(std::string prefix, Level lvl) { + return emplaceOrGet_(std::move(prefix), std::make_shared(), lvl); +} + +std::shared_ptr LoggerProvider::createFile(std::string prefix, std::string basePath, + std::uintmax_t maxBytes, Level lvl) { + return emplaceOrGet_(std::move(prefix), std::make_shared(std::move(basePath), maxBytes), lvl); +} + +std::shared_ptr LoggerProvider::createCombined(std::string prefix, std::string basePath, + std::uintmax_t maxBytes, Level lvl) { + auto a = std::make_shared(); + auto b = std::make_shared(std::move(basePath), maxBytes); + auto s = std::make_shared(std::move(a), std::move(b)); + return emplaceOrGet_(std::move(prefix), std::move(s), lvl); +} + +std::shared_ptr LoggerProvider::get(std::string_view prefix) const { + std::scoped_lock lk(mtx_); + auto it = byPrefix_.find(std::string(prefix)); + if (it == byPrefix_.end()) throw std::runtime_error("LoggerProvider::get: unknown prefix"); + return it->second; +} + +bool LoggerProvider::exists(std::string_view prefix) const { + std::scoped_lock lk(mtx_); + return byPrefix_.contains(std::string(prefix)); +} + +} // namespace vl::log diff --git a/src/Logging/LoggerRegister.cpp b/src/Logging/LoggerRegister.cpp new file mode 100644 index 0000000..90d14fe --- /dev/null +++ b/src/Logging/LoggerRegister.cpp @@ -0,0 +1,13 @@ +#include +#include +#include + +namespace vl::logging { + +static LoggerProvider g_coreProvider; // internal to the Core library + +void init_voidloader_logger() { + LoggerManager::instance().setProvider(&g_coreProvider); +} + +} // namespace vl::log diff --git a/src/agent.cpp b/src/agent.cpp index 7327314..45a8bb8 100644 --- a/src/agent.cpp +++ b/src/agent.cpp @@ -3,9 +3,11 @@ #include #include #include +#include "Logging/LoggerManager.hpp" #include "jvmti_handler.h" #include "class_transformer.h" #include "mod_manager.h" +#include // Global variables defined ONLY here namespace { @@ -96,13 +98,25 @@ extern "C" JNIEXPORT void JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeAgentSt } extern "C" JNIEXPORT void JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeAgentInit(JNIEnv* env, jclass clazz, jstring args, jobject instrumentation) { - std::cout << "[VoidLoader] Native agent initialized with Instrumentation" << std::endl; + try { + // Register logger provider in API singleton + vl::logging::init_voidloader_logger(); + } + catch (const std::exception& ex) { + // If something fails, return an error code, JVM will abort agent load + fprintf(stderr, "[VoidLoaderCore] Logger initialization failed: %s\n", ex.what()); + return; + } + auto logger = vl::logging::LoggerManager::instance().createConsole("[Core]"); + + logger->info("Native agent initialized with Instrumentation"); + // Initialize mod manager - but don't block g_modManager.discoverMods("mods"); JavaVM* vm; auto error = env->GetJavaVM(&vm); if (error != JNI_OK) { - std::cerr << "[VoidLoader] FATAL: Unable to get JavaVM from JNIEnv!" << std::endl; + logger->error("Unable to get JavaVM from JNIEnv"); return; } Agent_OnLoad(vm, nullptr, nullptr);