diff --git a/include/Void/Plugin/CAbi.h b/include/Void/Plugin/CAbi.h new file mode 100644 index 0000000..cfe6db3 --- /dev/null +++ b/include/Void/Plugin/CAbi.h @@ -0,0 +1,184 @@ +#ifndef VOID_PLUGIN_CABI_H +#define VOID_PLUGIN_CABI_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define VOID_CABI_MAJOR_V1 UINT32_C(1) +#define VOID_CABI_MINOR_V1 UINT32_C(0) +#define VOID_MODULE_QUERY_SYMBOL_V1 "void_module_query_v1" + +#define VOID_CAP_STATELESS_RELOAD (UINT64_C(1) << 0) +#define VOID_CAP_STATEFUL_CHECKPOINT (UINT64_C(1) << 1) +#define VOID_CAP_ASYNC_OPS (UINT64_C(1) << 2) +#define VOID_CAP_SERVICE_INTERFACES (UINT64_C(1) << 3) + +enum void_status_v1 { + VOID_STATUS_OK = 0, + VOID_STATUS_INVALID_ARGUMENT = 1, + VOID_STATUS_NOT_FOUND = 2, + VOID_STATUS_CONFLICT = 3, + VOID_STATUS_CANCELLED = 4, + VOID_STATUS_TIMEOUT = 5, + VOID_STATUS_OVERLOADED = 6, + VOID_STATUS_UNSUPPORTED = 7, + VOID_STATUS_CORRUPT = 8, + VOID_STATUS_EXHAUSTED = 9, + VOID_STATUS_INTERNAL = 10, + VOID_STATUS_NOT_READY = 11, + VOID_STATUS_QUIESCING = 12, + VOID_STATUS_STATE_REJECTED = 13, + VOID_STATUS_RESTART_REQUIRED = 14 +}; + +enum void_activation_policy_v1 { + VOID_POLICY_RELOADABLE = 0, + VOID_POLICY_RESTART_REQUIRED = 1, + VOID_POLICY_INSTALLER_REQUIRED = 2 +}; + +typedef struct void_module_handle void_module_handle; +typedef struct void_operation_handle void_operation_handle; +typedef struct void_host_context void_host_context; + +typedef struct void_bytes_v1 { + const uint8_t* data; + uint64_t size; +} void_bytes_v1; + +typedef struct void_owned_bytes_v1 { + const uint8_t* data; + uint64_t size; + void (*release)(void* release_ctx, const uint8_t* data, uint64_t size); + void* release_ctx; +} void_owned_bytes_v1; + +typedef struct void_interface_id_v1 { + uint8_t bytes[16]; +} void_interface_id_v1; + +typedef struct void_dependency_v1 { + const char* module_id; + const char* version_range; + uint8_t optional_dep; + uint8_t reserved[7]; +} void_dependency_v1; + +typedef struct void_module_info_v1 { + uint32_t struct_size; + uint32_t reserved; + const char* module_id; + const char* version; + uint32_t activation_policy; + uint32_t state_schema_version; + const void_dependency_v1* dependencies; + uint64_t dependency_count; +} void_module_info_v1; + +typedef struct void_op_options_v1 { + uint32_t struct_size; + uint32_t flags; + uint64_t deadline_ns; + uint8_t stop_requested; + uint8_t reserved[7]; +} void_op_options_v1; + +typedef struct void_error_detail_v1 { + uint32_t struct_size; + int32_t status; + const char* message; + void (*release)(void* release_ctx, const char* message); + void* release_ctx; +} void_error_detail_v1; + +typedef struct void_interface_view_v1 { + uint32_t struct_size; + uint32_t major; + uint32_t minor; + uint32_t table_size; + const void* function_table; +} void_interface_view_v1; + +typedef struct void_host_api_v1 { + uint32_t struct_size; + uint32_t abi_major; + uint32_t abi_minor; + uint32_t reserved; + void_host_context* host_ctx; + uint64_t generation; + uint64_t (*monotonic_now_ns)(void_host_context* ctx); + int32_t (*acquire_activity_pin)(void_host_context* ctx, uint64_t generation); + void (*release_activity_pin)(void_host_context* ctx, uint64_t generation); + void (*log_message)(void_host_context* ctx, int32_t level, const char* msg); +} void_host_api_v1; + +typedef void (*void_async_complete_fn)(void* user_ctx, + int32_t status, + const void_bytes_v1* result_bytes); + +typedef struct void_module_api_v1 { + uint32_t struct_size; + uint32_t abi_major; + uint32_t abi_minor; + uint32_t reserved; + uint64_t capabilities; + + int32_t (*get_info)(void_module_info_v1* out_info); + int32_t (*create)(const void_host_api_v1* host_api, + void_module_handle** out_handle); + int32_t (*activate)(void_module_handle* handle, + void_bytes_v1 config, + void_error_detail_v1* out_err); + int32_t (*readiness)(void_module_handle* handle, + uint32_t* out_ready, + void_error_detail_v1* out_err); + int32_t (*quiesce)(void_module_handle* handle, + const void_op_options_v1* opts, + void_error_detail_v1* out_err); + int32_t (*resume)(void_module_handle* handle, void_error_detail_v1* out_err); + int32_t (*checkpoint)(void_module_handle* handle, + const void_op_options_v1* opts, + void_owned_bytes_v1* out_state, + void_error_detail_v1* out_err); + int32_t (*restore)(void_module_handle* handle, + void_bytes_v1 state, + void_error_detail_v1* out_err); + int32_t (*query_interface)(void_module_handle* handle, + const void_interface_id_v1* iface_id, + uint32_t min_major, + uint32_t min_table_size, + void_interface_view_v1* out_view); + void (*release_interface)(void_module_handle* handle, + const void_interface_id_v1* iface_id, + const void_interface_view_v1* view); + int32_t (*submit_async)(void_module_handle* handle, + uint32_t op_kind, + void_bytes_v1 payload, + const void_op_options_v1* opts, + void_async_complete_fn cb, + void* cb_ctx, + void_operation_handle** out_op, + void_error_detail_v1* out_err); + int32_t (*cancel_async)(void_module_handle* handle, + void_operation_handle* op); + void (*release_async)(void_module_handle* handle, + void_operation_handle* op); + int32_t (*request_stop)(void_module_handle* handle); + int32_t (*deactivate)(void_module_handle* handle); + void (*destroy)(void_module_handle* handle); +} void_module_api_v1; + +#define VOID_MODULE_API_V1_MIN_SIZE sizeof(void_module_api_v1) + +typedef int32_t (*void_module_query_v1_fn)(uint32_t host_struct_size, + void_module_api_v1* out_api); + +#ifdef __cplusplus +} +#endif + +#endif /* VOID_PLUGIN_CABI_H */ diff --git a/include/Void/Plugin/CAbiAdapter.hpp b/include/Void/Plugin/CAbiAdapter.hpp new file mode 100644 index 0000000..7b72d81 --- /dev/null +++ b/include/Void/Plugin/CAbiAdapter.hpp @@ -0,0 +1,165 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Plugin +{ + namespace detail + { + inline void free_cabi_cstring(void* /*ctx*/, const char* msg) + { + delete[] msg; + } + + inline void set_error_detail(void_error_detail_v1* out_err, + std::int32_t status, + const std::string& msg) noexcept + { + if (out_err == nullptr || + out_err->struct_size < sizeof(void_error_detail_v1)) { + return; + } + out_err->status = status; + try { + char* buf = new char[msg.size() + 1]; + std::memcpy(buf, msg.c_str(), msg.size() + 1); + out_err->message = buf; + out_err->release = &free_cabi_cstring; + out_err->release_ctx = nullptr; + } catch (...) { + out_err->message = nullptr; + out_err->release = nullptr; + out_err->release_ctx = nullptr; + } + } + + inline void free_cabi_bytes(void* /*ctx*/, const std::uint8_t* data, + std::uint64_t /*size*/) + { + delete[] data; + } + } // namespace detail + + /// Exception-safe bridge adapting a C++ IModule instance to the C11 + /// void_module_api_v1 contract without letting C++ exceptions unwind across C. + struct CModuleAdapterBox { + std::unique_ptr module; + Service::ServiceRegistry fallback_registry; + ModuleHost host{fallback_registry}; + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + }; + + template + [[nodiscard]] inline std::int32_t + invoke_contained(void_error_detail_v1* out_err, CallbackFn&& fn) noexcept + { + try { + return fn(); + } catch (const std::exception& ex) { + detail::set_error_detail(out_err, VOID_STATUS_INTERNAL, ex.what()); + return VOID_STATUS_INTERNAL; + } catch (...) { + detail::set_error_detail(out_err, VOID_STATUS_INTERNAL, + "CAbiAdapter: unknown C++ exception"); + return VOID_STATUS_INTERNAL; + } + } + + [[nodiscard]] inline std::int32_t + adapt_checkpoint(CModuleAdapterBox* box, + void_owned_bytes_v1* out_state, + void_error_detail_v1* out_err) noexcept + { + if (box == nullptr || !box->module || out_state == nullptr) { + return VOID_STATUS_INVALID_ARGUMENT; + } + return invoke_contained(out_err, [&]() -> std::int32_t { + const auto json = Void::Json::serialize(box->module->checkpoint()); + auto* buf = new std::uint8_t[json.size()]; + if (!json.empty()) { + std::memcpy(buf, json.data(), json.size()); + } + out_state->data = buf; + out_state->size = static_cast(json.size()); + out_state->release = &detail::free_cabi_bytes; + out_state->release_ctx = nullptr; + return VOID_STATUS_OK; + }); + } + + [[nodiscard]] inline std::int32_t + adapt_restore(CModuleAdapterBox* box, void_bytes_v1 state, + void_error_detail_v1* out_err) noexcept + { + if (box == nullptr || !box->module) { + return VOID_STATUS_INVALID_ARGUMENT; + } + return invoke_contained(out_err, [&]() -> std::int32_t { + const std::string_view sv{ + reinterpret_cast(state.data), + static_cast(state.size)}; + const auto parsed = Void::Json::parse(sv); + if (!parsed.has_value()) { + detail::set_error_detail(out_err, VOID_STATUS_CORRUPT, + parsed.error().message); + return VOID_STATUS_CORRUPT; + } + const auto res = box->module->restore(*parsed); + if (!res.has_value()) { + detail::set_error_detail(out_err, VOID_STATUS_STATE_REJECTED, + res.error().message()); + return VOID_STATUS_STATE_REJECTED; + } + return VOID_STATUS_OK; + }); + } + + [[nodiscard]] inline std::int32_t + adapt_activate(CModuleAdapterBox* box, + void_error_detail_v1* out_err) noexcept + { + if (box == nullptr || !box->module) { + return VOID_STATUS_INVALID_ARGUMENT; + } + return invoke_contained(out_err, [&]() -> std::int32_t { + const auto r = box->module->activate(box->host); + if (!r.has_value()) { + detail::set_error_detail(out_err, VOID_STATUS_INTERNAL, + r.error().message()); + return VOID_STATUS_INTERNAL; + } + return VOID_STATUS_OK; + }); + } + + [[nodiscard]] inline std::int32_t + adapt_readiness(CModuleAdapterBox* box, std::uint32_t* out_ready, + void_error_detail_v1* out_err) noexcept + { + if (box == nullptr || !box->module || out_ready == nullptr) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_ready = 0; + return invoke_contained(out_err, [&]() -> std::int32_t { + const auto r = box->module->readiness(); + *out_ready = r.ready ? 1u : 0u; + if (!r.ready && !r.detail.empty()) { + detail::set_error_detail(out_err, VOID_STATUS_NOT_READY, + r.detail); + } + return VOID_STATUS_OK; + }); + } + +} // namespace Void::Plugin diff --git a/include/Void/Plugin/Host.hpp b/include/Void/Plugin/Host.hpp new file mode 100644 index 0000000..b74c1b4 --- /dev/null +++ b/include/Void/Plugin/Host.hpp @@ -0,0 +1,350 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Plugin +{ + enum class PluginErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + file_not_found = 2, + dlopen_failed = 3, + symbol_missing = 4, + abi_mismatch = 5, + activation_failed = 6, + not_ready = 7, + quiesce_failed = 8, + resume_degraded = 9, + checkpoint_failed = 10, + restore_failed = 11, + restart_required = 12, + cycle_detected = 13, + missing_dependency = 14, + retention_limit = 15, + budget_exceeded = 16, + conflict = 17, + cancelled = 18, + timeout = 19, + not_found = 20, + internal = 21, + }; + + [[nodiscard]] inline Void::Result::Error + make_plugin_error(PluginErrorCode code, std::string message = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case PluginErrorCode::none: + kind = ErrorKind::internal; + break; + case PluginErrorCode::invalid_argument: + case PluginErrorCode::abi_mismatch: + case PluginErrorCode::cycle_detected: + kind = ErrorKind::invalid_argument; + break; + case PluginErrorCode::file_not_found: + case PluginErrorCode::symbol_missing: + case PluginErrorCode::missing_dependency: + case PluginErrorCode::not_found: + kind = ErrorKind::not_found; + break; + case PluginErrorCode::dlopen_failed: + kind = ErrorKind::io; + break; + case PluginErrorCode::conflict: + case PluginErrorCode::restart_required: + kind = ErrorKind::conflict; + break; + case PluginErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case PluginErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case PluginErrorCode::retention_limit: + case PluginErrorCode::budget_exceeded: + kind = ErrorKind::exhausted; + break; + case PluginErrorCode::activation_failed: + case PluginErrorCode::not_ready: + case PluginErrorCode::quiesce_failed: + case PluginErrorCode::resume_degraded: + case PluginErrorCode::checkpoint_failed: + case PluginErrorCode::restore_failed: + case PluginErrorCode::internal: + kind = ErrorKind::internal; + break; + } + return Error{kind, std::move(message), + ErrorCode{Void::Result::kPluginErrorDomain, + static_cast(code)}}; + } + + struct PluginHostLimits { + std::size_t max_modules{64}; + std::size_t max_interfaces_per_module{256}; + std::size_t max_retained_generations{4}; + std::size_t max_mapped_bytes_per_module{64 * 1024 * 1024}; + std::size_t max_checkpoint_bytes{4 * 1024 * 1024}; + std::size_t max_config_bytes{1 * 1024 * 1024}; + std::size_t max_async_activities{1024}; + std::size_t max_pending_callbacks{256}; + std::chrono::milliseconds prepare_timeout{ + std::chrono::seconds{5}}; + std::chrono::milliseconds quiesce_timeout{ + std::chrono::seconds{5}}; + std::chrono::milliseconds readiness_timeout{ + std::chrono::seconds{10}}; + std::chrono::milliseconds total_reload_timeout{ + std::chrono::seconds{30}}; + bool allow_safe_dlclose{false}; + }; + + enum class GenerationHealth : std::uint8_t { + Healthy = 0, + Quiescing, + Degraded, + Retiring, + Retired, + }; + + struct GenerationSummary { + std::uint64_t generation{0}; + std::string module_id{}; + std::string version{}; + std::uint64_t image_bytes{0}; + std::size_t external_refs{0}; + std::size_t activity_pins{0}; + GenerationHealth health{GenerationHealth::Healthy}; + bool dlclosed{false}; + }; + + struct ReloadEvent { + std::string module_id{}; + std::uint64_t generation{0}; + bool rollback{false}; + std::string detail{}; + }; + + struct BatchModuleSpec { + std::filesystem::path path{}; + std::string config{}; + }; + + namespace detail + { + struct GenerationRecord; + } + + /// RAII pin holding an async activity count on a generation. Destroying + /// it may schedule asynchronous host retirement if no refs/pins remain. + class ActivityPin + { + public: + + ActivityPin() noexcept = default; + ~ActivityPin(); + ActivityPin(ActivityPin&& other) noexcept; + ActivityPin& operator=(ActivityPin&& other) noexcept; + ActivityPin(const ActivityPin&) = delete; + ActivityPin& operator=(const ActivityPin&) = delete; + + [[nodiscard]] explicit operator bool() const noexcept + { + return m_rec != nullptr; + } + [[nodiscard]] std::uint64_t generation() const noexcept; + + private: + + friend class CModuleHost; + friend class GenerationLease; + explicit ActivityPin(std::shared_ptr rec) + : m_rec(std::move(rec)) + { + } + std::shared_ptr m_rec{}; + }; + + /// Owning lease to a queried C interface function table from an exact + /// generation. Releases via release_interface before dropping generation ref. + class InterfaceLease + { + public: + + InterfaceLease() noexcept = default; + ~InterfaceLease(); + InterfaceLease(InterfaceLease&& other) noexcept; + InterfaceLease& operator=(InterfaceLease&& other) noexcept; + InterfaceLease(const InterfaceLease&) = delete; + InterfaceLease& operator=(const InterfaceLease&) = delete; + + [[nodiscard]] explicit operator bool() const noexcept + { + return m_view.function_table != nullptr; + } + + template + [[nodiscard]] const TableT* table() const noexcept + { + if (m_view.function_table == nullptr || + m_view.table_size < sizeof(TableT)) { + return nullptr; + } + return static_cast(m_view.function_table); + } + + [[nodiscard]] const void_interface_view_v1& view() const noexcept + { + return m_view; + } + [[nodiscard]] std::uint64_t generation() const noexcept; + + private: + + friend class GenerationLease; + InterfaceLease(std::shared_ptr rec, + void_interface_id_v1 id, + void_interface_view_v1 view) noexcept + : m_rec(std::move(rec)), m_id(id), m_view(view) + { + } + + std::shared_ptr m_rec{}; + void_interface_id_v1 m_id{}; + void_interface_view_v1 m_view{}; + }; + + /// Owning generation reference acquired from CModuleHost. Prevents module + /// deactivation and dlclose while held, and supports activity pinning, + /// C interface querying, and bounded async operation submission. + class GenerationLease + { + public: + + GenerationLease() noexcept = default; + ~GenerationLease(); + GenerationLease(const GenerationLease& other); + GenerationLease& operator=(const GenerationLease& other); + GenerationLease(GenerationLease&& other) noexcept; + GenerationLease& operator=(GenerationLease&& other) noexcept; + + [[nodiscard]] explicit operator bool() const noexcept + { + return m_rec != nullptr; + } + [[nodiscard]] std::uint64_t generation() const noexcept; + [[nodiscard]] std::string_view module_id() const noexcept; + [[nodiscard]] std::string_view version() const noexcept; + [[nodiscard]] GenerationHealth health() const noexcept; + + [[nodiscard]] ActivityPin acquire_activity_pin() const; + + [[nodiscard]] Void::Result::Result + query_interface(const void_interface_id_v1& id, + std::uint32_t min_major, + std::uint32_t min_table_size) const; + + [[nodiscard]] Void::Result::Result> + run_async(std::uint32_t op_kind, + const std::vector& payload, + Void::Async::OperationOptions options = {}) const; + + private: + + friend class CModuleHost; + struct AlreadyRefCountedTag {}; + explicit GenerationLease( + std::shared_ptr rec); + GenerationLease(std::shared_ptr rec, + AlreadyRefCountedTag) noexcept + : m_rec(std::move(rec)) + { + } + + std::shared_ptr m_rec{}; + }; + + /// Hardened C-ABI module host implementing size/version negotiation, + /// independent external_refs & activity_pins, host-thread retirement queue, + /// unlocked quiesce/checkpoint/restore/readiness/resume reload, and + /// dependency-ordered batch loading. + class CModuleHost + { + public: + + struct Impl; + + explicit CModuleHost( + PluginHostLimits limits = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + ~CModuleHost(); + + CModuleHost(const CModuleHost&) = delete; + CModuleHost& operator=(const CModuleHost&) = delete; + + [[nodiscard]] Void::Result::Result + load(const std::filesystem::path& path, + std::string_view config = {}, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result> + load_batch(const std::vector& specs, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + replace(std::string_view module_id, + const std::filesystem::path& new_path, + std::string_view config = {}, + std::optional expected_generation = + std::nullopt, + Void::Async::OperationOptions options = {}, + std::function( + const GenerationLease&)> + on_publish_locked = {}); + + [[nodiscard]] Void::Result::Result + unload(std::string_view module_id); + + [[nodiscard]] GenerationLease + acquire(std::string_view module_id) const; + + [[nodiscard]] std::vector + retained_generations(std::string_view module_id) const; + + [[nodiscard]] std::size_t + mapped_bytes(std::string_view module_id) const; + + std::size_t add_observer(std::function cb); + void remove_observer(std::size_t id); + + /// Drain retirement queue and shutdown background retirement worker. + void close_and_join(); + + private: + + std::shared_ptr m_impl; + }; + +} // namespace Void::Plugin diff --git a/include/Void/Plugin/Manager.hpp b/include/Void/Plugin/Manager.hpp index dc4bb76..236c2b1 100644 --- a/include/Void/Plugin/Manager.hpp +++ b/include/Void/Plugin/Manager.hpp @@ -215,18 +215,20 @@ namespace Void::Plugin std::filesystem::path path; std::atomic> current; bool watched{false}; + std::mutex reload_mutex; }; Entry* find(std::string_view name) const; - std::expected - reload_locked(Entry& entry, std::string_view name, - const std::filesystem::path& sourcePath); + std::shared_ptr find_shared(std::string_view name) const; + std::expected reload_entry_unlocked( + const std::shared_ptr& entry, std::string_view name, + const std::optional& newPath); std::vector> reload_callbacks_locked() const; Options m_options; - mutable std::mutex m_mutex; // guards the registry map + reloads - std::unordered_map> m_plugins; + mutable std::mutex m_mutex; // guards the registry map & observer list + std::unordered_map> m_plugins; std::vector>> m_on_reloaded; diff --git a/src/Plugin/Host.cpp b/src/Plugin/Host.cpp new file mode 100644 index 0000000..046dd8d --- /dev/null +++ b/src/Plugin/Host.cpp @@ -0,0 +1,1647 @@ +#include + +#include +#include + +#if defined(__unix__) || defined(__APPLE__) +#include +#define VOID_HOST_HAS_DLOPEN 1 +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Plugin +{ + namespace + { + PluginErrorCode map_cabi_status(std::int32_t status, + PluginErrorCode fallback) noexcept + { + switch (status) { + case VOID_STATUS_INVALID_ARGUMENT: + return PluginErrorCode::invalid_argument; + case VOID_STATUS_NOT_FOUND: + return PluginErrorCode::not_found; + case VOID_STATUS_CONFLICT: + return PluginErrorCode::conflict; + case VOID_STATUS_CANCELLED: + return PluginErrorCode::cancelled; + case VOID_STATUS_TIMEOUT: + return PluginErrorCode::timeout; + case VOID_STATUS_OVERLOADED: + case VOID_STATUS_EXHAUSTED: + return PluginErrorCode::budget_exceeded; + case VOID_STATUS_UNSUPPORTED: + return PluginErrorCode::abi_mismatch; + case VOID_STATUS_NOT_READY: + return PluginErrorCode::not_ready; + case VOID_STATUS_QUIESCING: + return PluginErrorCode::quiesce_failed; + case VOID_STATUS_STATE_REJECTED: + return PluginErrorCode::restore_failed; + case VOID_STATUS_RESTART_REQUIRED: + return PluginErrorCode::restart_required; + default: + return fallback; + } + } + + std::string consume_error_detail(void_error_detail_v1& err) + { + std::string msg; + if (err.message != nullptr) { + const std::size_t len = ::strnlen(err.message, 1024); + msg.assign(err.message, len); + if (err.release != nullptr) { + err.release(err.release_ctx, err.message); + } + } + err.message = nullptr; + err.release = nullptr; + return msg; + } + + bool is_all_zero(const void* data, std::size_t n) noexcept + { + const auto* bytes = static_cast(data); + for (std::size_t i = 0; i < n; ++i) { + if (bytes[i] != 0) { + return false; + } + } + return true; + } + + struct DependencySpec { + std::string module_id{}; + std::string version_range{}; + bool optional_dep{false}; + }; + } // namespace + + struct detail::GenerationRecord + : public std::enable_shared_from_this { + struct HostCtx { + std::weak_ptr host_impl; + std::weak_ptr rec; + }; + + std::weak_ptr host_impl{}; + HostCtx host_api_ctx{}; + std::uint64_t generation{0}; + std::string module_id{}; + std::string version{}; + std::uint64_t image_bytes{0}; + void* dl_handle{nullptr}; + void_module_api_v1 api{}; + void_module_handle* mod_handle{nullptr}; + std::vector dependencies{}; + std::uint32_t activation_policy{VOID_POLICY_RELOADABLE}; + std::atomic health{GenerationHealth::Healthy}; + std::atomic external_refs{0}; + std::atomic activity_pins{0}; + std::atomic active_async_ops{0}; + std::atomic retire_requested{false}; + std::atomic retired_enqueued{false}; + std::atomic destroyed{false}; + std::atomic dlclosed{false}; + bool allow_dlclose{false}; + bool activated{false}; + + void add_external_ref() noexcept + { + external_refs.fetch_add(1, std::memory_order_acq_rel); + } + + void release_external_ref() noexcept + { + if (external_refs.fetch_sub(1, std::memory_order_seq_cst) == 1) { + maybe_enqueue_retire(); + } + } + + void add_activity_pin() noexcept + { + activity_pins.fetch_add(1, std::memory_order_acq_rel); + } + + void release_activity_pin() noexcept + { + if (activity_pins.fetch_sub(1, std::memory_order_seq_cst) == 1) { + maybe_enqueue_retire(); + } + } + + void maybe_enqueue_retire() noexcept; + }; + + struct CModuleHost::Impl + : public std::enable_shared_from_this { + struct ModuleSlot { + std::mutex reload_mu{}; + std::shared_ptr current{}; + std::vector> + retained{}; + }; + + explicit Impl(PluginHostLimits l, + const Void::Time::MonotonicClock& c) + : limits(l), clock(&c) + { + retire_thread = std::thread([this] { run_retire_loop(); }); + } + + ~Impl() { shutdown(); } + + void enqueue_retire(std::shared_ptr rec) + { + { + std::lock_guard lk{retire_mu}; + if (retire_stop) { + return; + } + retire_queue.push_back(std::move(rec)); + } + retire_cv.notify_one(); + } + + void run_retire_loop() + { + for (;;) { + std::shared_ptr rec; + { + std::unique_lock lk{retire_mu}; + retire_cv.wait(lk, [this] { + return retire_stop || !retire_queue.empty(); + }); + if (retire_stop && retire_queue.empty()) { + return; + } + rec = std::move(retire_queue.front()); + retire_queue.pop_front(); + } + perform_retire(*rec); + } + } + + void perform_retire(detail::GenerationRecord& rec) noexcept + { + if (rec.external_refs.load(std::memory_order_seq_cst) > 0 || + rec.activity_pins.load(std::memory_order_seq_cst) > 0) { + return; + } + bool exp = false; + if (!rec.destroyed.compare_exchange_strong( + exp, true, std::memory_order_acq_rel)) { + return; + } + rec.health.store(GenerationHealth::Retired, + std::memory_order_release); + if (rec.mod_handle != nullptr) { + if (rec.activated && rec.api.deactivate != nullptr) { + (void)rec.api.deactivate(rec.mod_handle); + } + if (rec.api.destroy != nullptr) { + rec.api.destroy(rec.mod_handle); + } + rec.mod_handle = nullptr; + } +#ifdef VOID_HOST_HAS_DLOPEN + if (rec.allow_dlclose && rec.dl_handle != nullptr) { + dlclose(rec.dl_handle); + rec.dl_handle = nullptr; + rec.dlclosed.store(true, std::memory_order_release); + } +#endif + } + + void shutdown() + { + std::vector> slots; + { + std::lock_guard lk{map_mu}; + closing = true; + for (auto& [_, s] : modules) { + slots.push_back(s); + } + } + for (auto& slot : slots) { + std::lock_guard rlk{slot->reload_mu}; + std::shared_ptr prev; + { + std::lock_guard lk{map_mu}; + prev = std::exchange(slot->current, nullptr); + } + if (prev) { + prev->retire_requested.store(true, + std::memory_order_seq_cst); + if (prev->api.request_stop != nullptr && + prev->mod_handle != nullptr) { + (void)prev->api.request_stop(prev->mod_handle); + } + prev->release_external_ref(); + } + } + { + std::lock_guard lk{retire_mu}; + retire_stop = true; + } + retire_cv.notify_all(); + if (retire_thread.joinable()) { + retire_thread.join(); + } + // Prune destroyed generations once retirement worker finished; any + // generation still holding external_refs or activity_pins stays + // un-dlclosed intentionally. + for (auto& slot : slots) { + std::lock_guard rlk{slot->reload_mu}; + for (auto& r : slot->retained) { + if (r && + r->external_refs.load(std::memory_order_seq_cst) == + 0 && + r->activity_pins.load(std::memory_order_seq_cst) == + 0) { + perform_retire(*r); + } + } + } + } + + static std::uint64_t host_monotonic_ns(void_host_context* ctx) + { + auto* hctx = + reinterpret_cast(ctx); + if (hctx != nullptr) { + if (auto impl = hctx->host_impl.lock()) { + return static_cast(std::max( + 0, impl->clock->now().time_since_epoch().count())); + } + } + return 0; + } + + static std::int32_t host_acquire_pin(void_host_context* ctx, + std::uint64_t generation) + { + auto* hctx = + reinterpret_cast(ctx); + if (hctx == nullptr) { + return VOID_STATUS_INVALID_ARGUMENT; + } + auto rec = hctx->rec.lock(); + if (!rec || rec->generation != generation || + rec->destroyed.load(std::memory_order_acquire)) { + return VOID_STATUS_CONFLICT; + } + rec->add_activity_pin(); + return VOID_STATUS_OK; + } + + static void host_release_pin(void_host_context* ctx, + std::uint64_t generation) + { + auto* hctx = + reinterpret_cast(ctx); + if (hctx == nullptr) { + return; + } + auto rec = hctx->rec.lock(); + if (!rec || rec->generation != generation) { + return; + } + rec->release_activity_pin(); + } + + static void host_log_msg(void_host_context* /*ctx*/, + std::int32_t level, const char* msg) + { + if (msg == nullptr) { + return; + } + const std::size_t len = ::strnlen(msg, 1024); + const std::string_view sv{msg, len}; + if (level <= 0) { + Void::Log::debug("Plugin.CAbi", "{}", sv); + } else { + Void::Log::info("Plugin.CAbi", "{}", sv); + } + } + + void notify_observers(const ReloadEvent& ev) + { + std::vector> copy; + { + std::lock_guard lk{obs_mu}; + copy.reserve(observers.size()); + for (const auto& [_, cb] : observers) { + if (cb) copy.push_back(cb); + } + } + for (const auto& cb : copy) { + try { + cb(ev); + } catch (...) { + } + } + } + + void_op_options_v1 + make_op_opts(std::optional dl, + bool stop) const noexcept + { + void_op_options_v1 opts{}; + opts.struct_size = sizeof(void_op_options_v1); + opts.flags = 0; + opts.deadline_ns = + dl.has_value() + ? static_cast(std::max( + 0, dl->time_since_epoch().count())) + : 0; + opts.stop_requested = stop ? 1 : 0; + return opts; + } + + Void::Result::Result> + open_candidate(const std::filesystem::path& path, + std::uint64_t gen) + { +#ifdef VOID_HOST_HAS_DLOPEN + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::file_not_found, + "CModuleHost: module file not found: " + path.string())); + } + const auto file_sz = std::filesystem::file_size(path, ec); + if (ec) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::dlopen_failed, + "CModuleHost: cannot stat module file")); + } + if (file_sz > limits.max_mapped_bytes_per_module) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: candidate image exceeds max_mapped_bytes_per_module")); + } + + // Fresh-inode copy so repeated loads at same path load fresh bytes. + const std::uint64_t copy_id = + temp_counter.fetch_add(1, std::memory_order_relaxed); + const auto tmp = path.parent_path() / + (path.filename().string() + ".void_cabi." + + std::to_string(copy_id)); + std::filesystem::copy_file( + path, tmp, std::filesystem::copy_options::overwrite_existing, + ec); + if (ec) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::dlopen_failed, + "CModuleHost: failed to stage module copy")); + } + + void* handle = dlopen(tmp.c_str(), RTLD_NOW | RTLD_LOCAL); + std::filesystem::remove(tmp, ec); + if (handle == nullptr) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::dlopen_failed, + std::string{"CModuleHost: dlopen failed: "} + + (dlerror() ? dlerror() : "unknown"))); + } + + auto cleanup_handle = [&]() { + if (handle != nullptr && limits.allow_safe_dlclose) { + dlclose(handle); + } + handle = nullptr; + }; + + auto query_fn = reinterpret_cast( + dlsym(handle, VOID_MODULE_QUERY_SYMBOL_V1)); + if (query_fn == nullptr) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::symbol_missing, + "CModuleHost: missing void_module_query_v1 export")); + } + + void_module_api_v1 api{}; + const std::int32_t qrc = + query_fn(sizeof(void_module_api_v1), &api); + if (qrc != VOID_STATUS_OK) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + map_cabi_status(qrc, PluginErrorCode::abi_mismatch), + "CModuleHost: void_module_query_v1 failed")); + } + if (api.struct_size < VOID_MODULE_API_V1_MIN_SIZE || + api.abi_major != VOID_CABI_MAJOR_V1 || api.reserved != 0) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: invalid C ABI table size, major version, or reserved field")); + } + if (api.get_info == nullptr || api.create == nullptr || + api.activate == nullptr || api.readiness == nullptr || + api.request_stop == nullptr || api.deactivate == nullptr || + api.destroy == nullptr) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: required C ABI callbacks missing")); + } + if ((api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0 && + (api.quiesce == nullptr || api.resume == nullptr || + api.checkpoint == nullptr || api.restore == nullptr)) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: stateful capability requires quiesce/resume/checkpoint/restore")); + } + + void_module_info_v1 info{}; + const std::int32_t irc = api.get_info(&info); + if (irc != VOID_STATUS_OK || + info.struct_size < sizeof(void_module_info_v1) || + info.reserved != 0 || info.module_id == nullptr || + info.version == nullptr || info.module_id[0] == '\0') { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: invalid void_module_info_v1 descriptor")); + } + if (info.dependency_count > limits.max_interfaces_per_module || + (info.dependency_count > 0 && info.dependencies == nullptr)) { + cleanup_handle(); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: invalid or oversized dependency list")); + } + + auto rec = std::make_shared(); + rec->host_impl = weak_from_this(); + rec->host_api_ctx.host_impl = weak_from_this(); + rec->host_api_ctx.rec = rec; + rec->generation = gen; + rec->module_id = std::string{ + info.module_id, ::strnlen(info.module_id, 256)}; + rec->version = + std::string{info.version, ::strnlen(info.version, 128)}; + rec->image_bytes = file_sz; + rec->dl_handle = handle; + rec->api = api; + rec->activation_policy = info.activation_policy; + rec->allow_dlclose = limits.allow_safe_dlclose; + + for (std::uint64_t i = 0; i < info.dependency_count; ++i) { + const auto& d = info.dependencies[i]; + if (!is_all_zero(d.reserved, sizeof(d.reserved)) || + d.module_id == nullptr || d.version_range == nullptr || + d.module_id[0] == '\0') { + if (rec->allow_dlclose) dlclose(rec->dl_handle); + rec->dl_handle = nullptr; + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: malformed dependency entry")); + } + if (!Semver::VersionRange::parse(d.version_range)) { + if (rec->allow_dlclose) dlclose(rec->dl_handle); + rec->dl_handle = nullptr; + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "CModuleHost: invalid dependency semver range")); + } + rec->dependencies.push_back(DependencySpec{ + .module_id = d.module_id, + .version_range = d.version_range, + .optional_dep = d.optional_dep != 0}); + } + + void_host_api_v1 host_api{}; + host_api.struct_size = sizeof(void_host_api_v1); + host_api.abi_major = VOID_CABI_MAJOR_V1; + host_api.abi_minor = VOID_CABI_MINOR_V1; + host_api.reserved = 0; + host_api.host_ctx = + reinterpret_cast(&rec->host_api_ctx); + host_api.generation = gen; + host_api.monotonic_now_ns = &host_monotonic_ns; + host_api.acquire_activity_pin = &host_acquire_pin; + host_api.release_activity_pin = &host_release_pin; + host_api.log_message = &host_log_msg; + + void_module_handle* mod = nullptr; + const std::int32_t crc = api.create(&host_api, &mod); + if (crc != VOID_STATUS_OK || mod == nullptr) { + if (rec->allow_dlclose) dlclose(rec->dl_handle); + rec->dl_handle = nullptr; + return Void::Result::fail(make_plugin_error( + map_cabi_status(crc, PluginErrorCode::activation_failed), + "CModuleHost: plugin create failed")); + } + rec->mod_handle = mod; + return rec; +#else + (void)path; + (void)gen; + return Void::Result::fail(make_plugin_error( + PluginErrorCode::dlopen_failed, + "CModuleHost: dlopen unsupported on this platform")); +#endif + } + + void dispose_uncommitted( + const std::shared_ptr& rec) + { + if (!rec) return; + rec->retire_requested.store(true, std::memory_order_seq_cst); + perform_retire(*rec); + } + + Void::Result::Result + activate_and_verify(detail::GenerationRecord& rec, + std::string_view config, + const Void::Time::MonotonicClock::time_point total_dl, + const Void::Async::OperationOptions& caller_opts) + { + if (config.size() > limits.max_config_bytes) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: config payload exceeds max_config_bytes")); + } + if (caller_opts.stop.stop_requested()) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::cancelled, + "CModuleHost: cancelled before activation")); + } + if (clock->now() >= total_dl) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::timeout, + "CModuleHost: reload deadline expired before activation")); + } + + void_bytes_v1 cfg{ + .data = reinterpret_cast( + config.empty() ? "" : config.data()), + .size = static_cast(config.size())}; + void_error_detail_v1 err{}; + err.struct_size = sizeof(void_error_detail_v1); + const std::int32_t arc = + rec.api.activate(rec.mod_handle, cfg, &err); + std::string emsg = consume_error_detail(err); + if (arc != VOID_STATUS_OK) { + return Void::Result::fail(make_plugin_error( + map_cabi_status(arc, PluginErrorCode::activation_failed), + emsg.empty() ? "CModuleHost: module activate failed" + : emsg)); + } + rec.activated = true; + + if (clock->now() >= total_dl || + caller_opts.stop.stop_requested()) { + return Void::Result::fail(make_plugin_error( + caller_opts.stop.stop_requested() + ? PluginErrorCode::cancelled + : PluginErrorCode::timeout, + "CModuleHost: cancelled/timed out before readiness check")); + } + + std::uint32_t ready_flag = 0; + void_error_detail_v1 rerr{}; + rerr.struct_size = sizeof(void_error_detail_v1); + const std::int32_t rrc = + rec.api.readiness(rec.mod_handle, &ready_flag, &rerr); + std::string rmsg = consume_error_detail(rerr); + if (rrc != VOID_STATUS_OK || ready_flag == 0) { + return Void::Result::fail(make_plugin_error( + rrc == VOID_STATUS_OK + ? PluginErrorCode::not_ready + : map_cabi_status(rrc, PluginErrorCode::not_ready), + rmsg.empty() ? "CModuleHost: module reported not ready" + : rmsg)); + } + return {}; + } + + PluginHostLimits limits{}; + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + std::atomic next_gen{1}; + std::atomic temp_counter{1}; + + mutable std::mutex map_mu{}; + bool closing{false}; + std::unordered_map> + modules{}; + + std::mutex retire_mu{}; + std::condition_variable retire_cv{}; + bool retire_stop{false}; + std::deque> + retire_queue{}; + std::thread retire_thread{}; + + std::mutex obs_mu{}; + std::vector< + std::pair>> + observers{}; + std::size_t next_obs_id{1}; + }; + + void detail::GenerationRecord::maybe_enqueue_retire() noexcept + { + if (retire_requested.load(std::memory_order_seq_cst) && + external_refs.load(std::memory_order_seq_cst) == 0 && + activity_pins.load(std::memory_order_seq_cst) == 0) { + bool exp = false; + if (retired_enqueued.compare_exchange_strong( + exp, true, std::memory_order_acq_rel)) { + if (auto impl = host_impl.lock()) { + impl->enqueue_retire(shared_from_this()); + } + } + } + } + + // ── ActivityPin & InterfaceLease & GenerationLease ─────────────────── + + ActivityPin::~ActivityPin() + { + if (m_rec) { + m_rec->release_activity_pin(); + m_rec.reset(); + } + } + + ActivityPin::ActivityPin(ActivityPin&& other) noexcept + : m_rec(std::move(other.m_rec)) + { + } + + ActivityPin& ActivityPin::operator=(ActivityPin&& other) noexcept + { + if (this != &other) { + if (m_rec) { + m_rec->release_activity_pin(); + } + m_rec = std::move(other.m_rec); + } + return *this; + } + + std::uint64_t ActivityPin::generation() const noexcept + { + return m_rec ? m_rec->generation : 0; + } + + InterfaceLease::~InterfaceLease() + { + if (m_rec) { + if (m_view.function_table != nullptr && + m_rec->api.release_interface != nullptr && + m_rec->mod_handle != nullptr) { + m_rec->api.release_interface(m_rec->mod_handle, &m_id, &m_view); + } + m_rec->release_external_ref(); + m_rec.reset(); + } + m_view = {}; + } + + InterfaceLease::InterfaceLease(InterfaceLease&& other) noexcept + : m_rec(std::move(other.m_rec)), m_id(other.m_id), + m_view(other.m_view) + { + other.m_view = {}; + } + + InterfaceLease& InterfaceLease::operator=(InterfaceLease&& other) noexcept + { + if (this != &other) { + if (m_rec) { + if (m_view.function_table != nullptr && + m_rec->api.release_interface != nullptr && + m_rec->mod_handle != nullptr) { + m_rec->api.release_interface(m_rec->mod_handle, &m_id, + &m_view); + } + m_rec->release_external_ref(); + } + m_rec = std::move(other.m_rec); + m_id = other.m_id; + m_view = other.m_view; + other.m_view = {}; + } + return *this; + } + + std::uint64_t InterfaceLease::generation() const noexcept + { + return m_rec ? m_rec->generation : 0; + } + + GenerationLease::GenerationLease( + std::shared_ptr rec) + : m_rec(std::move(rec)) + { + if (m_rec) { + m_rec->add_external_ref(); + } + } + + GenerationLease::GenerationLease(const GenerationLease& other) + : m_rec(other.m_rec) + { + if (m_rec) { + m_rec->add_external_ref(); + } + } + + GenerationLease& GenerationLease::operator=(const GenerationLease& other) + { + if (this != &other) { + if (m_rec) { + m_rec->release_external_ref(); + } + m_rec = other.m_rec; + if (m_rec) { + m_rec->add_external_ref(); + } + } + return *this; + } + + GenerationLease::GenerationLease(GenerationLease&& other) noexcept + : m_rec(std::move(other.m_rec)) + { + } + + GenerationLease& GenerationLease::operator=(GenerationLease&& other) noexcept + { + if (this != &other) { + if (m_rec) { + m_rec->release_external_ref(); + } + m_rec = std::move(other.m_rec); + } + return *this; + } + + GenerationLease::~GenerationLease() + { + if (m_rec) { + m_rec->release_external_ref(); + m_rec.reset(); + } + } + + std::uint64_t GenerationLease::generation() const noexcept + { + return m_rec ? m_rec->generation : 0; + } + + std::string_view GenerationLease::module_id() const noexcept + { + return m_rec ? std::string_view{m_rec->module_id} : std::string_view{}; + } + + std::string_view GenerationLease::version() const noexcept + { + return m_rec ? std::string_view{m_rec->version} : std::string_view{}; + } + + GenerationHealth GenerationLease::health() const noexcept + { + return m_rec ? m_rec->health.load(std::memory_order_acquire) + : GenerationHealth::Retired; + } + + ActivityPin GenerationLease::acquire_activity_pin() const + { + if (!m_rec) { + return ActivityPin{}; + } + m_rec->add_activity_pin(); + return ActivityPin{m_rec}; + } + + Void::Result::Result + GenerationLease::query_interface(const void_interface_id_v1& id, + std::uint32_t min_major, + std::uint32_t min_table_size) const + { + if (!m_rec || m_rec->mod_handle == nullptr || + m_rec->api.query_interface == nullptr) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "GenerationLease: interface query unsupported")); + } + void_interface_view_v1 view{}; + view.struct_size = sizeof(void_interface_view_v1); + const std::int32_t rc = m_rec->api.query_interface( + m_rec->mod_handle, &id, min_major, min_table_size, &view); + if (rc != VOID_STATUS_OK) { + return Void::Result::fail(make_plugin_error( + map_cabi_status(rc, PluginErrorCode::abi_mismatch), + "GenerationLease: query_interface rejected or missing")); + } + if (view.struct_size < sizeof(void_interface_view_v1) || + view.major != min_major || view.table_size < min_table_size || + view.function_table == nullptr) { + if (m_rec->api.release_interface != nullptr) { + m_rec->api.release_interface(m_rec->mod_handle, &id, &view); + } + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "GenerationLease: interface table version or size mismatch")); + } + m_rec->add_external_ref(); + return InterfaceLease{m_rec, id, view}; + } + + Void::Result::Result> + GenerationLease::run_async(std::uint32_t op_kind, + const std::vector& payload, + Void::Async::OperationOptions options) const + { + if (!m_rec || m_rec->mod_handle == nullptr || + m_rec->api.submit_async == nullptr) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::abi_mismatch, + "GenerationLease: async operations unsupported")); + } + auto impl = m_rec->host_impl.lock(); + const std::size_t cap = + impl ? impl->limits.max_async_activities : 1024; + if (m_rec->active_async_ops.fetch_add(1, std::memory_order_acq_rel) >= + cap) { + m_rec->active_async_ops.fetch_sub(1, std::memory_order_acq_rel); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "GenerationLease: async activity limit exceeded")); + } + + struct AsyncState { + std::shared_ptr rec; + std::mutex mu{}; + std::condition_variable cv{}; + bool done{false}; + std::int32_t status{VOID_STATUS_INTERNAL}; + std::vector result{}; + }; + + auto st = std::make_shared(); + st->rec = m_rec; + m_rec->add_activity_pin(); + + auto release_guards = [&]() { + m_rec->active_async_ops.fetch_sub(1, std::memory_order_acq_rel); + m_rec->release_activity_pin(); + }; + + const void_bytes_v1 in_bytes{ + .data = payload.empty() ? nullptr : payload.data(), + .size = static_cast(payload.size())}; + + void_op_options_v1 cabi_opts{}; + cabi_opts.struct_size = sizeof(void_op_options_v1); + cabi_opts.deadline_ns = + options.deadline.has_value() + ? static_cast(std::max( + 0, options.deadline->time_since_epoch().count())) + : 0; + cabi_opts.stop_requested = options.stop.stop_requested() ? 1 : 0; + + auto* raw_state = new std::shared_ptr(st); + auto cb = [](void* ctx, std::int32_t status, + const void_bytes_v1* result_bytes) { + auto* holder = + static_cast*>(ctx); + auto s = *holder; + delete holder; + { + std::lock_guard lk{s->mu}; + s->status = status; + if (result_bytes != nullptr && result_bytes->data != nullptr && + result_bytes->size > 0 && + result_bytes->size <= 64 * 1024 * 1024) { + const auto sz = + static_cast(result_bytes->size); + s->result.assign(result_bytes->data, + result_bytes->data + sz); + } + s->done = true; + } + s->cv.notify_all(); + }; + + void_operation_handle* op_handle = nullptr; + void_error_detail_v1 err{}; + err.struct_size = sizeof(void_error_detail_v1); + const std::int32_t rc = m_rec->api.submit_async( + m_rec->mod_handle, op_kind, in_bytes, &cabi_opts, cb, raw_state, + &op_handle, &err); + std::string emsg = consume_error_detail(err); + if (rc != VOID_STATUS_OK || op_handle == nullptr) { + delete raw_state; + release_guards(); + return Void::Result::fail(make_plugin_error( + map_cabi_status(rc, PluginErrorCode::internal), + emsg.empty() ? "GenerationLease: submit_async failed" : emsg)); + } + + { + struct Canceller { + detail::GenerationRecord* rec; + void_operation_handle* op; + void operator()() const noexcept + { + if (rec->api.cancel_async != nullptr) { + (void)rec->api.cancel_async(rec->mod_handle, op); + } + } + }; + std::optional> stop_cb; + if (options.stop.stop_possible()) { + stop_cb.emplace(options.stop, + Canceller{m_rec.get(), op_handle}); + } + std::unique_lock lk{st->mu}; + st->cv.wait(lk, [&] { return st->done; }); + } + if (m_rec->api.release_async != nullptr) { + m_rec->api.release_async(m_rec->mod_handle, op_handle); + } + release_guards(); + + if (st->status != VOID_STATUS_OK) { + return Void::Result::fail(make_plugin_error( + map_cabi_status(st->status, PluginErrorCode::internal), + "GenerationLease: async operation failed")); + } + return st->result; + } + + // ── CModuleHost ────────────────────────────────────────────────────── + + CModuleHost::CModuleHost(PluginHostLimits limits, + const Void::Time::MonotonicClock& clock) + : m_impl(std::make_shared(limits, clock)) + { + } + + CModuleHost::~CModuleHost() + { + if (m_impl) { + m_impl->shutdown(); + } + } + + void CModuleHost::close_and_join() + { + if (m_impl) { + m_impl->shutdown(); + } + } + + std::size_t + CModuleHost::add_observer(std::function cb) + { + std::lock_guard lk{m_impl->obs_mu}; + const std::size_t id = m_impl->next_obs_id++; + m_impl->observers.emplace_back(id, std::move(cb)); + return id; + } + + void CModuleHost::remove_observer(std::size_t id) + { + std::lock_guard lk{m_impl->obs_mu}; + std::erase_if(m_impl->observers, + [id](const auto& pair) { return pair.first == id; }); + } + + Void::Result::Result + CModuleHost::load(const std::filesystem::path& path, + std::string_view config, + Void::Async::OperationOptions options) + { + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: host is closing")); + } + if (m_impl->modules.size() >= m_impl->limits.max_modules) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: max_modules limit reached")); + } + } + + const std::uint64_t gen = + m_impl->next_gen.fetch_add(1, std::memory_order_relaxed); + auto cand_res = m_impl->open_candidate(path, gen); + if (!cand_res) { + return Void::Result::fail(std::move(cand_res).error()); + } + auto cand = std::move(*cand_res); + + const auto now = m_impl->clock->now(); + auto total_dl = now + m_impl->limits.total_reload_timeout; + if (options.deadline.has_value() && *options.deadline < total_dl) { + total_dl = *options.deadline; + } + if (auto ar = m_impl->activate_and_verify(*cand, config, total_dl, + options); + !ar) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(std::move(ar).error()); + } + + std::shared_ptr slot; + std::string mod_id = cand->module_id; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, "CModuleHost: host closing")); + } + if (m_impl->modules.contains(mod_id)) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: module already loaded: " + mod_id)); + } + slot = std::make_shared(); + cand->add_external_ref(); + slot->current = cand; + slot->retained.push_back(cand); + m_impl->modules.emplace(mod_id, slot); + } + m_impl->notify_observers(ReloadEvent{ + .module_id = mod_id, .generation = gen, .rollback = false, + .detail = "loaded"}); + return mod_id; + } + + Void::Result::Result> + CModuleHost::load_batch(const std::vector& specs, + Void::Async::OperationOptions options) + { + if (specs.empty()) { + return std::vector{}; + } + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, "CModuleHost: host closing")); + } + if (m_impl->modules.size() + specs.size() > + m_impl->limits.max_modules) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: batch exceeds max_modules limit")); + } + } + + struct Opened { + std::shared_ptr rec; + std::string config; + std::size_t seq; + }; + std::vector opened; + opened.reserve(specs.size()); + std::unordered_map by_id; + + auto dispose_all = [&](std::size_t active_prefix) { + for (std::size_t i = active_prefix; i > 0; --i) { + m_impl->dispose_uncommitted(opened[i - 1].rec); + } + for (std::size_t i = active_prefix; i < opened.size(); ++i) { + m_impl->dispose_uncommitted(opened[i].rec); + } + }; + + for (std::size_t i = 0; i < specs.size(); ++i) { + const std::uint64_t gen = + m_impl->next_gen.fetch_add(1, std::memory_order_relaxed); + auto cr = m_impl->open_candidate(specs[i].path, gen); + if (!cr) { + dispose_all(0); + return Void::Result::fail(std::move(cr).error()); + } + auto rec = std::move(*cr); + if (!by_id.emplace(rec->module_id, i).second) { + m_impl->dispose_uncommitted(rec); + dispose_all(0); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost::load_batch: duplicate module_id '" + + rec->module_id + "'")); + } + opened.push_back(Opened{std::move(rec), specs[i].config, i}); + } + + // Topological dependency check and policy consistency. + const std::size_t n = opened.size(); + std::vector> adj(n); + std::vector indeg(n, 0); + + for (std::size_t i = 0; i < n; ++i) { + for (const auto& dep : opened[i].rec->dependencies) { + auto it = by_id.find(dep.module_id); + if (it == by_id.end()) { + // Check already-loaded modules. + bool present_active = false; + { + std::lock_guard lk{m_impl->map_mu}; + auto mit = m_impl->modules.find(dep.module_id); + if (mit != m_impl->modules.end() && + mit->second->current) { + if (auto ver = Semver::parse( + mit->second->current->version)) { + if (auto rng = Semver::VersionRange::parse( + dep.version_range); + rng && rng->contains(*ver)) { + present_active = true; + } + } + } + } + if (!dep.optional_dep && !present_active) { + dispose_all(0); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::missing_dependency, + "CModuleHost::load_batch: missing required dependency '" + + dep.module_id + "'")); + } + continue; + } + const std::size_t d = it->second; + if (d == i) { + dispose_all(0); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::cycle_detected, + "CModuleHost::load_batch: self dependency cycle")); + } + const auto ver = + Semver::parse(opened[d].rec->version); + const auto rng = + Semver::VersionRange::parse(dep.version_range); + if (!ver || !rng || !rng->contains(*ver)) { + dispose_all(0); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::missing_dependency, + "CModuleHost::load_batch: incompatible dependency version for '" + + dep.module_id + "'")); + } + adj[d].push_back(i); + ++indeg[i]; + } + } + + std::priority_queue, + std::greater> + ready; + for (std::size_t i = 0; i < n; ++i) { + if (indeg[i] == 0) ready.push(i); + } + std::vector order; + order.reserve(n); + while (!ready.empty()) { + const std::size_t u = ready.top(); + ready.pop(); + order.push_back(std::move(opened[u])); + for (const std::size_t v : adj[u]) { + if (--indeg[v] == 0) ready.push(v); + } + } + if (order.size() != n) { + for (auto& o : opened) m_impl->dispose_uncommitted(o.rec); + for (auto& o : order) m_impl->dispose_uncommitted(o.rec); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::cycle_detected, + "CModuleHost::load_batch: dependency cycle detected")); + } + + const auto now = m_impl->clock->now(); + auto total_dl = now + m_impl->limits.total_reload_timeout; + if (options.deadline.has_value() && *options.deadline < total_dl) { + total_dl = *options.deadline; + } + + std::vector activated_idx; + for (std::size_t i = 0; i < n; ++i) { + if (auto ar = m_impl->activate_and_verify( + *order[i].rec, order[i].config, total_dl, options); + !ar) { + for (auto it = activated_idx.rbegin(); + it != activated_idx.rend(); ++it) { + m_impl->dispose_uncommitted(order[*it].rec); + } + for (std::size_t k = i; k < n; ++k) { + m_impl->dispose_uncommitted(order[k].rec); + } + return Void::Result::fail(std::move(ar).error()); + } + activated_idx.push_back(i); + } + + std::vector ids; + ids.reserve(n); + { + std::lock_guard lk{m_impl->map_mu}; + for (auto& o : order) { + if (m_impl->modules.contains(o.rec->module_id)) { + for (const auto idx : activated_idx) { + m_impl->dispose_uncommitted(order[idx].rec); + } + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost::load_batch: conflict with loaded module")); + } + } + for (auto& o : order) { + auto slot = std::make_shared(); + o.rec->add_external_ref(); + slot->current = o.rec; + slot->retained.push_back(o.rec); + ids.push_back(o.rec->module_id); + m_impl->modules.emplace(o.rec->module_id, std::move(slot)); + } + } + return ids; + } + + Void::Result::Result CModuleHost::replace( + std::string_view module_id, const std::filesystem::path& new_path, + std::string_view config, + std::optional expected_generation, + Void::Async::OperationOptions options, + std::function(const GenerationLease&)> + on_publish_locked) + { + std::shared_ptr slot; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, "CModuleHost: host is closing")); + } + auto it = m_impl->modules.find(std::string{module_id}); + if (it == m_impl->modules.end()) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::not_found, + "CModuleHost: unknown module: " + std::string{module_id})); + } + slot = it->second; + } + + std::lock_guard reload_lk{slot->reload_mu}; + + std::shared_ptr old_rec; + std::size_t active_retained_count = 0; + std::size_t total_mapped = 0; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, "CModuleHost: host is closing")); + } + old_rec = slot->current; + std::erase_if(slot->retained, [](const auto& r) { + return !r || (r->destroyed.load(std::memory_order_acquire) && + r->dlclosed.load(std::memory_order_acquire)); + }); + for (const auto& r : slot->retained) { + if (!r->destroyed.load(std::memory_order_acquire)) { + ++active_retained_count; + } + if (!r->dlclosed.load(std::memory_order_acquire)) { + total_mapped += static_cast(r->image_bytes); + } + } + } + + if (!old_rec) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::not_found, "CModuleHost: module unloaded")); + } + if (expected_generation.has_value() && + old_rec->generation != *expected_generation) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: expected generation conflict")); + } + if (old_rec->activation_policy == VOID_POLICY_RESTART_REQUIRED || + old_rec->activation_policy == VOID_POLICY_INSTALLER_REQUIRED) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::restart_required, + "CModuleHost: active module requires restart for upgrade")); + } + if (m_impl->limits.max_retained_generations > 0 && + active_retained_count >= + m_impl->limits.max_retained_generations) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::retention_limit, + "CModuleHost: max_retained_generations limit reached")); + } + + const std::uint64_t new_gen = + m_impl->next_gen.fetch_add(1, std::memory_order_relaxed); + auto cand_res = m_impl->open_candidate(new_path, new_gen); + if (!cand_res) { + return Void::Result::fail(std::move(cand_res).error()); + } + auto cand = std::move(*cand_res); + + if (cand->module_id != module_id) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: replacement module_id mismatch")); + } + if (cand->activation_policy == VOID_POLICY_RESTART_REQUIRED || + cand->activation_policy == VOID_POLICY_INSTALLER_REQUIRED) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::restart_required, + "CModuleHost: candidate module requires restart")); + } + if (total_mapped + cand->image_bytes > + m_impl->limits.max_mapped_bytes_per_module) { + m_impl->dispose_uncommitted(cand); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: mapped image byte budget exceeded")); + } + + const auto now = m_impl->clock->now(); + auto total_dl = now + m_impl->limits.total_reload_timeout; + if (options.deadline.has_value() && *options.deadline < total_dl) { + total_dl = *options.deadline; + } + + bool old_quiesced = false; + auto rollback_and_resume_old = + [&](Void::Result::Error primary) -> Void::Result::Result { + m_impl->dispose_uncommitted(cand); + if (old_quiesced && old_rec->api.resume != nullptr && + old_rec->mod_handle != nullptr) { + void_error_detail_v1 res_err{}; + res_err.struct_size = sizeof(void_error_detail_v1); + const std::int32_t rrc = + old_rec->api.resume(old_rec->mod_handle, &res_err); + const std::string rmsg = consume_error_detail(res_err); + if (rrc != VOID_STATUS_OK) { + old_rec->health.store(GenerationHealth::Degraded, + std::memory_order_release); + m_impl->notify_observers(ReloadEvent{ + .module_id = std::string{module_id}, + .generation = old_rec->generation, + .rollback = true, + .detail = "degraded after resume failure: " + rmsg}); + return Void::Result::fail(make_plugin_error( + PluginErrorCode::resume_degraded, + primary.message() + "; old resume failed: " + rmsg)); + } + old_rec->health.store(GenerationHealth::Healthy, + std::memory_order_release); + } + m_impl->notify_observers(ReloadEvent{ + .module_id = std::string{module_id}, + .generation = old_rec->generation, + .rollback = true, + .detail = primary.message()}); + return Void::Result::fail(std::move(primary)); + }; + + const bool stateful = + ((old_rec->api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0) && + ((cand->api.capabilities & VOID_CAP_STATEFUL_CHECKPOINT) != 0); + + if (stateful) { + old_rec->health.store(GenerationHealth::Quiescing, + std::memory_order_release); + const auto q_dl = + std::min(total_dl, m_impl->clock->now() + + m_impl->limits.quiesce_timeout); + const auto q_opts = + m_impl->make_op_opts(q_dl, options.stop.stop_requested()); + void_error_detail_v1 qerr{}; + qerr.struct_size = sizeof(void_error_detail_v1); + const std::int32_t qrc = + old_rec->api.quiesce(old_rec->mod_handle, &q_opts, &qerr); + const std::string qmsg = consume_error_detail(qerr); + old_quiesced = true; + if (qrc != VOID_STATUS_OK) { + return rollback_and_resume_old(make_plugin_error( + map_cabi_status(qrc, PluginErrorCode::quiesce_failed), + qmsg.empty() ? "CModuleHost: quiesce failed" : qmsg)); + } + + void_owned_bytes_v1 ckpt{}; + void_error_detail_v1 cerr{}; + cerr.struct_size = sizeof(void_error_detail_v1); + const std::int32_t crc = old_rec->api.checkpoint( + old_rec->mod_handle, &q_opts, &ckpt, &cerr); + const std::string cmsg = consume_error_detail(cerr); + + std::vector ckpt_copy; + bool size_ok = true; + if (crc == VOID_STATUS_OK) { + if (ckpt.size > m_impl->limits.max_checkpoint_bytes || + (ckpt.size > 0 && ckpt.data == nullptr)) { + size_ok = false; + } else if (ckpt.size > 0) { + const auto sz = static_cast(ckpt.size); + ckpt_copy.assign(ckpt.data, ckpt.data + sz); + } + } + if (ckpt.release != nullptr && ckpt.data != nullptr) { + ckpt.release(ckpt.release_ctx, ckpt.data, ckpt.size); + } + if (crc != VOID_STATUS_OK) { + return rollback_and_resume_old(make_plugin_error( + map_cabi_status(crc, PluginErrorCode::checkpoint_failed), + cmsg.empty() ? "CModuleHost: checkpoint failed" : cmsg)); + } + if (!size_ok) { + return rollback_and_resume_old(make_plugin_error( + PluginErrorCode::budget_exceeded, + "CModuleHost: checkpoint exceeded max_checkpoint_bytes or invalid buffer")); + } + + const void_bytes_v1 r_bytes{ + .data = ckpt_copy.empty() ? nullptr : ckpt_copy.data(), + .size = static_cast(ckpt_copy.size())}; + void_error_detail_v1 rerr{}; + rerr.struct_size = sizeof(void_error_detail_v1); + const std::int32_t rrc = + cand->api.restore(cand->mod_handle, r_bytes, &rerr); + const std::string rmsg = consume_error_detail(rerr); + if (rrc != VOID_STATUS_OK) { + return rollback_and_resume_old(make_plugin_error( + map_cabi_status(rrc, PluginErrorCode::restore_failed), + rmsg.empty() ? "CModuleHost: restore failed" : rmsg)); + } + } + + if (auto ar = m_impl->activate_and_verify(*cand, config, total_dl, + options); + !ar) { + return rollback_and_resume_old(std::move(ar).error()); + } + + if (on_publish_locked) { + GenerationLease cand_lease{cand}; + if (auto phr = on_publish_locked(cand_lease); !phr) { + return rollback_and_resume_old(std::move(phr).error()); + } + } + + std::shared_ptr retired_old; + bool swap_conflict = false; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing || slot->current != old_rec) { + swap_conflict = true; + } else { + cand->add_external_ref(); + retired_old = std::exchange(slot->current, cand); + slot->retained.push_back(cand); + } + } + if (swap_conflict) { + return rollback_and_resume_old(make_plugin_error( + PluginErrorCode::conflict, + "CModuleHost: concurrent generation swap conflict")); + } + + if (retired_old) { + retired_old->health.store(GenerationHealth::Retiring, + std::memory_order_release); + retired_old->retire_requested.store(true, + std::memory_order_seq_cst); + retired_old->release_external_ref(); + } + + m_impl->notify_observers(ReloadEvent{ + .module_id = std::string{module_id}, + .generation = new_gen, + .rollback = false, + .detail = "replaced"}); + return new_gen; + } + + Void::Result::Result CModuleHost::unload(std::string_view module_id) + { + std::shared_ptr slot; + { + std::lock_guard lk{m_impl->map_mu}; + auto it = m_impl->modules.find(std::string{module_id}); + if (it == m_impl->modules.end()) { + return Void::Result::fail(make_plugin_error( + PluginErrorCode::not_found, + "CModuleHost: unknown module: " + std::string{module_id})); + } + slot = it->second; + m_impl->modules.erase(it); + } + std::lock_guard reload_lk{slot->reload_mu}; + std::shared_ptr old; + { + std::lock_guard lk{m_impl->map_mu}; + old = std::exchange(slot->current, nullptr); + } + if (old) { + old->health.store(GenerationHealth::Retiring, + std::memory_order_release); + old->retire_requested.store(true, std::memory_order_seq_cst); + if (old->api.request_stop != nullptr && old->mod_handle != nullptr) { + (void)old->api.request_stop(old->mod_handle); + } + old->release_external_ref(); + } + return {}; + } + + GenerationLease CModuleHost::acquire(std::string_view module_id) const + { + std::shared_ptr rec; + { + std::lock_guard lk{m_impl->map_mu}; + if (m_impl->closing) { + return GenerationLease{}; + } + auto it = m_impl->modules.find(std::string{module_id}); + if (it != m_impl->modules.end() && it->second->current) { + rec = it->second->current; + rec->add_external_ref(); + } + } + return rec ? GenerationLease{std::move(rec), + GenerationLease::AlreadyRefCountedTag{}} + : GenerationLease{}; + } + + std::vector + CModuleHost::retained_generations(std::string_view module_id) const + { + std::lock_guard lk{m_impl->map_mu}; + auto it = m_impl->modules.find(std::string{module_id}); + if (it == m_impl->modules.end()) { + return {}; + } + const auto& slot = it->second; + std::vector out; + for (const auto& r : slot->retained) { + if (!r) continue; + if (r->destroyed.load(std::memory_order_acquire) && + r->dlclosed.load(std::memory_order_acquire)) { + continue; + } + out.push_back(GenerationSummary{ + .generation = r->generation, + .module_id = r->module_id, + .version = r->version, + .image_bytes = r->image_bytes, + .external_refs = + r->external_refs.load(std::memory_order_acquire), + .activity_pins = + r->activity_pins.load(std::memory_order_acquire), + .health = r->health.load(std::memory_order_acquire), + .dlclosed = r->dlclosed.load(std::memory_order_acquire)}); + } + return out; + } + + std::size_t CModuleHost::mapped_bytes(std::string_view module_id) const + { + std::size_t sum = 0; + for (const auto& g : retained_generations(module_id)) { + if (!g.dlclosed) { + sum += static_cast(g.image_bytes); + } + } + return sum; + } + +} // namespace Void::Plugin diff --git a/src/Plugin/Manager.cpp b/src/Plugin/Manager.cpp index f727ffc..ee0ff19 100644 --- a/src/Plugin/Manager.cpp +++ b/src/Plugin/Manager.cpp @@ -187,10 +187,7 @@ namespace Void::Plugin } // Copy to a fresh-inode temp path so dlopen does not return the - // already-mapped image when the file is replaced in place. The name - // must be unique per copy: glibc dedupes dlopen by pathname, so - // reusing a temp name would hand back the previously mapped (old) - // image no matter what bytes the file now holds. + // already-mapped image when the file is replaced in place. std::expected hotswap_copy(const std::filesystem::path& path) { @@ -213,9 +210,10 @@ namespace Void::Plugin // ── PluginManager ───────────────────────────────────────────────────── PluginManager::PluginManager(Options options) - : m_options(options), m_watcher(FileSystem::FileWatcherOptions{ - .poll_interval = options.poll_interval, - .debounce_polls = options.debounce_polls}) + : m_options(std::move(options)), + m_watcher(FileSystem::FileWatcherOptions{ + .poll_interval = m_options.poll_interval, + .debounce_polls = m_options.debounce_polls}) { } @@ -227,6 +225,13 @@ namespace Void::Plugin return it == m_plugins.end() ? nullptr : it->second.get(); } + std::shared_ptr + PluginManager::find_shared(std::string_view name) const + { + const auto it = m_plugins.find(std::string{name}); + return it == m_plugins.end() ? nullptr : it->second; + } + std::expected PluginManager::load(const std::filesystem::path& path) { @@ -244,8 +249,6 @@ namespace Void::Plugin } auto inst = open_instance(load_path, m_options.dlclose_on_swap); if (m_options.copy_on_load) { - // The mapping keeps the unlinked inode alive; the registry - // keeps addressing the original path for watch/reload. std::filesystem::remove(load_path, ec); } if (!inst.has_value()) { @@ -278,15 +281,24 @@ namespace Void::Plugin return std::unexpected{LoadError::ActivationFailed}; } - std::lock_guard lock(m_mutex); - auto entry = std::make_unique(); - entry->path = path; - entry->current.store(std::move(*inst), std::memory_order_release); - Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})", - path.string(), name, - entry->current.load(std::memory_order_relaxed) - ->info.plugin_version); - m_plugins.insert_or_assign(name, std::move(entry)); + std::shared_ptr replaced_entry; + { + std::lock_guard lock(m_mutex); + auto entry = std::make_shared(); + entry->path = path; + entry->current.store(std::move(*inst), std::memory_order_release); + Void::Log::info("Plugin.Manager", "loaded '{}' as '{}' (v{})", + path.string(), name, + entry->current.load(std::memory_order_relaxed) + ->info.plugin_version); + auto it = m_plugins.find(name); + if (it != m_plugins.end()) { + replaced_entry = std::move(it->second); + it->second = std::move(entry); + } else { + m_plugins.emplace(name, std::move(entry)); + } + } return name; } @@ -323,195 +335,199 @@ namespace Void::Plugin std::expected PluginManager::unload(std::string_view name) { - std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { - return std::unexpected{LoadError::UnknownPlugin}; + std::shared_ptr removed; + { + std::lock_guard lock(m_mutex); + auto it = m_plugins.find(std::string{name}); + if (it == m_plugins.end()) { + return std::unexpected{LoadError::UnknownPlugin}; + } + m_watcher.unwatch(it->second->path); + removed = std::move(it->second); + m_plugins.erase(it); } - m_watcher.unwatch(entry->path); - // Erasing drops the registry's reference; outstanding handles keep - // the instance (and its mapped .so) alive until they drop. - m_plugins.erase(std::string{name}); Void::Log::info("Plugin.Manager", "unloaded '{}'", name); return {}; } PluginHandle PluginManager::acquire(std::string_view name) const { - std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { + std::shared_ptr entry; + { + std::lock_guard lock(m_mutex); + entry = find_shared(name); + } + if (!entry) { return PluginHandle{}; } - // One atomic load pins the instance; it survives any later swap. return PluginHandle{entry->current.load(std::memory_order_acquire)}; } std::expected PluginManager::reload(std::string_view name) { - std::vector> callbacks; + std::shared_ptr entry; { std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { - return std::unexpected{LoadError::UnknownPlugin}; - } - auto result = reload_locked(*entry, name, entry->path); - if (!result.has_value()) { - return result; - } - callbacks = reload_callbacks_locked(); + entry = find_shared(name); } - for (const auto& cb : callbacks) { - cb(name); + if (!entry) { + return std::unexpected{LoadError::UnknownPlugin}; } - return {}; + return reload_entry_unlocked(entry, name, std::nullopt); } std::expected PluginManager::replace(std::string_view name, const std::filesystem::path& newPath) { - std::vector> callbacks; - bool restartWatcher = false; + std::shared_ptr entry; { std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { - return std::unexpected{LoadError::UnknownPlugin}; - } - std::error_code error; - if (!std::filesystem::is_regular_file(newPath, error)) { - return std::unexpected{LoadError::FileNotFound}; - } - auto result = reload_locked(*entry, name, newPath); - if (!result) { - return result; - } - restartWatcher = entry->watched; - if (restartWatcher) { - m_watcher.unwatch(entry->path); - } - entry->path = newPath; - callbacks = reload_callbacks_locked(); + entry = find_shared(name); } + if (!entry) { + return std::unexpected{LoadError::UnknownPlugin}; + } + std::error_code error; + if (!std::filesystem::is_regular_file(newPath, error)) { + return std::unexpected{LoadError::FileNotFound}; + } + return reload_entry_unlocked(entry, name, newPath); + } + + std::expected PluginManager::reload_entry_unlocked( + const std::shared_ptr& entry, std::string_view name, + const std::optional& newPath) + { + std::vector> callbacks; + bool restartWatcher = false; + std::shared_ptr retired_old; + + { + // Serialize reloads per plugin entry WITHOUT holding m_mutex, so + // validators, config providers, and concurrent acquire() callers can + // reenter PluginManager without deadlocking. + std::lock_guard reload_lk{entry->reload_mutex}; + + std::filesystem::path sourcePath; + { + std::lock_guard lock(m_mutex); + if (find(name) != entry.get()) { + return std::unexpected{LoadError::UnknownPlugin}; + } + sourcePath = newPath.has_value() ? *newPath : entry->path; + } + + auto tmp = hotswap_copy(sourcePath); + if (!tmp.has_value()) { + return std::unexpected{tmp.error()}; + } + auto next = open_instance(*tmp, m_options.dlclose_on_swap); + std::error_code ec; + std::filesystem::remove(*tmp, ec); + if (!next.has_value()) { + Void::Log::warn("Plugin.Manager", + "reload '{}' failed: {}; keeping old", name, + to_string(next.error())); + return std::unexpected{next.error()}; + } + if ((*next)->plugin->name() != name) { + Void::Log::warn("Plugin.Manager", + "replace '{}' rejected: candidate reports '{}'", + name, (*next)->plugin->name()); + return std::unexpected{LoadError::NameMismatch}; + } + if (m_options.candidate_validator && + !m_options.candidate_validator(PluginHandle{*next})) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: binary validation failed", + name); + return std::unexpected{LoadError::ActivationFailed}; + } + + if (m_options.config_provider && (*next)->configure != nullptr) { + const std::string config = m_options.config_provider(name); + (*next)->configure((*next)->plugin, config.c_str()); + } + + auto old = entry->current.load(std::memory_order_acquire); + if (old) { + if (!transfer_state(*old, **next)) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: state rejected", name); + return std::unexpected{LoadError::StateRejected}; + } + } + + try { + (*next)->plugin->on_load(); + } catch (...) { + return std::unexpected{LoadError::ActivationFailed}; + } + if ((*next)->ready != nullptr && + (*next)->ready((*next)->plugin) != 0) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: activation failed", name); + return std::unexpected{LoadError::ActivationFailed}; + } + if (m_options.instance_validator && + !m_options.instance_validator(*(*next)->plugin, (*next)->info)) { + Void::Log::warn("Plugin.Manager", + "reload '{}' aborted: host validation failed", + name); + return std::unexpected{LoadError::ActivationFailed}; + } + + { + std::lock_guard lock(m_mutex); + if (find(name) != entry.get()) { + return std::unexpected{LoadError::UnknownPlugin}; + } + retired_old = entry->current.exchange( + std::move(*next), std::memory_order_acq_rel); + if (newPath.has_value()) { + restartWatcher = entry->watched; + if (restartWatcher) { + m_watcher.unwatch(entry->path); + } + entry->path = *newPath; + } + callbacks = reload_callbacks_locked(); + } + } + + // Drop old instance and invoke observers strictly outside all locks. + retired_old.reset(); if (restartWatcher) { watch(name); } - for (const auto& callback : callbacks) { - callback(name); - } - return {}; - } - - std::expected - PluginManager::reload_locked(Entry& entry, std::string_view name, - const std::filesystem::path& sourcePath) - { - // Copy to a fresh inode so dlopen loads the new bytes instead of - // returning the still-open handle for this path. The caller must - // have installed the new file via atomic rename (a fresh inode of - // its own) — overwriting the mapped file in place corrupts the - // running instance's mapping (SIGBUS). - auto tmp = hotswap_copy(sourcePath); - if (!tmp.has_value()) { - return std::unexpected{tmp.error()}; - } - auto next = open_instance(*tmp, m_options.dlclose_on_swap); - std::error_code ec; - std::filesystem::remove(*tmp, ec); - if (!next.has_value()) { - Void::Log::warn("Plugin.Manager", - "reload '{}' failed: {}; keeping old", name, - to_string(next.error())); - return std::unexpected{next.error()}; - } - if ((*next)->plugin->name() != name) { - Void::Log::warn("Plugin.Manager", - "replace '{}' rejected: candidate reports '{}'", - name, (*next)->plugin->name()); - return std::unexpected{LoadError::NameMismatch}; - } - if (m_options.candidate_validator && - !m_options.candidate_validator(PluginHandle{*next})) { - Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: binary validation failed", - name); - return std::unexpected{LoadError::ActivationFailed}; - } - - if (m_options.config_provider && (*next)->configure != nullptr) { - const std::string config = m_options.config_provider(name); - (*next)->configure((*next)->plugin, config.c_str()); - } - - // Transfer state with both instances alive (transactional). - auto old = entry.current.load(std::memory_order_acquire); - if (old) { - if (!transfer_state(*old, **next)) { - Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: state rejected", name); - return std::unexpected{LoadError::StateRejected}; - } - } - - try { - (*next)->plugin->on_load(); - } catch (...) { - return std::unexpected{LoadError::ActivationFailed}; - } - if ((*next)->ready != nullptr && (*next)->ready((*next)->plugin) != 0) { - Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: activation failed", name); - return std::unexpected{LoadError::ActivationFailed}; - } - if (m_options.instance_validator && - !m_options.instance_validator(*(*next)->plugin, (*next)->info)) { - Void::Log::warn("Plugin.Manager", - "reload '{}' aborted: host validation failed", - name); - return std::unexpected{LoadError::ActivationFailed}; - } - // Atomic swap. The old instance keeps living while any acquired - // handle still pins it; it is destroyed when the last one drops. - entry.current.store(std::move(*next), std::memory_order_release); Void::Log::info("Plugin.Manager", "reloaded '{}'", name); + for (const auto& cb : callbacks) { + cb(name); + } return {}; } void PluginManager::watch(std::string_view name) { + std::shared_ptr entry; std::filesystem::path path; { std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { + entry = find_shared(name); + if (!entry) { return; } path = entry->path; entry->watched = true; } const std::string name_str{name}; - m_watcher.watch(path, [this, name_str]( + m_watcher.watch(path, [this, entry, name_str]( const FileSystem::FileWatcher::Event& e) { if (!e.exists) { return; } - std::vector> callbacks; - { - std::lock_guard lock(m_mutex); - auto* entry = find(name_str); - if (entry == nullptr) { - return; - } - if (!reload_locked(*entry, name_str, entry->path).has_value()) { - return; - } - callbacks = reload_callbacks_locked(); - } - for (const auto& cb : callbacks) { - cb(name_str); - } + (void)reload_entry_unlocked(entry, name_str, std::nullopt); }); } diff --git a/src/Plugin/module.cmake b/src/Plugin/module.cmake index 3463646..9275728 100644 --- a/src/Plugin/module.cmake +++ b/src/Plugin/module.cmake @@ -1,4 +1,4 @@ void_add_module(Plugin - INTERNAL_DEPS Functional System Data LogState Text Service + INTERNAL_DEPS Core Functional System Data Time Async LogState Text Service DEPS_UNIX dl ) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 458d156..7ab3e31 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -252,4 +252,56 @@ if(TARGET VoidTests AND TARGET Void::Plugin) ) add_dependencies(VoidTests VoidServicePluginV1 VoidServicePluginV2) endif() + + enable_language(C) + function(_void_add_cabi_fixture target_name source_file) + add_library(${target_name} SHARED "${CMAKE_CURRENT_SOURCE_DIR}/plugins/${source_file}") + target_include_directories(${target_name} PRIVATE "${CMAKE_SOURCE_DIR}/include") + set_target_properties(${target_name} PROPERTIES + C_STANDARD 11 + C_STANDARD_REQUIRED ON + C_EXTENSIONS OFF + VOID_TESTING_NO_AUTO_SCAN TRUE) + if(VOID_WARNINGS_AS_ERRORS) + target_compile_options(${target_name} PRIVATE -Wall -Wextra -Wpedantic -Werror) + endif() + if(VOID_ENABLE_ASAN) + target_compile_options(${target_name} PRIVATE -fsanitize=address -fno-omit-frame-pointer) + target_link_options(${target_name} PRIVATE -fsanitize=address) + endif() + if(VOID_ENABLE_UBSAN) + target_compile_options(${target_name} PRIVATE -fsanitize=undefined) + target_link_options(${target_name} PRIVATE -fsanitize=undefined) + endif() + if(VOID_ENABLE_TSAN) + target_compile_options(${target_name} PRIVATE -fsanitize=thread) + target_link_options(${target_name} PRIVATE -fsanitize=thread) + endif() + foreach(_def IN LISTS ARGN) + target_compile_definitions(${target_name} PRIVATE "${_def}") + endforeach() + add_dependencies(VoidTests ${target_name}) + endfunction() + + _void_add_cabi_fixture(VoidCAbiPluginV1 CAbiPluginV1.c) + _void_add_cabi_fixture(VoidCAbiPluginV2 CAbiPluginV2.c) + _void_add_cabi_fixture(VoidCAbiBadTrunc CAbiBadPlugin.c "BAD_MODE=1") + _void_add_cabi_fixture(VoidCAbiBadMajor CAbiBadPlugin.c "BAD_MODE=2") + _void_add_cabi_fixture(VoidCAbiBadReserved CAbiBadPlugin.c "BAD_MODE=3") + _void_add_cabi_fixture(VoidCAbiDepA CAbiDepPlugin.c "DEP_MODE=1") + _void_add_cabi_fixture(VoidCAbiDepB CAbiDepPlugin.c "DEP_MODE=2") + _void_add_cabi_fixture(VoidCAbiCycA CAbiDepPlugin.c "DEP_MODE=3") + _void_add_cabi_fixture(VoidCAbiCycB CAbiDepPlugin.c "DEP_MODE=4") + + target_compile_definitions(VoidTests PRIVATE + "VOID_CABI_V1_PATH=\"$\"" + "VOID_CABI_V2_PATH=\"$\"" + "VOID_CABI_BAD_TRUNC_PATH=\"$\"" + "VOID_CABI_BAD_MAJOR_PATH=\"$\"" + "VOID_CABI_BAD_RESERVED_PATH=\"$\"" + "VOID_CABI_DEP_A_PATH=\"$\"" + "VOID_CABI_DEP_B_PATH=\"$\"" + "VOID_CABI_CYC_A_PATH=\"$\"" + "VOID_CABI_CYC_B_PATH=\"$\"" + ) endif() diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 0e4289c..0e11b78 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -252,6 +252,16 @@ if(_has_service_plugin) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_plugin Plugin Core Functional System Data Time Async LogState Text Service) +if(_has_plugin) + run_consumer(PluginOnly "${install_prefix}" "PluginOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/PluginOnly/CMakeLists.txt b/tests/package/PluginOnly/CMakeLists.txt new file mode 100644 index 0000000..93b102f --- /dev/null +++ b/tests/package/PluginOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidPluginOnlyConsumer LANGUAGES C CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Plugin) + +add_executable(void_plugin_only_consumer main.cpp) +target_link_libraries(void_plugin_only_consumer PRIVATE Void::Plugin) +target_compile_features(void_plugin_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME PluginOnlyConsumer COMMAND void_plugin_only_consumer) diff --git a/tests/package/PluginOnly/main.cpp b/tests/package/PluginOnly/main.cpp new file mode 100644 index 0000000..cde5c87 --- /dev/null +++ b/tests/package/PluginOnly/main.cpp @@ -0,0 +1,18 @@ +#include +#include +#include +#include + +#include + +int main() +{ + Void::Plugin::PluginHostLimits limits{}; + Void::Plugin::CModuleHost host{limits}; + const auto loaded = host.acquire("missing"); + void_module_api_v1 api{}; + api.struct_size = sizeof(api); + api.abi_major = VOID_CABI_MAJOR_V1; + api.abi_minor = VOID_CABI_MINOR_V1; + return !loaded && api.abi_major == 1u ? 0 : 1; +} diff --git a/tests/plugins/CAbiBadPlugin.c b/tests/plugins/CAbiBadPlugin.c new file mode 100644 index 0000000..610b339 --- /dev/null +++ b/tests/plugins/CAbiBadPlugin.c @@ -0,0 +1,78 @@ +#include + +#include +#include + +#ifndef BAD_MODE +#define BAD_MODE 1 +#endif + +static int32_t stub_get_info(void_module_info_v1* out) +{ + if (out == NULL) return VOID_STATUS_INVALID_ARGUMENT; + memset(out, 0, sizeof(*out)); + out->struct_size = (uint32_t)sizeof(void_module_info_v1); + out->module_id = "cabi.bad"; + out->version = "1.0.0"; + return VOID_STATUS_OK; +} + +static int32_t stub_create(const void_host_api_v1* h, void_module_handle** out) +{ + (void)h; + if (out != NULL) *out = NULL; + return VOID_STATUS_INTERNAL; +} + +static int32_t stub_activate(void_module_handle* h, void_bytes_v1 c, void_error_detail_v1* e) +{ + (void)h; (void)c; (void)e; + return VOID_STATUS_OK; +} + +static int32_t stub_readiness(void_module_handle* h, uint32_t* r, void_error_detail_v1* e) +{ + (void)h; (void)r; (void)e; + return VOID_STATUS_OK; +} + +static int32_t stub_stop(void_module_handle* h) +{ + (void)h; + return VOID_STATUS_OK; +} + +static void stub_destroy(void_module_handle* h) { (void)h; } + +int32_t void_module_query_v1(uint32_t host_struct_size, + void_module_api_v1* out_api) +{ + (void)host_struct_size; + if (out_api == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_api, 0, sizeof(*out_api)); + out_api->struct_size = (uint32_t)sizeof(void_module_api_v1); + out_api->abi_major = VOID_CABI_MAJOR_V1; + out_api->abi_minor = VOID_CABI_MINOR_V1; + out_api->reserved = 0; + out_api->get_info = stub_get_info; + out_api->create = stub_create; + out_api->activate = stub_activate; + out_api->readiness = stub_readiness; + out_api->request_stop = stub_stop; + out_api->deactivate = stub_stop; + out_api->destroy = stub_destroy; + +#if BAD_MODE == 1 + /* Truncated struct_size */ + out_api->struct_size = 16u; +#elif BAD_MODE == 2 + /* Unsupported abi_major */ + out_api->abi_major = 99u; +#elif BAD_MODE == 3 + /* Non-zero reserved */ + out_api->reserved = 1u; +#endif + return VOID_STATUS_OK; +} diff --git a/tests/plugins/CAbiDepPlugin.c b/tests/plugins/CAbiDepPlugin.c new file mode 100644 index 0000000..54f1e4e --- /dev/null +++ b/tests/plugins/CAbiDepPlugin.c @@ -0,0 +1,104 @@ +#include + +#include +#include +#include + +#ifndef DEP_MODE +#define DEP_MODE 1 +#endif + +struct void_module_handle { + int dummy; +}; + +#if DEP_MODE == 2 +static const void_dependency_v1 kDeps[] = { + {.module_id = "cabi.dep.a", .version_range = "^1.0.0", .optional_dep = 0}, +}; +#elif DEP_MODE == 3 +static const void_dependency_v1 kDeps[] = { + {.module_id = "cabi.cyc.b", .version_range = "^1.0.0", .optional_dep = 0}, +}; +#elif DEP_MODE == 4 +static const void_dependency_v1 kDeps[] = { + {.module_id = "cabi.cyc.a", .version_range = "^1.0.0", .optional_dep = 0}, +}; +#endif + +static int32_t dep_get_info(void_module_info_v1* out) +{ + if (out == NULL) return VOID_STATUS_INVALID_ARGUMENT; + memset(out, 0, sizeof(*out)); + out->struct_size = (uint32_t)sizeof(void_module_info_v1); +#if DEP_MODE == 1 + out->module_id = "cabi.dep.a"; + out->version = "1.0.0"; + out->activation_policy = VOID_POLICY_RESTART_REQUIRED; +#elif DEP_MODE == 2 + out->module_id = "cabi.dep.b"; + out->version = "1.0.0"; + out->activation_policy = VOID_POLICY_RELOADABLE; + out->dependencies = kDeps; + out->dependency_count = 1u; +#elif DEP_MODE == 3 + out->module_id = "cabi.cyc.a"; + out->version = "1.0.0"; + out->dependencies = kDeps; + out->dependency_count = 1u; +#elif DEP_MODE == 4 + out->module_id = "cabi.cyc.b"; + out->version = "1.0.0"; + out->dependencies = kDeps; + out->dependency_count = 1u; +#endif + return VOID_STATUS_OK; +} + +static int32_t dep_create(const void_host_api_v1* h, void_module_handle** out) +{ + (void)h; + *out = (struct void_module_handle*)calloc(1, sizeof(struct void_module_handle)); + return *out ? VOID_STATUS_OK : VOID_STATUS_EXHAUSTED; +} + +static int32_t dep_activate(void_module_handle* h, void_bytes_v1 c, void_error_detail_v1* e) +{ + (void)h; (void)c; (void)e; + return VOID_STATUS_OK; +} + +static int32_t dep_readiness(void_module_handle* h, uint32_t* r, void_error_detail_v1* e) +{ + (void)h; (void)e; + *r = 1u; + return VOID_STATUS_OK; +} + +static int32_t dep_stop(void_module_handle* h) +{ + (void)h; + return VOID_STATUS_OK; +} + +static void dep_destroy(void_module_handle* h) { free(h); } + +int32_t void_module_query_v1(uint32_t host_struct_size, + void_module_api_v1* out_api) +{ + if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_api, 0, sizeof(*out_api)); + out_api->struct_size = (uint32_t)sizeof(void_module_api_v1); + out_api->abi_major = VOID_CABI_MAJOR_V1; + out_api->abi_minor = VOID_CABI_MINOR_V1; + out_api->get_info = dep_get_info; + out_api->create = dep_create; + out_api->activate = dep_activate; + out_api->readiness = dep_readiness; + out_api->request_stop = dep_stop; + out_api->deactivate = dep_stop; + out_api->destroy = dep_destroy; + return VOID_STATUS_OK; +} diff --git a/tests/plugins/CAbiPluginV1.c b/tests/plugins/CAbiPluginV1.c new file mode 100644 index 0000000..c3ea077 --- /dev/null +++ b/tests/plugins/CAbiPluginV1.c @@ -0,0 +1,488 @@ +#include + +#include +#include +#include +#include +#include +#include + +typedef struct cabi_calc_v1 { + uint32_t (*version)(void_module_handle* h); + int32_t (*accumulate)(void_module_handle* h, int32_t delta); +} cabi_calc_v1; + +struct void_operation_handle { + void_module_handle* owner; + thrd_t worker; + int worker_started; + atomic_int cancelled; + uint32_t op_kind; + int32_t delta; + void_async_complete_fn cb; + void* cb_ctx; +}; + +struct void_module_handle { + void_host_api_v1 host; + atomic_int total; + atomic_int quiescing; + int fail_quiesce; + int fail_resume; + int ckpt_fail; + int ckpt_oversized; + int ready; + mtx_t ops_mu; + struct void_operation_handle* ops[64]; + size_t ops_count; +}; + +static const void_interface_id_v1 kCalcIfaceId = { + {0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01}}; + +static void free_c_str(void* ctx, const char* msg) +{ + (void)ctx; + free((void*)msg); +} + +static void free_c_bytes(void* ctx, const uint8_t* data, uint64_t size) +{ + (void)ctx; + (void)size; + free((void*)data); +} + +static void set_err(void_error_detail_v1* out_err, + int32_t status, + const char* text) +{ + if (out_err == NULL || out_err->struct_size < sizeof(void_error_detail_v1)) { + return; + } + out_err->status = status; + if (text != NULL) { + size_t n = strlen(text); + char* copy = (char*)malloc(n + 1); + if (copy != NULL) { + memcpy(copy, text, n + 1); + out_err->message = copy; + out_err->release = free_c_str; + out_err->release_ctx = NULL; + } + } +} + +static int cfg_has(void_bytes_v1 cfg, const char* needle) +{ + if (cfg.data == NULL || cfg.size == 0) { + return 0; + } + size_t nlen = strlen(needle); + if (cfg.size < nlen) { + return 0; + } + for (uint64_t i = 0; i + nlen <= cfg.size; ++i) { + if (memcmp(cfg.data + i, needle, nlen) == 0) { + return 1; + } + } + return 0; +} + +static int32_t cabi_get_info(void_module_info_v1* out_info) +{ + if (out_info == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_info, 0, sizeof(*out_info)); + out_info->struct_size = (uint32_t)sizeof(void_module_info_v1); + out_info->module_id = "cabi.calc"; + out_info->version = "1.0.0"; + out_info->activation_policy = VOID_POLICY_RELOADABLE; + out_info->state_schema_version = 1; + out_info->dependencies = NULL; + out_info->dependency_count = 0; + return VOID_STATUS_OK; +} + +static int32_t cabi_create(const void_host_api_v1* host_api, + void_module_handle** out_handle) +{ + if (out_handle == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_handle = NULL; + if (host_api == NULL || host_api->struct_size < sizeof(void_host_api_v1)) { + return VOID_STATUS_INVALID_ARGUMENT; + } + struct void_module_handle* h = + (struct void_module_handle*)calloc(1, sizeof(*h)); + if (h == NULL) { + return VOID_STATUS_EXHAUSTED; + } + h->host = *host_api; + atomic_init(&h->total, 0); + atomic_init(&h->quiescing, 0); + h->ready = 1; + mtx_init(&h->ops_mu, mtx_plain); + *out_handle = h; + return VOID_STATUS_OK; +} + +static int32_t cabi_activate(void_module_handle* h, + void_bytes_v1 config, + void_error_detail_v1* out_err) +{ + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (cfg_has(config, "fail_activate")) { + set_err(out_err, VOID_STATUS_INTERNAL, "V1 activation rejected"); + return VOID_STATUS_INTERNAL; + } + h->ready = cfg_has(config, "not_ready") ? 0 : 1; + h->fail_quiesce = cfg_has(config, "quiesce_fail"); + h->fail_resume = cfg_has(config, "quiesce_fail_resume_fail"); + if (h->fail_resume) { + h->fail_quiesce = 1; + } + h->ckpt_fail = cfg_has(config, "ckpt_fail"); + h->ckpt_oversized = cfg_has(config, "ckpt_oversized"); + return VOID_STATUS_OK; +} + +static int32_t cabi_readiness(void_module_handle* h, + uint32_t* out_ready, + void_error_detail_v1* out_err) +{ + if (h == NULL || out_ready == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_ready = h->ready ? 1u : 0u; + if (!h->ready) { + set_err(out_err, VOID_STATUS_NOT_READY, "V1 not ready"); + } + return VOID_STATUS_OK; +} + +static int32_t cabi_quiesce(void_module_handle* h, + const void_op_options_v1* opts, + void_error_detail_v1* out_err) +{ + (void)opts; + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + atomic_store(&h->quiescing, 1); + if (h->fail_quiesce) { + set_err(out_err, VOID_STATUS_QUIESCING, "V1 quiesce refused"); + return VOID_STATUS_QUIESCING; + } + return VOID_STATUS_OK; +} + +static int32_t cabi_resume(void_module_handle* h, void_error_detail_v1* out_err) +{ + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (h->fail_resume) { + set_err(out_err, VOID_STATUS_INTERNAL, "V1 resume failed"); + return VOID_STATUS_INTERNAL; + } + atomic_store(&h->quiescing, 0); + return VOID_STATUS_OK; +} + +static int32_t cabi_checkpoint(void_module_handle* h, + const void_op_options_v1* opts, + void_owned_bytes_v1* out_state, + void_error_detail_v1* out_err) +{ + (void)opts; + if (h == NULL || out_state == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_state, 0, sizeof(*out_state)); + if (h->ckpt_fail) { + set_err(out_err, VOID_STATUS_INTERNAL, "V1 checkpoint error"); + return VOID_STATUS_INTERNAL; + } + if (h->ckpt_oversized) { + uint8_t* dummy = (uint8_t*)malloc(16); + out_state->data = dummy; + out_state->size = UINT64_C(8) * UINT64_C(1024) * UINT64_C(1024); + out_state->release = free_c_bytes; + out_state->release_ctx = NULL; + return VOID_STATUS_OK; + } + char buf[64]; + int n = snprintf(buf, sizeof(buf), "v1:%d", atomic_load(&h->total)); + if (n <= 0) { + return VOID_STATUS_INTERNAL; + } + uint8_t* copy = (uint8_t*)malloc((size_t)n); + if (copy == NULL) { + return VOID_STATUS_EXHAUSTED; + } + memcpy(copy, buf, (size_t)n); + out_state->data = copy; + out_state->size = (uint64_t)n; + out_state->release = free_c_bytes; + out_state->release_ctx = NULL; + return VOID_STATUS_OK; +} + +static int32_t cabi_restore(void_module_handle* h, + void_bytes_v1 state, + void_error_detail_v1* out_err) +{ + (void)h; + (void)state; + (void)out_err; + return VOID_STATUS_OK; +} + +static uint32_t iface_get_version(void_module_handle* h) +{ + (void)h; + return 1u; +} + +static int32_t iface_accumulate(void_module_handle* h, int32_t delta) +{ + if (h == NULL) { + return -1; + } + if (atomic_load(&h->quiescing) != 0 && delta != 0) { + return -1; + } + return atomic_fetch_add(&h->total, delta) + delta; +} + +static const cabi_calc_v1 kCalcTable = {iface_get_version, iface_accumulate}; + +static int32_t cabi_query_interface(void_module_handle* h, + const void_interface_id_v1* iface_id, + uint32_t min_major, + uint32_t min_table_size, + void_interface_view_v1* out_view) +{ + if (h == NULL || iface_id == NULL || out_view == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (memcmp(iface_id->bytes, kCalcIfaceId.bytes, 16) != 0) { + return VOID_STATUS_NOT_FOUND; + } + if (min_major != 1u || min_table_size > sizeof(cabi_calc_v1)) { + return VOID_STATUS_UNSUPPORTED; + } + out_view->struct_size = (uint32_t)sizeof(void_interface_view_v1); + out_view->major = 1u; + out_view->minor = 0u; + out_view->table_size = (uint32_t)sizeof(cabi_calc_v1); + out_view->function_table = &kCalcTable; + return VOID_STATUS_OK; +} + +static void cabi_release_interface(void_module_handle* h, + const void_interface_id_v1* iface_id, + const void_interface_view_v1* view) +{ + (void)h; + (void)iface_id; + (void)view; +} + +static int async_worker(void* arg) +{ + struct void_operation_handle* op = (struct void_operation_handle*)arg; + int pinned = 0; + if (op->op_kind == 3u && op->owner->host.acquire_activity_pin != NULL) { + if (op->owner->host.acquire_activity_pin( + op->owner->host.host_ctx, op->owner->host.generation) == + VOID_STATUS_OK) { + pinned = 1; + } + } + struct timespec ts = {.tv_sec = 0, .tv_nsec = 2000000}; + for (int i = 0; i < 10; ++i) { + if (atomic_load(&op->cancelled) != 0) { + op->cb(op->cb_ctx, VOID_STATUS_CANCELLED, NULL); + if (pinned) { + op->owner->host.release_activity_pin( + op->owner->host.host_ctx, op->owner->host.generation); + } + return 0; + } + thrd_sleep(&ts, NULL); + } + int32_t val = atomic_fetch_add(&op->owner->total, op->delta) + op->delta; + uint8_t buf[4]; + memcpy(buf, &val, sizeof(val)); + void_bytes_v1 res = {.data = buf, .size = sizeof(buf)}; + op->cb(op->cb_ctx, VOID_STATUS_OK, &res); + if (pinned) { + op->owner->host.release_activity_pin(op->owner->host.host_ctx, + op->owner->host.generation); + } + return 0; +} + +static int32_t cabi_submit_async(void_module_handle* h, + uint32_t op_kind, + void_bytes_v1 payload, + const void_op_options_v1* opts, + void_async_complete_fn cb, + void* cb_ctx, + void_operation_handle** out_op, + void_error_detail_v1* out_err) +{ + (void)out_err; + if (h == NULL || cb == NULL || out_op == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_op = NULL; + if (opts != NULL && opts->stop_requested) { + return VOID_STATUS_CANCELLED; + } + int32_t delta = 0; + if (payload.data != NULL && payload.size >= 4) { + memcpy(&delta, payload.data, 4); + } + struct void_operation_handle* op = + (struct void_operation_handle*)calloc(1, sizeof(*op)); + if (op == NULL) { + return VOID_STATUS_EXHAUSTED; + } + op->owner = h; + op->op_kind = op_kind; + op->delta = delta; + op->cb = cb; + op->cb_ctx = cb_ctx; + atomic_init(&op->cancelled, 0); + + if (op_kind == 2u) { + int32_t val = atomic_fetch_add(&h->total, delta) + delta; + uint8_t buf[4]; + memcpy(buf, &val, sizeof(val)); + void_bytes_v1 res = {.data = buf, .size = sizeof(buf)}; + *out_op = op; + cb(cb_ctx, VOID_STATUS_OK, &res); + return VOID_STATUS_OK; + } + + mtx_lock(&h->ops_mu); + if (h->ops_count < 64) { + h->ops[h->ops_count++] = op; + } + mtx_unlock(&h->ops_mu); + + op->worker_started = 1; + *out_op = op; + if (thrd_create(&op->worker, async_worker, op) != thrd_success) { + op->worker_started = 0; + *out_op = NULL; + free(op); + return VOID_STATUS_INTERNAL; + } + return VOID_STATUS_OK; +} + +static int32_t cabi_cancel_async(void_module_handle* h, void_operation_handle* op) +{ + (void)h; + if (op == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + atomic_store(&op->cancelled, 1); + return VOID_STATUS_OK; +} + +static void cabi_release_async(void_module_handle* h, void_operation_handle* op) +{ + if (op == NULL) { + return; + } + if (op->worker_started) { + thrd_join(op->worker, NULL); + op->worker_started = 0; + } + if (h != NULL) { + mtx_lock(&h->ops_mu); + for (size_t i = 0; i < h->ops_count; ++i) { + if (h->ops[i] == op) { + h->ops[i] = h->ops[h->ops_count - 1]; + --h->ops_count; + break; + } + } + mtx_unlock(&h->ops_mu); + } + free(op); +} + +static int32_t cabi_request_stop(void_module_handle* h) +{ + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + atomic_store(&h->quiescing, 1); + mtx_lock(&h->ops_mu); + for (size_t i = 0; i < h->ops_count; ++i) { + if (h->ops[i] != NULL) { + atomic_store(&h->ops[i]->cancelled, 1); + } + } + mtx_unlock(&h->ops_mu); + return VOID_STATUS_OK; +} + +static int32_t cabi_deactivate(void_module_handle* h) +{ + return cabi_request_stop(h); +} + +static void cabi_destroy(void_module_handle* h) +{ + if (h == NULL) { + return; + } + mtx_destroy(&h->ops_mu); + free(h); +} + +int32_t void_module_query_v1(uint32_t host_struct_size, + void_module_api_v1* out_api) +{ + if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_api, 0, sizeof(*out_api)); + out_api->struct_size = (uint32_t)sizeof(void_module_api_v1); + out_api->abi_major = VOID_CABI_MAJOR_V1; + out_api->abi_minor = VOID_CABI_MINOR_V1; + out_api->reserved = 0; + out_api->capabilities = VOID_CAP_STATELESS_RELOAD | + VOID_CAP_STATEFUL_CHECKPOINT | VOID_CAP_ASYNC_OPS | + VOID_CAP_SERVICE_INTERFACES; + out_api->get_info = cabi_get_info; + out_api->create = cabi_create; + out_api->activate = cabi_activate; + out_api->readiness = cabi_readiness; + out_api->quiesce = cabi_quiesce; + out_api->resume = cabi_resume; + out_api->checkpoint = cabi_checkpoint; + out_api->restore = cabi_restore; + out_api->query_interface = cabi_query_interface; + out_api->release_interface = cabi_release_interface; + out_api->submit_async = cabi_submit_async; + out_api->cancel_async = cabi_cancel_async; + out_api->release_async = cabi_release_async; + out_api->request_stop = cabi_request_stop; + out_api->deactivate = cabi_deactivate; + out_api->destroy = cabi_destroy; + return VOID_STATUS_OK; +} diff --git a/tests/plugins/CAbiPluginV2.c b/tests/plugins/CAbiPluginV2.c new file mode 100644 index 0000000..8c81cc0 --- /dev/null +++ b/tests/plugins/CAbiPluginV2.c @@ -0,0 +1,357 @@ +#include + +#include +#include +#include +#include + +typedef struct cabi_calc_v1 { + uint32_t (*version)(void_module_handle* h); + int32_t (*accumulate)(void_module_handle* h, int32_t delta); +} cabi_calc_v1; + +struct void_module_handle { + void_host_api_v1 host; + atomic_int total; + int ready; +}; + +static const void_interface_id_v1 kCalcIfaceId = { + {0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01}}; + +static void free_c_str(void* ctx, const char* msg) +{ + (void)ctx; + free((void*)msg); +} + +static void free_c_bytes(void* ctx, const uint8_t* data, uint64_t size) +{ + (void)ctx; + (void)size; + free((void*)data); +} + +static void set_err(void_error_detail_v1* out_err, + int32_t status, + const char* text) +{ + if (out_err == NULL || out_err->struct_size < sizeof(void_error_detail_v1)) { + return; + } + out_err->status = status; + if (text != NULL) { + size_t n = strlen(text); + char* copy = (char*)malloc(n + 1); + if (copy != NULL) { + memcpy(copy, text, n + 1); + out_err->message = copy; + out_err->release = free_c_str; + out_err->release_ctx = NULL; + } + } +} + +static int cfg_has(void_bytes_v1 cfg, const char* needle) +{ + if (cfg.data == NULL || cfg.size == 0) { + return 0; + } + size_t nlen = strlen(needle); + if (cfg.size < nlen) { + return 0; + } + for (uint64_t i = 0; i + nlen <= cfg.size; ++i) { + if (memcmp(cfg.data + i, needle, nlen) == 0) { + return 1; + } + } + return 0; +} + +static int32_t cabi_v2_get_info(void_module_info_v1* out_info) +{ + if (out_info == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_info, 0, sizeof(*out_info)); + out_info->struct_size = (uint32_t)sizeof(void_module_info_v1); + out_info->module_id = "cabi.calc"; + out_info->version = "2.0.0"; + out_info->activation_policy = VOID_POLICY_RELOADABLE; + out_info->state_schema_version = 2; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_create(const void_host_api_v1* host_api, + void_module_handle** out_handle) +{ + if (out_handle == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_handle = NULL; + if (host_api == NULL || host_api->struct_size < sizeof(void_host_api_v1)) { + return VOID_STATUS_INVALID_ARGUMENT; + } + struct void_module_handle* h = + (struct void_module_handle*)calloc(1, sizeof(*h)); + if (h == NULL) { + return VOID_STATUS_EXHAUSTED; + } + h->host = *host_api; + atomic_init(&h->total, 0); + h->ready = 1; + *out_handle = h; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_activate(void_module_handle* h, + void_bytes_v1 config, + void_error_detail_v1* out_err) +{ + if (h == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (cfg_has(config, "fail_activate")) { + set_err(out_err, VOID_STATUS_INTERNAL, "V2 activation failed"); + return VOID_STATUS_INTERNAL; + } + h->ready = cfg_has(config, "not_ready") ? 0 : 1; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_readiness(void_module_handle* h, + uint32_t* out_ready, + void_error_detail_v1* out_err) +{ + if (h == NULL || out_ready == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + *out_ready = h->ready ? 1u : 0u; + if (!h->ready) { + set_err(out_err, VOID_STATUS_NOT_READY, "V2 not ready"); + } + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_quiesce(void_module_handle* h, + const void_op_options_v1* opts, + void_error_detail_v1* out_err) +{ + (void)h; + (void)opts; + (void)out_err; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_resume(void_module_handle* h, + void_error_detail_v1* out_err) +{ + (void)h; + (void)out_err; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_checkpoint(void_module_handle* h, + const void_op_options_v1* opts, + void_owned_bytes_v1* out_state, + void_error_detail_v1* out_err) +{ + (void)opts; + (void)out_err; + if (h == NULL || out_state == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + char buf[64]; + int val = atomic_load(&h->total); + int len = 0; + if (val == 0) { + memcpy(buf, "v2:0", 4); + len = 4; + } else { + /* Decimal conversion without stdio overhead. */ + char rev[32]; + int rlen = 0; + int neg = val < 0; + unsigned u = neg ? (unsigned)(-val) : (unsigned)val; + while (u > 0) { + rev[rlen++] = (char)('0' + (u % 10u)); + u /= 10u; + } + buf[len++] = 'v'; + buf[len++] = '2'; + buf[len++] = ':'; + if (neg) { + buf[len++] = '-'; + } + while (rlen > 0) { + buf[len++] = rev[--rlen]; + } + } + uint8_t* copy = (uint8_t*)malloc((size_t)len); + if (copy == NULL) { + return VOID_STATUS_EXHAUSTED; + } + memcpy(copy, buf, (size_t)len); + out_state->data = copy; + out_state->size = (uint64_t)len; + out_state->release = free_c_bytes; + out_state->release_ctx = NULL; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_restore(void_module_handle* h, + void_bytes_v1 state, + void_error_detail_v1* out_err) +{ + if (h == NULL || state.data == NULL || state.size < 4) { + set_err(out_err, VOID_STATUS_STATE_REJECTED, "V2 invalid checkpoint"); + return VOID_STATUS_STATE_REJECTED; + } + if (memcmp(state.data, "v1:", 3) != 0 && + memcmp(state.data, "v2:", 3) != 0) { + set_err(out_err, VOID_STATUS_STATE_REJECTED, "V2 unknown checkpoint header"); + return VOID_STATUS_STATE_REJECTED; + } + char buf[64]; + size_t n = (size_t)(state.size - 3); + if (n >= sizeof(buf)) { + return VOID_STATUS_STATE_REJECTED; + } + memcpy(buf, state.data + 3, n); + buf[n] = '\0'; + int val = atoi(buf); + atomic_store(&h->total, val); + return VOID_STATUS_OK; +} + +static uint32_t iface_v2_version(void_module_handle* h) +{ + (void)h; + return 2u; +} + +static int32_t iface_v2_accumulate(void_module_handle* h, int32_t delta) +{ + if (h == NULL) { + return -1; + } + return atomic_fetch_add(&h->total, delta) + delta; +} + +static const cabi_calc_v1 kCalcV2 = {iface_v2_version, iface_v2_accumulate}; + +static int32_t cabi_v2_query_interface(void_module_handle* h, + const void_interface_id_v1* iface_id, + uint32_t min_major, + uint32_t min_table_size, + void_interface_view_v1* out_view) +{ + if (h == NULL || iface_id == NULL || out_view == NULL) { + return VOID_STATUS_INVALID_ARGUMENT; + } + if (memcmp(iface_id->bytes, kCalcIfaceId.bytes, 16) != 0) { + return VOID_STATUS_NOT_FOUND; + } + if (min_major != 1u || min_table_size > sizeof(cabi_calc_v1)) { + return VOID_STATUS_UNSUPPORTED; + } + out_view->struct_size = (uint32_t)sizeof(void_interface_view_v1); + out_view->major = 1u; + out_view->minor = 1u; + out_view->table_size = (uint32_t)sizeof(cabi_calc_v1); + out_view->function_table = &kCalcV2; + return VOID_STATUS_OK; +} + +static void cabi_v2_release_interface(void_module_handle* h, + const void_interface_id_v1* iface_id, + const void_interface_view_v1* view) +{ + (void)h; + (void)iface_id; + (void)view; +} + +static int32_t cabi_v2_submit_async(void_module_handle* h, + uint32_t op_kind, + void_bytes_v1 payload, + const void_op_options_v1* opts, + void_async_complete_fn cb, + void* cb_ctx, + void_operation_handle** out_op, + void_error_detail_v1* out_err) +{ + (void)h; + (void)op_kind; + (void)payload; + (void)opts; + (void)cb; + (void)cb_ctx; + (void)out_op; + (void)out_err; + return VOID_STATUS_UNSUPPORTED; +} + +static int32_t cabi_v2_cancel_async(void_module_handle* h, + void_operation_handle* op) +{ + (void)h; + (void)op; + return VOID_STATUS_UNSUPPORTED; +} + +static void cabi_v2_release_async(void_module_handle* h, + void_operation_handle* op) +{ + (void)h; + (void)op; +} + +static int32_t cabi_v2_request_stop(void_module_handle* h) +{ + (void)h; + return VOID_STATUS_OK; +} + +static int32_t cabi_v2_deactivate(void_module_handle* h) +{ + (void)h; + return VOID_STATUS_OK; +} + +static void cabi_v2_destroy(void_module_handle* h) { free(h); } + +int32_t void_module_query_v1(uint32_t host_struct_size, + void_module_api_v1* out_api) +{ + if (out_api == NULL || host_struct_size < VOID_MODULE_API_V1_MIN_SIZE) { + return VOID_STATUS_INVALID_ARGUMENT; + } + memset(out_api, 0, sizeof(*out_api)); + out_api->struct_size = (uint32_t)sizeof(void_module_api_v1); + out_api->abi_major = VOID_CABI_MAJOR_V1; + out_api->abi_minor = VOID_CABI_MINOR_V1; + out_api->reserved = 0; + out_api->capabilities = VOID_CAP_STATELESS_RELOAD | + VOID_CAP_STATEFUL_CHECKPOINT | + VOID_CAP_SERVICE_INTERFACES; + out_api->get_info = cabi_v2_get_info; + out_api->create = cabi_v2_create; + out_api->activate = cabi_v2_activate; + out_api->readiness = cabi_v2_readiness; + out_api->quiesce = cabi_v2_quiesce; + out_api->resume = cabi_v2_resume; + out_api->checkpoint = cabi_v2_checkpoint; + out_api->restore = cabi_v2_restore; + out_api->query_interface = cabi_v2_query_interface; + out_api->release_interface = cabi_v2_release_interface; + out_api->submit_async = cabi_v2_submit_async; + out_api->cancel_async = cabi_v2_cancel_async; + out_api->release_async = cabi_v2_release_async; + out_api->request_stop = cabi_v2_request_stop; + out_api->deactivate = cabi_v2_deactivate; + out_api->destroy = cabi_v2_destroy; + return VOID_STATUS_OK; +} diff --git a/tests/standalone/Plugin/PluginHardening.cpp b/tests/standalone/Plugin/PluginHardening.cpp new file mode 100644 index 0000000..17d3a99 --- /dev/null +++ b/tests/standalone/Plugin/PluginHardening.cpp @@ -0,0 +1,315 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Plugin; + + struct CabiCalcTable { + uint32_t (*version)(void_module_handle* h); + int32_t (*accumulate)(void_module_handle* h, int32_t delta); + }; + + const void_interface_id_v1 kCalcIfaceId{ + {0x76, 0x6f, 0x69, 0x64, 0x63, 0x61, 0x6c, 0x63, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01}}; + + std::vector encode_i32_le(std::int32_t v) + { + std::vector out(4); + std::memcpy(out.data(), &v, 4); + return out; + } + + std::int32_t decode_i32_le(const std::vector& b) + { + std::int32_t v = 0; + if (b.size() >= 4) { + std::memcpy(&v, b.data(), 4); + } + return v; + } +} // namespace + +#if defined(VOID_CABI_V1_PATH) && defined(VOID_CABI_V2_PATH) && \ + __has_include() + +Void::Testing::Test plugin_cabi_v1_to_v2_stateful_quiesce_and_reload() +{ + PluginHostLimits limits{}; + limits.allow_safe_dlclose = true; + CModuleHost host{limits}; + + auto id = host.load(VOID_CABI_V1_PATH); + Void::Testing::require(id.has_value()); + Void::Testing::expect_eq(*id, std::string{"cabi.calc"}); + + auto g1 = host.acquire("cabi.calc"); + Void::Testing::require(static_cast(g1)); + const auto gen1 = g1.generation(); + + auto iface1 = g1.query_interface(kCalcIfaceId, 1, sizeof(CabiCalcTable)); + Void::Testing::require(iface1.has_value()); + const auto* t1 = iface1->table(); + Void::Testing::require(t1 != nullptr); + Void::Testing::expect_eq(t1->version(nullptr), std::uint32_t{1}); + + // Run async op on V1 (kind=3 pins activity via host API, kind=2 sync). + auto op_sync = g1.run_async(2u, encode_i32_le(15)); + Void::Testing::require(op_sync.has_value()); + Void::Testing::expect_eq(decode_i32_le(*op_sync), 15); + + auto op_async = g1.run_async(3u, encode_i32_le(25)); + Void::Testing::require(op_async.has_value()); + Void::Testing::expect_eq(decode_i32_le(*op_async), 40); + + // Reload V1 -> V2 while g1 + iface1 are still pinned! + auto gen2_res = + host.replace("cabi.calc", VOID_CABI_V2_PATH, {}, gen1); + Void::Testing::require(gen2_res.has_value()); + Void::Testing::expect(*gen2_res > gen1); + + // Old generation stays mapped & live until both leases drop. + auto retained_mid = host.retained_generations("cabi.calc"); + Void::Testing::expect_eq(retained_mid.size(), std::size_t{2}); + + // Acquire V2 interface and confirm checkpoint migrated 40 -> V2. + auto g2 = host.acquire("cabi.calc"); + Void::Testing::require(static_cast(g2)); + auto iface2 = g2.query_interface(kCalcIfaceId, 1, sizeof(CabiCalcTable)); + Void::Testing::require(iface2.has_value()); + const auto* t2 = iface2->table(); + Void::Testing::expect_eq(t2->version(nullptr), std::uint32_t{2}); + + auto op2 = g2.run_async(1u, encode_i32_le(5)); + // V2 does not implement async ops -> UNSUPPORTED mapped to abi_mismatch. + Void::Testing::expect(!op2.has_value()); + + // Old iface1/g1 still pinned; V1 sees quiesced mutation return -1. + Void::Testing::expect_eq(t1->version(nullptr), std::uint32_t{1}); + + // Drop all pins to gen1 and verify host retirement thread dlcloses gen1. + iface1 = InterfaceLease{}; + g1 = GenerationLease{}; + for (int i = 0; i < 100; ++i) { + if (host.retained_generations("cabi.calc").size() == 1) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + } + Void::Testing::expect_eq(host.retained_generations("cabi.calc").size(), + std::size_t{1}); +} + +Void::Testing::Test plugin_cabi_async_cancel_and_safe_dlclose_wait() +{ + PluginHostLimits limits{}; + limits.allow_safe_dlclose = true; + CModuleHost host{limits}; + + Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value()); + auto lease = host.acquire("cabi.calc"); + ActivityPin extra_pin = lease.acquire_activity_pin(); + + std::stop_source ss; + std::thread canceller([&] { + std::this_thread::sleep_for(std::chrono::milliseconds{2}); + ss.request_stop(); + }); + Void::Async::OperationOptions opts; + opts.stop = ss.get_token(); + auto res = lease.run_async(1u, encode_i32_le(1), opts); + canceller.join(); + Void::Testing::expect(!res.has_value()); + Void::Testing::expect_eq( + res.error().code().value, + static_cast(PluginErrorCode::cancelled)); + + // Unload while extra_pin + lease still exist -> cannot destroy/dlclose yet. + Void::Testing::require(host.unload("cabi.calc").has_value()); + lease = GenerationLease{}; + std::this_thread::sleep_for(std::chrono::milliseconds{10}); + extra_pin = ActivityPin{}; + host.close_and_join(); +} + +Void::Testing::Test plugin_cabi_bad_abi_oversized_ckpt_and_resume_degraded() +{ + CModuleHost host{PluginHostLimits{.allow_safe_dlclose = true}}; + + for (const char* bad_path : + {VOID_CABI_BAD_TRUNC_PATH, VOID_CABI_BAD_MAJOR_PATH, + VOID_CABI_BAD_RESERVED_PATH}) { + auto r = host.load(bad_path); + Void::Testing::expect(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(PluginErrorCode::abi_mismatch)); + } + + // Prepublication V2 readiness failure resumes V1 cleanly. + Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value()); + auto fail_v2 = + host.replace("cabi.calc", VOID_CABI_V2_PATH, "not_ready"); + Void::Testing::expect(!fail_v2.has_value()); + auto after = host.acquire("cabi.calc"); + Void::Testing::expect(after.health() == GenerationHealth::Healthy); + Void::Testing::expect_eq(after.version(), std::string_view{"1.0.0"}); + + // Reload into V1 with quiesce_fail_resume_fail -> failed reload leaves old + // generation marked Degraded. + Void::Testing::require( + host.replace("cabi.calc", VOID_CABI_V1_PATH, + "quiesce_fail_resume_fail") + .has_value()); + auto deg_attempt = host.replace("cabi.calc", VOID_CABI_V2_PATH); + Void::Testing::expect(!deg_attempt.has_value()); + Void::Testing::expect_eq( + deg_attempt.error().code().value, + static_cast(PluginErrorCode::resume_degraded)); + Void::Testing::expect(host.acquire("cabi.calc").health() == + GenerationHealth::Degraded); + Void::Testing::require(host.unload("cabi.calc").has_value()); + + // Oversized checkpoint rejected without crashing or leaking. + Void::Testing::require( + host.load(VOID_CABI_V1_PATH, "ckpt_oversized").has_value()); + auto ov = host.replace("cabi.calc", VOID_CABI_V2_PATH); + Void::Testing::expect(!ov.has_value()); + Void::Testing::expect_eq( + ov.error().code().value, + static_cast(PluginErrorCode::budget_exceeded)); +} + +Void::Testing::Test plugin_cabi_retention_byte_budget_and_dep_batch() +{ + // 4-generation retention cap + byte budget. + PluginHostLimits limits{}; + limits.allow_safe_dlclose = true; + limits.max_retained_generations = 4; + CModuleHost host{limits}; + + Void::Testing::require(host.load(VOID_CABI_V1_PATH).has_value()); + std::vector pins; + for (int i = 0; i < 3; ++i) { + pins.push_back(host.acquire("cabi.calc")); + auto next = host.replace("cabi.calc", VOID_CABI_V1_PATH); + Void::Testing::require(next.has_value()); + } + pins.push_back(host.acquire("cabi.calc")); + // Now 4 distinct generations are pinned -> 5th replace fails retention_limit. + auto cap_fail = host.replace("cabi.calc", VOID_CABI_V2_PATH); + Void::Testing::expect(!cap_fail.has_value()); + Void::Testing::expect_eq( + cap_fail.error().code().value, + static_cast(PluginErrorCode::retention_limit)); + Void::Testing::expect(host.mapped_bytes("cabi.calc") > 0); + pins.clear(); + + // Byte budget rejection. + PluginHostLimits tiny_mem{}; + tiny_mem.max_mapped_bytes_per_module = 1024; + CModuleHost tight{tiny_mem}; + auto too_big = tight.load(VOID_CABI_V1_PATH); + Void::Testing::expect(!too_big.has_value()); + Void::Testing::expect_eq( + too_big.error().code().value, + static_cast(PluginErrorCode::budget_exceeded)); + + // Dependency batch: B depends on A (supplied out of order) -> A sorted first. + CModuleHost batch_host; + auto batch_ok = batch_host.load_batch( + {{.path = VOID_CABI_DEP_B_PATH}, {.path = VOID_CABI_DEP_A_PATH}}); + Void::Testing::require(batch_ok.has_value()); + Void::Testing::expect_eq(batch_ok->size(), std::size_t{2}); + Void::Testing::expect_eq((*batch_ok)[0], std::string{"cabi.dep.a"}); + Void::Testing::expect_eq((*batch_ok)[1], std::string{"cabi.dep.b"}); + + // RestartRequired policy refuses live upgrade. + auto rr = batch_host.replace("cabi.dep.a", VOID_CABI_DEP_A_PATH); + Void::Testing::expect(!rr.has_value()); + Void::Testing::expect_eq( + rr.error().code().value, + static_cast(PluginErrorCode::restart_required)); + + // Cycle in batch rejected before activating anything. + CModuleHost cyc_host; + auto cyc_res = cyc_host.load_batch( + {{.path = VOID_CABI_CYC_A_PATH}, {.path = VOID_CABI_CYC_B_PATH}}); + Void::Testing::expect(!cyc_res.has_value()); + Void::Testing::expect_eq( + cyc_res.error().code().value, + static_cast(PluginErrorCode::cycle_detected)); +} + +Void::Testing::Test plugin_cpp_adapter_contains_exceptions_and_manager_unlocks() +{ + struct ThrowingModule final : Void::Plugin::IModule { + std::string_view name() const noexcept override { return "throw"; } + Void::Result::Result activate(Void::Plugin::ModuleHost&) override + { + throw std::runtime_error("boom"); + } + Void::Json::Value checkpoint() const override + { + throw std::runtime_error("ckpt-boom"); + } + }; + Void::Plugin::CModuleAdapterBox box{.module = std::make_unique()}; + void_error_detail_v1 err{}; + err.struct_size = sizeof(err); + Void::Testing::expect_eq(Void::Plugin::adapt_activate(&box, &err), + static_cast(VOID_STATUS_INTERNAL)); + if (err.release != nullptr && err.message != nullptr) { + Void::Testing::expect_eq(std::string_view{err.message}, + std::string_view{"boom"}); + err.release(err.release_ctx, err.message); + } + void_owned_bytes_v1 ck{}; + void_error_detail_v1 err2{}; + err2.struct_size = sizeof(err2); + Void::Testing::expect_eq(Void::Plugin::adapt_checkpoint(&box, &ck, &err2), + static_cast(VOID_STATUS_INTERNAL)); + if (err2.release != nullptr && err2.message != nullptr) { + err2.release(err2.release_ctx, err2.message); + } + + // Reentrant candidate/instance validator in PluginManager must NOT deadlock + // on m_mutex. +#if defined(VOID_STATEFUL_V1_PATH) && defined(VOID_STATEFUL_V2_PATH) + PluginManager* mgr_ptr = nullptr; + PluginManager mgr{{ + .instance_validator = [&](IPlugin&, const PluginInfo&) { + auto current = mgr_ptr->acquire("StatefulPlugin"); + auto all_names = mgr_ptr->names(); + return all_names.empty() || static_cast(current); + }, + .candidate_validator = [&](const PluginHandle&) { + auto current = mgr_ptr->acquire("StatefulPlugin"); + return static_cast(current) || mgr_ptr->names().empty(); + }, + }}; + mgr_ptr = &mgr; + Void::Testing::require(mgr.load(VOID_STATEFUL_V1_PATH).has_value()); + Void::Testing::require( + mgr.replace("StatefulPlugin", VOID_STATEFUL_V2_PATH).has_value()); +#endif +} + +#endif // C ABI fixtures available