From 691bd04e9708e55c29fb2bb723249e6405737e02 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:09:13 -0400 Subject: [PATCH] refactor(platform): own dynamically loaded API tables --- src/platform/linux/avahi_api.h | 356 ++++++++++++++++++ src/platform/linux/cuda.cpp | 114 ++---- src/platform/linux/dynamic_library.h | 58 +++ src/platform/linux/graphics.cpp | 57 +-- src/platform/linux/graphics.h | 60 ++- src/platform/linux/kmsgrab.cpp | 7 +- src/platform/linux/nvfbc_api.h | 79 ++++ src/platform/linux/publish.cpp | 249 +----------- src/platform/linux/vaapi.cpp | 5 +- src/platform/linux/x11grab.cpp | 87 +++-- .../windows/nvprefs/driver_settings.cpp | 82 ++-- .../windows/nvprefs/driver_settings.h | 41 +- .../nvprefs/nvapi_opensource_wrapper.cpp | 266 ++----------- .../nvprefs/nvapi_opensource_wrapper.h | 94 +++++ tests/unit/test_linux_dynamic_apis.cpp | 319 ++++++++++++++++ tests/unit/test_nvapi_opensource_wrapper.cpp | 150 ++++++++ 16 files changed, 1331 insertions(+), 693 deletions(-) create mode 100644 src/platform/linux/avahi_api.h create mode 100644 src/platform/linux/dynamic_library.h create mode 100644 src/platform/linux/nvfbc_api.h create mode 100644 src/platform/windows/nvprefs/nvapi_opensource_wrapper.h create mode 100644 tests/unit/test_linux_dynamic_apis.cpp create mode 100644 tests/unit/test_nvapi_opensource_wrapper.cpp diff --git a/src/platform/linux/avahi_api.h b/src/platform/linux/avahi_api.h new file mode 100644 index 000000000..029e50461 --- /dev/null +++ b/src/platform/linux/avahi_api.h @@ -0,0 +1,356 @@ +/** + * @file src/platform/linux/avahi_api.h + * @brief Avahi protocol types and immutable dynamic-library ownership. + * @note Adapted from https://www.avahi.org/doxygen/html/client-publish-service_8c-example.html + */ +#pragma once + +// standard includes +#include + +// local includes +#include "dynamic_library.h" + +namespace avahi { + + /** + * @brief Error codes used by avahi. + */ + enum err_e { + OK = 0, ///< OK + ERR_FAILURE = -1, ///< Generic error code + ERR_BAD_STATE = -2, ///< Object was in a bad state + ERR_INVALID_HOST_NAME = -3, ///< Invalid host name + ERR_INVALID_DOMAIN_NAME = -4, ///< Invalid domain name + ERR_NO_NETWORK = -5, ///< No suitable network protocol available + ERR_INVALID_TTL = -6, ///< Invalid DNS TTL + ERR_IS_PATTERN = -7, ///< RR key is pattern + ERR_COLLISION = -8, ///< Name collision + ERR_INVALID_RECORD = -9, ///< Invalid RR + + ERR_INVALID_SERVICE_NAME = -10, ///< Invalid service name + ERR_INVALID_SERVICE_TYPE = -11, ///< Invalid service type + ERR_INVALID_PORT = -12, ///< Invalid port number + ERR_INVALID_KEY = -13, ///< Invalid key + ERR_INVALID_ADDRESS = -14, ///< Invalid address + ERR_TIMEOUT = -15, ///< Timeout reached + ERR_TOO_MANY_CLIENTS = -16, ///< Too many clients + ERR_TOO_MANY_OBJECTS = -17, ///< Too many objects + ERR_TOO_MANY_ENTRIES = -18, ///< Too many entries + ERR_OS = -19, ///< OS error + + ERR_ACCESS_DENIED = -20, ///< Access denied + ERR_INVALID_OPERATION = -21, ///< Invalid operation + ERR_DBUS_ERROR = -22, ///< An unexpected D-Bus error occurred + ERR_DISCONNECTED = -23, ///< Daemon connection failed + ERR_NO_MEMORY = -24, ///< Memory exhausted + ERR_INVALID_OBJECT = -25, ///< The object passed to this function was invalid + ERR_NO_DAEMON = -26, ///< Daemon not running + ERR_INVALID_INTERFACE = -27, ///< Invalid interface + ERR_INVALID_PROTOCOL = -28, ///< Invalid protocol + ERR_INVALID_FLAGS = -29, ///< Invalid flags + + ERR_NOT_FOUND = -30, ///< Not found + ERR_INVALID_CONFIG = -31, ///< Configuration error + ERR_VERSION_MISMATCH = -32, ///< Version mismatch + ERR_INVALID_SERVICE_SUBTYPE = -33, ///< Invalid service subtype + ERR_INVALID_PACKET = -34, ///< Invalid packet + ERR_INVALID_DNS_ERROR = -35, ///< Invalid DNS return code + ERR_DNS_FORMERR = -36, ///< DNS Error: Form error + ERR_DNS_SERVFAIL = -37, ///< DNS Error: Server Failure + ERR_DNS_NXDOMAIN = -38, ///< DNS Error: No such domain + ERR_DNS_NOTIMP = -39, ///< DNS Error: Not implemented + + ERR_DNS_REFUSED = -40, ///< DNS Error: Operation refused + ERR_DNS_YXDOMAIN = -41, ///< TODO + ERR_DNS_YXRRSET = -42, ///< TODO + ERR_DNS_NXRRSET = -43, ///< TODO + ERR_DNS_NOTAUTH = -44, ///< DNS Error: Not authorized + ERR_DNS_NOTZONE = -45, ///< TODO + ERR_INVALID_RDATA = -46, ///< Invalid RDATA + ERR_INVALID_DNS_CLASS = -47, ///< Invalid DNS class + ERR_INVALID_DNS_TYPE = -48, ///< Invalid DNS type + ERR_NOT_SUPPORTED = -49, ///< Not supported + + ERR_NOT_PERMITTED = -50, ///< Operation not permitted + ERR_INVALID_ARGUMENT = -51, ///< Invalid argument + ERR_IS_EMPTY = -52, ///< Is empty + ERR_NO_CHANGE = -53, ///< The requested operation is invalid because it is redundant + + ERR_MAX = -54 ///< TODO + }; + + constexpr auto IF_UNSPEC = -1; ///< Protocol or platform constant for if unspec. + + /** + * @brief Enumerates supported proto options. + */ + enum proto { + PROTO_INET = 0, ///< IPv4 + PROTO_INET6 = 1, ///< IPv6 + PROTO_UNSPEC = -1 ///< Unspecified/all protocol(s) + }; + + /** + * @brief Enumerates supported server state options. + */ + enum ServerState { + SERVER_INVALID, ///< Invalid state (initial) + SERVER_REGISTERING, ///< Host RRs are being registered + SERVER_RUNNING, ///< All host RRs have been established + SERVER_COLLISION, ///< There is a collision with a host RR. All host RRs have been withdrawn, the user should set a new host name via avahi_server_set_host_name() + SERVER_FAILURE ///< Some fatal failure happened, the server is unable to proceed + }; + + /** + * @brief Enumerates supported client state options. + */ + enum ClientState { + CLIENT_S_REGISTERING = SERVER_REGISTERING, ///< Server state: REGISTERING + CLIENT_S_RUNNING = SERVER_RUNNING, ///< Server state: RUNNING + CLIENT_S_COLLISION = SERVER_COLLISION, ///< Server state: COLLISION + CLIENT_FAILURE = 100, ///< Some kind of error happened on the client side + CLIENT_CONNECTING = 101 ///< We're still connecting. This state is only entered when AVAHI_CLIENT_NO_FAIL has been passed to avahi_client_new() and the daemon is not yet available. + }; + + /** + * @brief Enumerates supported entry group state options. + */ + enum EntryGroupState { + ENTRY_GROUP_UNCOMMITED, ///< The group has not yet been committed, the user must still call avahi_entry_group_commit() + ENTRY_GROUP_REGISTERING, ///< The entries of the group are currently being registered + ENTRY_GROUP_ESTABLISHED, ///< The entries have successfully been established + ENTRY_GROUP_COLLISION, ///< A name collision for one of the entries in the group has been detected, the entries have been withdrawn + ENTRY_GROUP_FAILURE ///< Some kind of failure happened, the entries have been withdrawn + }; + + /** + * @brief Enumerates supported client flags options. + */ + enum ClientFlags { + CLIENT_IGNORE_USER_CONFIG = 1, ///< Don't read user configuration + CLIENT_NO_FAIL = 2 ///< Don't fail if the daemon is not available when avahi_client_new() is called, instead enter CLIENT_CONNECTING state and wait for the daemon to appear + }; + + /** + * @brief Flags for publishing functions. + */ + enum PublishFlags { + PUBLISH_UNIQUE = 1, ///< For raw records: The RRset is intended to be unique + PUBLISH_NO_PROBE = 2, ///< For raw records: Though the RRset is intended to be unique no probes shall be sent + PUBLISH_NO_ANNOUNCE = 4, ///< For raw records: Do not announce this RR to other hosts + PUBLISH_ALLOW_MULTIPLE = 8, ///< For raw records: Allow multiple local records of this type, even if they are intended to be unique + PUBLISH_NO_REVERSE = 16, ///< For address records: don't create a reverse (PTR) entry + PUBLISH_NO_COOKIE = 32, ///< For service records: do not implicitly add the local service cookie to TXT data + PUBLISH_UPDATE = 64, ///< Update existing records instead of adding new ones + PUBLISH_USE_WIDE_AREA = 128, ///< Register the record using wide area DNS (i.e. unicast DNS update) + PUBLISH_USE_MULTICAST = 256 ///< Register the record using multicast DNS + }; + + /** + * @brief Network interface index type used by Avahi. + */ + using IfIndex = int; + /** + * @brief Avahi protocol/address-family selector type. + */ + using Protocol = int; + + struct EntryGroup; + struct Poll; + struct SimplePoll; + struct Client; + + /** + * @brief Avahi client state-change callback signature. + */ + typedef void (*ClientCallback)(Client *, ClientState, void *userdata); + /** + * @brief Avahi entry-group state-change callback signature. + */ + typedef void (*EntryGroupCallback)(EntryGroup *g, EntryGroupState state, void *userdata); + + /** + * @brief Function pointer used to free Avahi-allocated memory. + */ + typedef void (*free_fn)(void *); + + /** + * @brief Function pointer used to create an Avahi client. + */ + typedef Client *(*client_new_fn)(const Poll *poll_api, ClientFlags flags, ClientCallback callback, void *userdata, int *error); + /** + * @brief Function pointer used to destroy an Avahi client. + */ + typedef void (*client_free_fn)(Client *); + /** + * @brief Function pointer used to request an alternative Avahi service name. + */ + typedef char *(*alternative_service_name_fn)(char *); + + /** + * @brief Function pointer used to get an Avahi client from an entry group. + */ + typedef Client *(*entry_group_get_client_fn)(EntryGroup *); + + /** + * @brief Function pointer used to create an Avahi entry group. + */ + typedef EntryGroup *(*entry_group_new_fn)(Client *, EntryGroupCallback, void *userdata); + /** + * @brief Function pointer used to add a service to an Avahi entry group. + */ + typedef int (*entry_group_add_service_fn)( + EntryGroup *group, + IfIndex interface, + Protocol protocol, + PublishFlags flags, + const char *name, + const char *type, + const char *domain, + const char *host, + uint16_t port, + ... + ); + + /** + * @brief Function pointer used to test whether an Avahi entry group is empty. + */ + typedef int (*entry_group_is_empty_fn)(EntryGroup *); + /** + * @brief Function pointer used to reset an Avahi entry group. + */ + typedef int (*entry_group_reset_fn)(EntryGroup *); + /** + * @brief Function pointer used to publish an Avahi entry group. + */ + typedef int (*entry_group_commit_fn)(EntryGroup *); + + /** + * @brief Function pointer used to duplicate Avahi strings. + */ + typedef char *(*strdup_fn)(const char *); + /** + * @brief Function pointer used to format Avahi error codes. + */ + typedef char *(*strerror_fn)(int); + /** + * @brief Function pointer used to read the last Avahi client error. + */ + typedef int (*client_errno_fn)(Client *); + + /** + * @brief Function pointer used to get the Avahi simple-poll API. + */ + typedef Poll *(*simple_poll_get_fn)(SimplePoll *); + /** + * @brief Function pointer used to run the Avahi simple-poll loop. + */ + typedef int (*simple_poll_loop_fn)(SimplePoll *); + /** + * @brief Function pointer used to stop the Avahi simple-poll loop. + */ + typedef void (*simple_poll_quit_fn)(SimplePoll *); + /** + * @brief Function pointer used to allocate an Avahi simple-poll instance. + */ + typedef SimplePoll *(*simple_poll_new_fn)(); + /** + * @brief Function pointer used to free an Avahi simple-poll instance. + */ + typedef void (*simple_poll_free_fn)(SimplePoll *); + + /** + * @brief Validated Avahi functions and the libraries that own their code and data. + */ + class api_t { + public: + /** + * @brief Load the common and client libraries without publishing partial state. + * + * @return Immutable API owner, or nullptr when a library or symbol is unavailable. + */ + static std::shared_ptr load() { + return load(dyn::system_loader()); + } + + /** + * @brief Load both Avahi libraries through injected loading operations. + * + * @param loader Loading operations used for this publisher initialization attempt. + * @return Immutable API owner, or nullptr when a library or symbol is unavailable. + */ + static std::shared_ptr load(const dyn::loader_t &loader) { + auto api = std::shared_ptr(new api_t()); + api->common_library = loader.open({"libavahi-common.so.3", "libavahi-common.so"}); + if (!api->common_library) { + return {}; + } + + const std::vector> common_functions { + {(dyn::apiproc *) &api->alternative_service_name, "avahi_alternative_service_name"}, + {(dyn::apiproc *) &api->free, "avahi_free"}, + {(dyn::apiproc *) &api->strdup, "avahi_strdup"}, + {(dyn::apiproc *) &api->strerror, "avahi_strerror"}, + {(dyn::apiproc *) &api->simple_poll_get, "avahi_simple_poll_get"}, + {(dyn::apiproc *) &api->simple_poll_loop, "avahi_simple_poll_loop"}, + {(dyn::apiproc *) &api->simple_poll_quit, "avahi_simple_poll_quit"}, + {(dyn::apiproc *) &api->simple_poll_new, "avahi_simple_poll_new"}, + {(dyn::apiproc *) &api->simple_poll_free, "avahi_simple_poll_free"}, + }; + if (loader.resolve(api->common_library.get(), common_functions)) { + return {}; + } + + api->client_library = loader.open({"libavahi-client.so.3", "libavahi-client.so"}); + if (!api->client_library) { + return {}; + } + + const std::vector> client_functions { + {(dyn::apiproc *) &api->client_new, "avahi_client_new"}, + {(dyn::apiproc *) &api->client_free, "avahi_client_free"}, + {(dyn::apiproc *) &api->entry_group_get_client, "avahi_entry_group_get_client"}, + {(dyn::apiproc *) &api->entry_group_new, "avahi_entry_group_new"}, + {(dyn::apiproc *) &api->entry_group_add_service, "avahi_entry_group_add_service"}, + {(dyn::apiproc *) &api->entry_group_is_empty, "avahi_entry_group_is_empty"}, + {(dyn::apiproc *) &api->entry_group_reset, "avahi_entry_group_reset"}, + {(dyn::apiproc *) &api->entry_group_commit, "avahi_entry_group_commit"}, + {(dyn::apiproc *) &api->client_errno, "avahi_client_errno"}, + }; + if (loader.resolve(api->client_library.get(), client_functions)) { + return {}; + } + return api; + } + + free_fn free {}; ///< Release an allocation from the common library. + client_new_fn client_new {}; ///< Create a client with an instance callback context. + client_free_fn client_free {}; ///< Release a client and its entry groups. + alternative_service_name_fn alternative_service_name {}; ///< Resolve a conflicting service name. + entry_group_get_client_fn entry_group_get_client {}; ///< Read the client owning an entry group. + entry_group_new_fn entry_group_new {}; ///< Create an entry group. + entry_group_add_service_fn entry_group_add_service {}; ///< Add a service to an entry group. + entry_group_is_empty_fn entry_group_is_empty {}; ///< Check whether a group has service entries. + entry_group_reset_fn entry_group_reset {}; ///< Clear the services from a group. + entry_group_commit_fn entry_group_commit {}; ///< Publish the services in a group. + strdup_fn strdup {}; ///< Allocate a copy of a service name. + strerror_fn strerror {}; ///< Format an Avahi error. + client_errno_fn client_errno {}; ///< Read the last client error. + simple_poll_get_fn simple_poll_get {}; ///< Read the event-loop API. + simple_poll_loop_fn simple_poll_loop {}; ///< Run the event loop. + simple_poll_quit_fn simple_poll_quit {}; ///< Request event-loop shutdown. + simple_poll_new_fn simple_poll_new {}; ///< Allocate an event loop. + simple_poll_free_fn simple_poll_free {}; ///< Release an event loop. + + private: + /** + * @brief Create an empty API that is validated before being returned to a caller. + */ + api_t() = default; + + std::shared_ptr common_library; ///< Keep common functions alive until clients are destroyed. + std::shared_ptr client_library; ///< Keep client functions alive for all publisher resources. + }; + +} // namespace avahi diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index a87e98798..8063b4565 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -21,7 +21,9 @@ extern "C" { // local includes #include "cuda.h" +#include "dynamic_library.h" #include "graphics.h" +#include "nvfbc_api.h" #include "src/logging.h" #include "src/utility.h" #include "src/video.h" @@ -428,7 +430,7 @@ namespace cuda { return -1; } - gbm.reset(gbm::create_device(file.el)); + gbm = gbm::make_device(gbm::api_t::load(), file.el); if (!gbm) { BOOST_LOG(error) << "Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() << ']'; return -1; @@ -694,58 +696,10 @@ namespace cuda { } namespace nvfbc { - static PNVFBCCREATEINSTANCE createInstance {}; - static NVFBC_API_FUNCTION_LIST func {.dwVersion = NVFBC_VERSION}; - static constexpr inline NVFBC_BOOL nv_bool(bool b) { return b ? NVFBC_TRUE : NVFBC_FALSE; } - static void *handle {nullptr}; - - /** - * @brief Load NvFBC and create the CUDA capture helper. - * - * @return 0 on success; nonzero or negative platform status on failure. - */ - int init() { - static bool funcs_loaded = false; - - if (funcs_loaded) { - return 0; - } - - if (!handle) { - handle = dyn::handle({"libnvidia-fbc.so.1", "libnvidia-fbc.so"}); - if (!handle) { - return -1; - } - } - - std::vector> funcs { - {(dyn::apiproc *) &createInstance, "NvFBCCreateInstance"}, - }; - - if (dyn::load(handle, funcs)) { - dlclose(handle); - handle = nullptr; - - return -1; - } - - auto status = cuda::nvfbc::createInstance(&cuda::nvfbc::func); - if (status) { - BOOST_LOG(error) << "Unable to create NvFBC instance"sv; - - dlclose(handle); - handle = nullptr; - return -1; - } - - funcs_loaded = true; - return 0; - } - /** * @brief NvFBC CUDA context selected for a capture session. */ @@ -754,26 +708,28 @@ namespace cuda { /** * @brief Create an NvFBC session context for a native capture handle. * + * @param api API that owns the context functions. * @param handle Native library or object handle used by the operation. */ - ctx_t(NVFBC_SESSION_HANDLE handle) { + ctx_t(std::shared_ptr api, NVFBC_SESSION_HANDLE handle): + api {std::move(api)}, + handle {handle} { NVFBC_BIND_CONTEXT_PARAMS params {NVFBC_BIND_CONTEXT_PARAMS_VER}; - if (func.nvFBCBindContext(handle, ¶ms)) { - BOOST_LOG(error) << "Couldn't bind NvFBC context to current thread: " << func.nvFBCGetLastErrorStr(handle); + if (this->api->functions.nvFBCBindContext(handle, ¶ms)) { + BOOST_LOG(error) << "Couldn't bind NvFBC context to current thread: " << this->api->functions.nvFBCGetLastErrorStr(handle); } - - this->handle = handle; } ~ctx_t() { NVFBC_RELEASE_CONTEXT_PARAMS params {NVFBC_RELEASE_CONTEXT_PARAMS_VER}; - if (func.nvFBCReleaseContext(handle, ¶ms)) { - BOOST_LOG(error) << "Couldn't release NvFBC context from current thread: " << func.nvFBCGetLastErrorStr(handle); + if (api->functions.nvFBCReleaseContext(handle, ¶ms)) { + BOOST_LOG(error) << "Couldn't release NvFBC context from current thread: " << api->functions.nvFBCGetLastErrorStr(handle); } } - NVFBC_SESSION_HANDLE handle; ///< NVIDIA FBC capture session handle. + const std::shared_ptr api; ///< Keep context functions alive until release completes. + const NVFBC_SESSION_HANDLE handle; ///< NVIDIA FBC capture session handle. }; /** @@ -795,6 +751,7 @@ namespace cuda { * @param other Source object whose state is copied or moved into this object. */ handle_t(handle_t &&other): + api {std::move(other.api)}, handle_flags {other.handle_flags}, handle {other.handle} { other.handle_flags.reset(); @@ -807,6 +764,7 @@ namespace cuda { * @return Reference or value produced by the operator. */ handle_t &operator=(handle_t &&other) { + std::swap(api, other.api); std::swap(handle_flags, other.handle_flags); std::swap(handle, other.handle); @@ -816,9 +774,13 @@ namespace cuda { /** * @brief Allocate the underlying object and wrap it in the owning handle. * + * @param api API retained until the session and its contexts are released. * @return Created backend object, or null when creation fails. */ - static std::optional make() { + static std::optional make(std::shared_ptr api) { + if (!api) { + return std::nullopt; + } NVFBC_CREATE_HANDLE_PARAMS params {.dwVersion = NVFBC_CREATE_HANDLE_PARAMS_VER}; // Set privateData to allow NvFBC on consumer NVIDIA GPUs. @@ -828,7 +790,8 @@ namespace cuda { params.privateDataSize = sizeof(MAGIC_PRIVATE_DATA); handle_t handle; - auto status = func.nvFBCCreateHandle(&handle.handle, ¶ms); + handle.api = std::move(api); + auto status = handle.api->functions.nvFBCCreateHandle(&handle.handle, ¶ms); if (status) { BOOST_LOG(error) << "Failed to create session: "sv << handle.last_error(); @@ -846,7 +809,7 @@ namespace cuda { * @return Human-readable NvFBC error string. */ const char *last_error() { - return func.nvFBCGetLastErrorStr(handle); + return api->functions.nvFBCGetLastErrorStr(handle); } /** @@ -857,7 +820,7 @@ namespace cuda { std::optional status() { NVFBC_GET_STATUS_PARAMS params {.dwVersion = NVFBC_GET_STATUS_PARAMS_VER}; - auto status = func.nvFBCGetStatus(handle, ¶ms); + auto status = api->functions.nvFBCGetStatus(handle, ¶ms); if (status) { BOOST_LOG(error) << "Failed to get NvFBC status: "sv << last_error(); @@ -874,7 +837,7 @@ namespace cuda { * @return Capture status reported to the streaming pipeline. */ int capture(NVFBC_CREATE_CAPTURE_SESSION_PARAMS &capture_params) { - if (func.nvFBCCreateCaptureSession(handle, &capture_params)) { + if (api->functions.nvFBCCreateCaptureSession(handle, &capture_params)) { BOOST_LOG(error) << "Failed to start capture session: "sv << last_error(); return -1; } @@ -886,7 +849,7 @@ namespace cuda { NVFBC_BUFFER_FORMAT_BGRA, }; - if (func.nvFBCToCudaSetUp(handle, &setup_params)) { + if (api->functions.nvFBCToCudaSetUp(handle, &setup_params)) { BOOST_LOG(error) << "Failed to setup cuda interop with nvFBC: "sv << last_error(); return -1; } @@ -905,7 +868,7 @@ namespace cuda { NVFBC_DESTROY_CAPTURE_SESSION_PARAMS params {NVFBC_DESTROY_CAPTURE_SESSION_PARAMS_VER}; - if (func.nvFBCDestroyCaptureSession(handle, ¶ms)) { + if (api->functions.nvFBCDestroyCaptureSession(handle, ¶ms)) { BOOST_LOG(error) << "Couldn't destroy capture session: "sv << last_error(); return -1; @@ -930,9 +893,9 @@ namespace cuda { NVFBC_DESTROY_HANDLE_PARAMS params {NVFBC_DESTROY_HANDLE_PARAMS_VER}; - ctx_t ctx {handle}; - if (func.nvFBCDestroyHandle(handle, ¶ms)) { - BOOST_LOG(error) << "Couldn't destroy session handle: "sv << func.nvFBCGetLastErrorStr(handle); + ctx_t ctx {api, handle}; + if (api->functions.nvFBCDestroyHandle(handle, ¶ms)) { + BOOST_LOG(error) << "Couldn't destroy session handle: "sv << api->functions.nvFBCGetLastErrorStr(handle); } handle_flags[SESSION_HANDLE] = false; @@ -944,9 +907,10 @@ namespace cuda { reset(); } + std::shared_ptr api; ///< Own the API for this session and any bound contexts. std::bitset handle_flags; ///< Handle flags. - NVFBC_SESSION_HANDLE handle; ///< NVIDIA FBC capture session handle. + NVFBC_SESSION_HANDLE handle {}; ///< NVIDIA FBC capture session handle. }; /** @@ -962,12 +926,12 @@ namespace cuda { * @return 0 on success; nonzero or negative platform status on failure. */ int init(const std::string_view &display_name, const ::video::config_t &config) { - auto handle = handle_t::make(); + auto handle = handle_t::make(api_t::load()); if (!handle) { return -1; } - ctx_t ctx {handle->handle}; + ctx_t ctx {handle->api, handle->handle}; auto status_params = handle->status(); if (!status_params) { @@ -1035,7 +999,7 @@ namespace cuda { // Force display_t::capture to initialize handle_t::capture cursor_visible = !*cursor; - ctx_t ctx {handle.handle}; + ctx_t ctx {handle.api, handle.handle}; auto fg = util::fail_guard([&]() { handle.reset(); }); @@ -1113,7 +1077,7 @@ namespace cuda { // Direct Capture may fail the first few times, even if it's possible for (int x = 0; x < 3; ++x) { - if (auto status = func.nvFBCToCudaGrabFrame(handle.handle, &grab)) { + if (auto status = handle.api->functions.nvFBCToCudaGrabFrame(handle.handle, &grab)) { if (status == NVFBC_ERR_MUST_RECREATE) { return platf::capture_e::reinit; } @@ -1174,7 +1138,7 @@ namespace cuda { (std::uint32_t) timeout.count(), }; - if (auto status = func.nvFBCToCudaGrabFrame(handle.handle, &grab)) { + if (auto status = handle.api->functions.nvFBCToCudaGrabFrame(handle.handle, &grab)) { if (status == NVFBC_ERR_MUST_RECREATE) { return platf::capture_e::reinit; } @@ -1278,13 +1242,13 @@ namespace platf { * @return NvFBC display names, or an empty list when enumeration fails. */ std::vector nvfbc_display_names() { - if (cuda::init() || cuda::nvfbc::init()) { + if (cuda::init()) { return {}; } std::vector display_names; - auto handle = cuda::nvfbc::handle_t::make(); + auto handle = cuda::nvfbc::handle_t::make(cuda::nvfbc::api_t::load()); if (!handle) { return {}; } diff --git a/src/platform/linux/dynamic_library.h b/src/platform/linux/dynamic_library.h new file mode 100644 index 000000000..e1b43e7be --- /dev/null +++ b/src/platform/linux/dynamic_library.h @@ -0,0 +1,58 @@ +/** + * @file src/platform/linux/dynamic_library.h + * @brief Owning handles for optional Linux capture libraries. + */ +#pragma once + +// standard includes +#include +#include +#include + +// local includes +#include "misc.h" + +namespace dyn { + /** + * @brief Symbol destinations used while constructing an immutable API table. + */ + using symbols_t = std::vector>; + + /** + * @brief Loading operations supplied to optional-library factories. + */ + struct loader_t { + std::function(const std::vector &)> open; ///< Open a library owner. + std::function resolve; ///< Resolve all required symbols into a local table. + }; + + /** + * @brief Open an optional library and retain it until its last owner is released. + * + * @param names Library names to try in order. + * @return Shared library owner, or nullptr when none of the names can be loaded. + */ + inline std::shared_ptr open(const std::vector &names) { + auto library = handle(names); + if (!library) { + return {}; + } + return {library, [](void *value) { + dlclose(value); + }}; + } + + /** + * @brief Return the platform loader used by production API owners. + * + * @return Operations that use the existing library-name fallback and strict symbol lookup. + */ + inline loader_t system_loader() { + return { + open, + [](void *library, const symbols_t &symbols) { + return load(library, symbols); + }, + }; + } +} // namespace dyn diff --git a/src/platform/linux/graphics.cpp b/src/platform/linux/graphics.cpp index 74a4c8b24..eff59b242 100644 --- a/src/platform/linux/graphics.cpp +++ b/src/platform/linux/graphics.cpp @@ -9,6 +9,7 @@ #include // local includes +#include "dynamic_library.h" #include "graphics.h" #include "src/file_handler.h" #include "src/logging.h" @@ -300,38 +301,46 @@ namespace gl { } // namespace gl namespace gbm { - device_destroy_fn device_destroy; ///< Device destroy. - create_device_fn create_device; ///< Create device. + api_t::api_t(std::shared_ptr library, device_destroy_fn destroy, create_device_fn create): + library {std::move(library)}, + device_destroy {destroy}, + create_device {create} { + } - /** - * @brief Load GBM symbols required for EGL device creation. - */ - int init() { - static void *handle {nullptr}; - static bool funcs_loaded = false; + std::shared_ptr api_t::load() { + return load(dyn::system_loader()); + } - if (funcs_loaded) { - return 0; + std::shared_ptr api_t::load(const dyn::loader_t &loader) { + auto library = loader.open({"libgbm.so.1", "libgbm.so"}); + if (!library) { + return {}; } - if (!handle) { - handle = dyn::handle({"libgbm.so.1", "libgbm.so"}); - if (!handle) { - return -1; - } - } - - std::vector> funcs { - {(GLADapiproc *) &device_destroy, "gbm_device_destroy"}, - {(GLADapiproc *) &create_device, "gbm_create_device"}, + device_destroy_fn destroy {}; + create_device_fn create {}; + const std::vector> funcs { + {(dyn::apiproc *) &destroy, "gbm_device_destroy"}, + {(dyn::apiproc *) &create, "gbm_create_device"}, }; - if (dyn::load(handle, funcs)) { - return -1; + if (loader.resolve(library.get(), funcs) || !destroy || !create) { + return {}; } + return std::make_shared(std::move(library), destroy, create); + } - funcs_loaded = true; - return 0; + void device_deleter_t::operator()(device *value) const { + api->device_destroy(value); + } + + gbm_t make_device(std::shared_ptr api, int fd) { + auto value = api ? api->create_device(fd) : nullptr; + return {value, device_deleter_t {std::move(api)}}; + } + + int init() { + return api_t::load() ? 0 : -1; } } // namespace gbm diff --git a/src/platform/linux/graphics.h b/src/platform/linux/graphics.h index fbcdc728a..744791240 100644 --- a/src/platform/linux/graphics.h +++ b/src/platform/linux/graphics.h @@ -14,6 +14,7 @@ #include // local includes +#include "dynamic_library.h" #include "misc.h" #include "src/logging.h" #include "src/platform/common.h" @@ -364,13 +365,66 @@ namespace gbm { */ typedef device *(*create_device_fn)(int fd); - extern device_destroy_fn device_destroy; - extern create_device_fn create_device; + /** + * @brief Immutable GBM functions with ownership of the library that implements them. + */ + struct api_t { + /** + * @brief Construct a validated API from a library and resolved functions. + * + * @param library Owner of the loaded library or an injected implementation. + * @param destroy Function used to release devices. + * @param create Function used to allocate devices. + */ + api_t(std::shared_ptr library, device_destroy_fn destroy, create_device_fn create); + + /** + * @brief Load all required GBM functions for a capture or encoding owner. + * + * @return Validated immutable API, or nullptr when loading fails. + */ + static std::shared_ptr load(); + + /** + * @brief Load a GBM table through injected library-loading operations. + * + * @param loader Loading operations for this initialization attempt. + * @return Validated immutable API, or nullptr when loading fails. + */ + static std::shared_ptr load(const dyn::loader_t &loader); + + const std::shared_ptr library; ///< Keep functions valid until all devices have been released. + const device_destroy_fn device_destroy; ///< Release a device created by this API. + const create_device_fn create_device; ///< Create a device from an open DRM file descriptor. + }; + + /** + * @brief Release a GBM device before dropping its loaded-library owner. + */ + struct device_deleter_t { + /** + * @brief Destroy a device through the API that allocated it. + * + * @param value Device to release. + */ + void operator()(device *value) const; + + std::shared_ptr api; ///< API owner retained for the lifetime of this device. + }; /** * @brief Owning GBM device pointer released with the GBM destroy callback. */ - using gbm_t = util::dyn_safe_ptr; + using gbm_t = std::unique_ptr; + + /** + * @brief Allocate a device and retain the supplied API until it is released. + * + * @param api Validated API used to create and destroy the device. + * @param fd DRM file descriptor that must outlive the returned device. + * @return Owning device, or nullptr when the API or device is unavailable. + */ + gbm_t make_device(std::shared_ptr api, int fd); /** * @brief Load GBM symbols required for EGL device creation. diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 988f5c964..9f00fd88d 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -1766,7 +1766,8 @@ namespace platf { * @return 0 on success; nonzero or negative platform status on failure. */ int init(const std::string &display_name, const ::video::config_t &config) { - if (!gbm::create_device) { + auto gbm_api = gbm::api_t::load(); + if (!gbm_api) { BOOST_LOG(warning) << "libgbm not initialized"sv; return -1; } @@ -1775,7 +1776,7 @@ namespace platf { return -1; } - gbm.reset(gbm::create_device(card.fd.el)); + gbm = gbm::make_device(std::move(gbm_api), card.fd.el); if (!gbm) { BOOST_LOG(error) << "Couldn't create GBM device: ["sv << util::hex(eglGetError()).to_string_view() << ']'; return -1; @@ -2289,7 +2290,7 @@ namespace platf { return {}; } - if (!gbm::create_device) { + if (!gbm::api_t::load()) { BOOST_LOG(warning) << "libgbm not initialized"sv; return {}; } diff --git a/src/platform/linux/nvfbc_api.h b/src/platform/linux/nvfbc_api.h new file mode 100644 index 000000000..adf09cab8 --- /dev/null +++ b/src/platform/linux/nvfbc_api.h @@ -0,0 +1,79 @@ +/** + * @file src/platform/linux/nvfbc_api.h + * @brief Immutable NvFBC API ownership for capture sessions. + */ +#pragma once + +// local includes +#include "dynamic_library.h" +#include "src/logging.h" +#ifndef DOXYGEN + #include "third-party/nvfbc/NvFBC.h" +#endif + +namespace cuda::nvfbc { + /** + * @brief Immutable NvFBC function table that keeps its implementing library loaded. + */ + class api_t { + public: + /** + * @brief Load and validate the API for a new capture or enumeration owner. + * + * @return Immutable API, or nullptr when the library or API is unavailable. + */ + static std::shared_ptr load() { + return load(dyn::system_loader()); + } + + /** + * @brief Load an NvFBC table through injected library-loading operations. + * + * @param loader Loading operations for this initialization attempt. + * @return Immutable API, or nullptr when loading or function-table creation fails. + */ + static std::shared_ptr load(const dyn::loader_t &loader) { + auto library = loader.open({"libnvidia-fbc.so.1", "libnvidia-fbc.so"}); + if (!library) { + return {}; + } + + PNVFBCCREATEINSTANCE create_instance {}; + const std::vector> symbols { + {(dyn::apiproc *) &create_instance, "NvFBCCreateInstance"}, + }; + if (loader.resolve(library.get(), symbols) || !create_instance) { + return {}; + } + + NVFBC_API_FUNCTION_LIST functions {.dwVersion = NVFBC_VERSION}; + if (create_instance(&functions)) { + BOOST_LOG(error) << "Unable to create NvFBC instance"; + return {}; + } + + if (!functions.nvFBCCreateHandle || !functions.nvFBCDestroyHandle || !functions.nvFBCGetStatus || !functions.nvFBCGetLastErrorStr || !functions.nvFBCBindContext || !functions.nvFBCReleaseContext || !functions.nvFBCCreateCaptureSession || !functions.nvFBCDestroyCaptureSession || !functions.nvFBCToCudaSetUp || !functions.nvFBCToCudaGrabFrame) { + BOOST_LOG(error) << "NvFBC function table is incomplete"; + return {}; + } + return std::shared_ptr(new api_t(std::move(library), functions)); + } + + const NVFBC_API_FUNCTION_LIST functions; ///< Validated functions used by NvFBC sessions. + + private: + /** + * @brief Publish a fully initialized function table with its library owner. + * + * @param library Library implementing the table. + * @param functions Functions returned by NvFBCCreateInstance. + */ + api_t(std::shared_ptr library, const NVFBC_API_FUNCTION_LIST &functions): + functions {functions}, + library {std::move(library)} { + } + + const std::shared_ptr library; ///< Keep the API loaded until all sessions are destroyed. + }; + +} // namespace cuda::nvfbc diff --git a/src/platform/linux/publish.cpp b/src/platform/linux/publish.cpp index 5a2f45825..2c914e91c 100644 --- a/src/platform/linux/publish.cpp +++ b/src/platform/linux/publish.cpp @@ -7,6 +7,7 @@ #include // local includes +#include "avahi_api.h" #include "misc.h" #include "src/logging.h" #include "src/network.h" @@ -17,254 +18,6 @@ using namespace std::literals; namespace avahi { - - /** - * @brief Error codes used by avahi. - */ - enum err_e { - OK = 0, ///< OK - ERR_FAILURE = -1, ///< Generic error code - ERR_BAD_STATE = -2, ///< Object was in a bad state - ERR_INVALID_HOST_NAME = -3, ///< Invalid host name - ERR_INVALID_DOMAIN_NAME = -4, ///< Invalid domain name - ERR_NO_NETWORK = -5, ///< No suitable network protocol available - ERR_INVALID_TTL = -6, ///< Invalid DNS TTL - ERR_IS_PATTERN = -7, ///< RR key is pattern - ERR_COLLISION = -8, ///< Name collision - ERR_INVALID_RECORD = -9, ///< Invalid RR - - ERR_INVALID_SERVICE_NAME = -10, ///< Invalid service name - ERR_INVALID_SERVICE_TYPE = -11, ///< Invalid service type - ERR_INVALID_PORT = -12, ///< Invalid port number - ERR_INVALID_KEY = -13, ///< Invalid key - ERR_INVALID_ADDRESS = -14, ///< Invalid address - ERR_TIMEOUT = -15, ///< Timeout reached - ERR_TOO_MANY_CLIENTS = -16, ///< Too many clients - ERR_TOO_MANY_OBJECTS = -17, ///< Too many objects - ERR_TOO_MANY_ENTRIES = -18, ///< Too many entries - ERR_OS = -19, ///< OS error - - ERR_ACCESS_DENIED = -20, ///< Access denied - ERR_INVALID_OPERATION = -21, ///< Invalid operation - ERR_DBUS_ERROR = -22, ///< An unexpected D-Bus error occurred - ERR_DISCONNECTED = -23, ///< Daemon connection failed - ERR_NO_MEMORY = -24, ///< Memory exhausted - ERR_INVALID_OBJECT = -25, ///< The object passed to this function was invalid - ERR_NO_DAEMON = -26, ///< Daemon not running - ERR_INVALID_INTERFACE = -27, ///< Invalid interface - ERR_INVALID_PROTOCOL = -28, ///< Invalid protocol - ERR_INVALID_FLAGS = -29, ///< Invalid flags - - ERR_NOT_FOUND = -30, ///< Not found - ERR_INVALID_CONFIG = -31, ///< Configuration error - ERR_VERSION_MISMATCH = -32, ///< Version mismatch - ERR_INVALID_SERVICE_SUBTYPE = -33, ///< Invalid service subtype - ERR_INVALID_PACKET = -34, ///< Invalid packet - ERR_INVALID_DNS_ERROR = -35, ///< Invalid DNS return code - ERR_DNS_FORMERR = -36, ///< DNS Error: Form error - ERR_DNS_SERVFAIL = -37, ///< DNS Error: Server Failure - ERR_DNS_NXDOMAIN = -38, ///< DNS Error: No such domain - ERR_DNS_NOTIMP = -39, ///< DNS Error: Not implemented - - ERR_DNS_REFUSED = -40, ///< DNS Error: Operation refused - ERR_DNS_YXDOMAIN = -41, ///< TODO - ERR_DNS_YXRRSET = -42, ///< TODO - ERR_DNS_NXRRSET = -43, ///< TODO - ERR_DNS_NOTAUTH = -44, ///< DNS Error: Not authorized - ERR_DNS_NOTZONE = -45, ///< TODO - ERR_INVALID_RDATA = -46, ///< Invalid RDATA - ERR_INVALID_DNS_CLASS = -47, ///< Invalid DNS class - ERR_INVALID_DNS_TYPE = -48, ///< Invalid DNS type - ERR_NOT_SUPPORTED = -49, ///< Not supported - - ERR_NOT_PERMITTED = -50, ///< Operation not permitted - ERR_INVALID_ARGUMENT = -51, ///< Invalid argument - ERR_IS_EMPTY = -52, ///< Is empty - ERR_NO_CHANGE = -53, ///< The requested operation is invalid because it is redundant - - ERR_MAX = -54 ///< TODO - }; - - constexpr auto IF_UNSPEC = -1; ///< Protocol or platform constant for if unspec. - - /** - * @brief Enumerates supported proto options. - */ - enum proto { - PROTO_INET = 0, ///< IPv4 - PROTO_INET6 = 1, ///< IPv6 - PROTO_UNSPEC = -1 ///< Unspecified/all protocol(s) - }; - - /** - * @brief Enumerates supported server state options. - */ - enum ServerState { - SERVER_INVALID, ///< Invalid state (initial) - SERVER_REGISTERING, ///< Host RRs are being registered - SERVER_RUNNING, ///< All host RRs have been established - SERVER_COLLISION, ///< There is a collision with a host RR. All host RRs have been withdrawn, the user should set a new host name via avahi_server_set_host_name() - SERVER_FAILURE ///< Some fatal failure happened, the server is unable to proceed - }; - - /** - * @brief Enumerates supported client state options. - */ - enum ClientState { - CLIENT_S_REGISTERING = SERVER_REGISTERING, ///< Server state: REGISTERING - CLIENT_S_RUNNING = SERVER_RUNNING, ///< Server state: RUNNING - CLIENT_S_COLLISION = SERVER_COLLISION, ///< Server state: COLLISION - CLIENT_FAILURE = 100, ///< Some kind of error happened on the client side - CLIENT_CONNECTING = 101 ///< We're still connecting. This state is only entered when AVAHI_CLIENT_NO_FAIL has been passed to avahi_client_new() and the daemon is not yet available. - }; - - /** - * @brief Enumerates supported entry group state options. - */ - enum EntryGroupState { - ENTRY_GROUP_UNCOMMITED, ///< The group has not yet been committed, the user must still call avahi_entry_group_commit() - ENTRY_GROUP_REGISTERING, ///< The entries of the group are currently being registered - ENTRY_GROUP_ESTABLISHED, ///< The entries have successfully been established - ENTRY_GROUP_COLLISION, ///< A name collision for one of the entries in the group has been detected, the entries have been withdrawn - ENTRY_GROUP_FAILURE ///< Some kind of failure happened, the entries have been withdrawn - }; - - /** - * @brief Enumerates supported client flags options. - */ - enum ClientFlags { - CLIENT_IGNORE_USER_CONFIG = 1, ///< Don't read user configuration - CLIENT_NO_FAIL = 2 ///< Don't fail if the daemon is not available when avahi_client_new() is called, instead enter CLIENT_CONNECTING state and wait for the daemon to appear - }; - - /** - * @brief Flags for publishing functions. - */ - enum PublishFlags { - PUBLISH_UNIQUE = 1, ///< For raw records: The RRset is intended to be unique - PUBLISH_NO_PROBE = 2, ///< For raw records: Though the RRset is intended to be unique no probes shall be sent - PUBLISH_NO_ANNOUNCE = 4, ///< For raw records: Do not announce this RR to other hosts - PUBLISH_ALLOW_MULTIPLE = 8, ///< For raw records: Allow multiple local records of this type, even if they are intended to be unique - PUBLISH_NO_REVERSE = 16, ///< For address records: don't create a reverse (PTR) entry - PUBLISH_NO_COOKIE = 32, ///< For service records: do not implicitly add the local service cookie to TXT data - PUBLISH_UPDATE = 64, ///< Update existing records instead of adding new ones - PUBLISH_USE_WIDE_AREA = 128, ///< Register the record using wide area DNS (i.e. unicast DNS update) - PUBLISH_USE_MULTICAST = 256 ///< Register the record using multicast DNS - }; - - /** - * @brief Network interface index type used by Avahi. - */ - using IfIndex = int; - /** - * @brief Avahi protocol/address-family selector type. - */ - using Protocol = int; - - struct EntryGroup; - struct Poll; - struct SimplePoll; - struct Client; - - /** - * @brief Avahi client state-change callback signature. - */ - typedef void (*ClientCallback)(Client *, ClientState, void *userdata); - /** - * @brief Avahi entry-group state-change callback signature. - */ - typedef void (*EntryGroupCallback)(EntryGroup *g, EntryGroupState state, void *userdata); - - /** - * @brief Function pointer used to free Avahi-allocated memory. - */ - typedef void (*free_fn)(void *); - - /** - * @brief Function pointer used to create an Avahi client. - */ - typedef Client *(*client_new_fn)(const Poll *poll_api, ClientFlags flags, ClientCallback callback, void *userdata, int *error); - /** - * @brief Function pointer used to destroy an Avahi client. - */ - typedef void (*client_free_fn)(Client *); - /** - * @brief Function pointer used to request an alternative Avahi service name. - */ - typedef char *(*alternative_service_name_fn)(char *); - - /** - * @brief Function pointer used to get an Avahi client from an entry group. - */ - typedef Client *(*entry_group_get_client_fn)(EntryGroup *); - - /** - * @brief Function pointer used to create an Avahi entry group. - */ - typedef EntryGroup *(*entry_group_new_fn)(Client *, EntryGroupCallback, void *userdata); - /** - * @brief Function pointer used to add a service to an Avahi entry group. - */ - typedef int (*entry_group_add_service_fn)( - EntryGroup *group, - IfIndex interface, - Protocol protocol, - PublishFlags flags, - const char *name, - const char *type, - const char *domain, - const char *host, - uint16_t port, - ... - ); - - /** - * @brief Function pointer used to test whether an Avahi entry group is empty. - */ - typedef int (*entry_group_is_empty_fn)(EntryGroup *); - /** - * @brief Function pointer used to reset an Avahi entry group. - */ - typedef int (*entry_group_reset_fn)(EntryGroup *); - /** - * @brief Function pointer used to publish an Avahi entry group. - */ - typedef int (*entry_group_commit_fn)(EntryGroup *); - - /** - * @brief Function pointer used to duplicate Avahi strings. - */ - typedef char *(*strdup_fn)(const char *); - /** - * @brief Function pointer used to format Avahi error codes. - */ - typedef char *(*strerror_fn)(int); - /** - * @brief Function pointer used to read the last Avahi client error. - */ - typedef int (*client_errno_fn)(Client *); - - /** - * @brief Function pointer used to get the Avahi simple-poll API. - */ - typedef Poll *(*simple_poll_get_fn)(SimplePoll *); - /** - * @brief Function pointer used to run the Avahi simple-poll loop. - */ - typedef int (*simple_poll_loop_fn)(SimplePoll *); - /** - * @brief Function pointer used to stop the Avahi simple-poll loop. - */ - typedef void (*simple_poll_quit_fn)(SimplePoll *); - /** - * @brief Function pointer used to allocate an Avahi simple-poll instance. - */ - typedef SimplePoll *(*simple_poll_new_fn)(); - /** - * @brief Function pointer used to free an Avahi simple-poll instance. - */ - typedef void (*simple_poll_free_fn)(SimplePoll *); - free_fn free; ///< Free. client_new_fn client_new; ///< Client new. client_free_fn client_free; ///< Client free. diff --git a/src/platform/linux/vaapi.cpp b/src/platform/linux/vaapi.cpp index 1badbb7a8..e2e0de21d 100644 --- a/src/platform/linux/vaapi.cpp +++ b/src/platform/linux/vaapi.cpp @@ -181,14 +181,15 @@ namespace va { int init(int in_width, int in_height, file_t &&render_device) { file = std::move(render_device); - if (!gbm::create_device) { + auto gbm_api = gbm::api_t::load(); + if (!gbm_api) { BOOST_LOG(warning) << "libgbm not initialized"sv; return -1; } this->data = (void *) vaapi_init_avcodec_hardware_input_buffer; - gbm.reset(gbm::create_device(file.el)); + gbm = gbm::make_device(std::move(gbm_api), file.el); if (!gbm) { std::array string; BOOST_LOG(error) << "Couldn't create GBM device: ["sv << strerror_r(errno, string.data(), string.size()) << ']'; diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index a14b3b66d..6ffbfa252 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -20,6 +20,7 @@ // local includes #include "cuda.h" +#include "dynamic_library.h" #include "graphics.h" #include "misc.h" #include "src/config.h" @@ -178,14 +179,6 @@ namespace platf { } // namespace x11 namespace xcb { - static xcb_extension_t *shm_id; - - _FN(shm_get_image_reply, xcb_shm_get_image_reply_t *, (xcb_connection_t * c, xcb_shm_get_image_cookie_t cookie, xcb_generic_error_t **e)); - - _FN(shm_get_image_unchecked, xcb_shm_get_image_cookie_t, (xcb_connection_t * c, xcb_drawable_t drawable, int16_t x, int16_t y, uint16_t width, uint16_t height, uint32_t plane_mask, uint8_t format, xcb_shm_seg_t shmseg, uint32_t offset)); - - _FN(shm_attach, xcb_void_cookie_t, (xcb_connection_t * c, xcb_shm_seg_t shmseg, uint32_t shmid, uint8_t read_only)); - _FN(get_extension_data, xcb_query_extension_reply_t *, (xcb_connection_t * c, xcb_extension_t *ext)); _FN(get_setup, xcb_setup_t *, (xcb_connection_t * c)); @@ -196,39 +189,39 @@ namespace platf { _FN(generate_id, std::uint32_t, (xcb_connection_t * c)); /** - * @brief Initialize shared-memory support for X11 capture. - * - * @return 0 when XCB shared-memory functions are loaded; nonzero otherwise. + * @brief XCB shared-memory symbols owned by the capture instance that uses them. */ - int init_shm() { - static void *handle {nullptr}; - static bool funcs_loaded = false; - - if (funcs_loaded) { - return 0; - } - - if (!handle) { - handle = dyn::handle({"libxcb-shm.so.0", "libxcb-shm.so"}); - if (!handle) { - return -1; + struct shm_api_t { + /** + * @brief Load and validate all symbols used by the shared-memory capture path. + * + * @return API owner, or nullptr when the library or a symbol is unavailable. + */ + static std::shared_ptr load() { + auto api = std::make_shared(); + api->library = dyn::open({"libxcb-shm.so.0", "libxcb-shm.so"}); + if (!api->library) { + return {}; } + + const std::vector> symbols { + {(dyn::apiproc *) &api->shm_id, "xcb_shm_id"}, + {(dyn::apiproc *) &api->shm_get_image_reply, "xcb_shm_get_image_reply"}, + {(dyn::apiproc *) &api->shm_get_image_unchecked, "xcb_shm_get_image_unchecked"}, + {(dyn::apiproc *) &api->shm_attach, "xcb_shm_attach"}, + }; + if (dyn::load(api->library.get(), symbols)) { + return {}; + } + return api; } - std::vector> funcs { - {(dyn::apiproc *) &shm_id, "xcb_shm_id"}, - {(dyn::apiproc *) &shm_get_image_reply, "xcb_shm_get_image_reply"}, - {(dyn::apiproc *) &shm_get_image_unchecked, "xcb_shm_get_image_unchecked"}, - {(dyn::apiproc *) &shm_attach, "xcb_shm_attach"}, - }; - - if (dyn::load(handle, funcs)) { - return -1; - } - - funcs_loaded = true; - return 0; - } + std::shared_ptr library; ///< Keep the extension descriptor and functions loaded. + xcb_extension_t *shm_id {}; ///< Extension descriptor whose cache is managed by XCB. + decltype(&xcb_shm_get_image_reply) shm_get_image_reply {}; ///< Read a shared-memory image reply. + decltype(&xcb_shm_get_image_unchecked) shm_get_image_unchecked {}; ///< Request an image through SHM. + decltype(&xcb_shm_attach) shm_attach {}; ///< Attach a shared-memory segment to the connection. + }; /** * @brief Initialize XFixes cursor tracking for an X11 display. @@ -689,6 +682,7 @@ namespace platf { * @brief X11 shared-memory image dimensions and identifiers. */ struct shm_attr_t: public x11_attr_t { + const std::shared_ptr shm_api; ///< API retained until SHM resources are released. x11::xdisplay_t shm_xdisplay; ///< X11 display held separately to prevent races with x11_attr_t::xdisplay. xcb_connect_t xcb; ///< XCB connection used by the shared-memory capture path. xcb_screen_t *display; ///< XCB screen containing the captured root window. @@ -713,9 +707,11 @@ namespace platf { * @brief Open an X11 shared-memory capture backend. * * @param mem_type Requested memory path for the capture backend. + * @param shm_api Validated API retained for the lifetime of shared-memory capture. */ - shm_attr_t(mem_type_e mem_type): + shm_attr_t(mem_type_e mem_type, std::shared_ptr shm_api): x11_attr_t(mem_type), + shm_api {std::move(shm_api)}, shm_xdisplay {x11::OpenDisplay(nullptr)} { refresh_task_id = task_pool.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id; } @@ -773,10 +769,10 @@ namespace platf { BOOST_LOG(warning) << "X dimensions changed in SHM mode, request reinit"sv; return capture_e::reinit; } else { - auto img_cookie = xcb::shm_get_image_unchecked(xcb.get(), display->root, offset_x, offset_y, width, height, ~0, XCB_IMAGE_FORMAT_Z_PIXMAP, seg, 0); + auto img_cookie = shm_api->shm_get_image_unchecked(xcb.get(), display->root, offset_x, offset_y, width, height, ~0, XCB_IMAGE_FORMAT_Z_PIXMAP, seg, 0); auto frame_timestamp = std::chrono::steady_clock::now(); - xcb_img_t img_reply {xcb::shm_get_image_reply(xcb.get(), img_cookie, nullptr)}; + xcb_img_t img_reply {shm_api->shm_get_image_reply(xcb.get(), img_cookie, nullptr)}; if (!img_reply) { BOOST_LOG(error) << "Could not get image reply"sv; return capture_e::reinit; @@ -841,7 +837,7 @@ namespace platf { return -1; } - if (!xcb::get_extension_data(xcb.get(), xcb::shm_id)->present) { + if (!xcb::get_extension_data(xcb.get(), shm_api->shm_id)->present) { BOOST_LOG(error) << "Missing SHM extension"sv; return -1; @@ -857,7 +853,7 @@ namespace platf { return -1; } - xcb::shm_attach(xcb.get(), seg, shm_id.id, false); + shm_api->shm_attach(xcb.get(), seg, shm_id.id, false); data.data = shmat(shm_id.id, nullptr, 0); if ((uintptr_t) data.data == -1) { @@ -893,14 +889,15 @@ namespace platf { return nullptr; } - if (xcb::init_shm() || xcb::init() || x11::init() || x11::rr::init() || x11::fix::init()) { + auto shm_api = xcb::shm_api_t::load(); + if (!shm_api || xcb::init() || x11::init() || x11::rr::init() || x11::fix::init()) { BOOST_LOG(error) << "Couldn't init x11 libraries"sv; return nullptr; } // Attempt to use shared memory X11 to avoid copying the frame - auto shm_disp = std::make_shared(hwdevice_type); + auto shm_disp = std::make_shared(hwdevice_type, std::move(shm_api)); auto status = shm_disp->init(display_name, config); if (status > 0) { @@ -976,7 +973,7 @@ namespace platf { */ int load_xcb() { // This will be called once only - static int xcb_status = xcb::init_shm() || xcb::init(); + static const int xcb_status = !xcb::shm_api_t::load() || xcb::init(); return xcb_status; } diff --git a/src/platform/windows/nvprefs/driver_settings.cpp b/src/platform/windows/nvprefs/driver_settings.cpp index 42410729a..46110e303 100644 --- a/src/platform/windows/nvprefs/driver_settings.cpp +++ b/src/platform/windows/nvprefs/driver_settings.cpp @@ -13,9 +13,15 @@ namespace { const auto sunshine_application_profile_name = L"SunshineStream"; const auto sunshine_application_path = L"sunshine.exe"; - void nvapi_error_message(NvAPI_Status status) { + /** + * @brief Format a driver error through the API that owns the failed session. + * + * @param api Driver API retained by the session owner. + * @param status Driver status to report. + */ + void nvapi_error_message(const nvprefs::api_t &api, NvAPI_Status status) { NvAPI_ShortString message = {}; - NvAPI_GetErrorMessage(status, message); + api.call_interface("NvAPI_GetErrorMessage", status, message); nvprefs::error_message(std::string("NvAPI error: ") + message); } @@ -29,9 +35,7 @@ namespace { namespace nvprefs { driver_settings_t::~driver_settings_t() { - if (session_handle) { - NvAPI_DRS_DestroySession(session_handle); - } + destroy(); } bool driver_settings_t::init() { @@ -41,15 +45,15 @@ namespace nvprefs { NvAPI_Status status; - status = NvAPI_Initialize(); - if (status != NVAPI_OK) { + api = api_t::load(); + if (!api) { info_message("NvAPI_Initialize() failed, ignore if you don't have NVIDIA video card"); return false; } - status = NvAPI_DRS_CreateSession(&session_handle); + status = api->call_interface("NvAPI_DRS_CreateSession", &session_handle); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_CreateSession() failed"); return false; } @@ -59,10 +63,10 @@ namespace nvprefs { void driver_settings_t::destroy() { if (session_handle) { - NvAPI_DRS_DestroySession(session_handle); + api->call_interface("NvAPI_DRS_DestroySession", session_handle); session_handle = nullptr; } - NvAPI_Unload(); + api.reset(); } bool driver_settings_t::load_settings() { @@ -70,9 +74,9 @@ namespace nvprefs { return false; } - NvAPI_Status status = NvAPI_DRS_LoadSettings(session_handle); + NvAPI_Status status = api->call_interface("NvAPI_DRS_LoadSettings", session_handle); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_LoadSettings() failed"); destroy(); return false; @@ -86,9 +90,9 @@ namespace nvprefs { return false; } - NvAPI_Status status = NvAPI_DRS_SaveSettings(session_handle); + NvAPI_Status status = api->call_interface("NvAPI_DRS_SaveSettings", session_handle); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_SaveSettings() failed"); return false; } @@ -106,16 +110,16 @@ namespace nvprefs { NvAPI_Status status; NvDRSProfileHandle profile_handle = nullptr; - status = NvAPI_DRS_GetBaseProfile(session_handle, &profile_handle); + status = api->call_interface("NvAPI_DRS_GetBaseProfile", session_handle, &profile_handle); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_GetBaseProfile() failed"); return false; } NVDRS_SETTING setting = {}; setting.version = NVDRS_SETTING_VER; - status = NvAPI_DRS_GetSetting(session_handle, profile_handle, OGL_CPL_PREFER_DXPRESENT_ID, &setting); + status = api->call_interface("NvAPI_DRS_GetSetting", session_handle, profile_handle, OGL_CPL_PREFER_DXPRESENT_ID, &setting); if (status == NVAPI_OK && setting.settingLocation == NVDRS_CURRENT_PROFILE_LOCATION && setting.u32CurrentValue == swapchain_data->our_value) { if (swapchain_data->undo_value) { @@ -126,18 +130,18 @@ namespace nvprefs { setting.settingLocation = NVDRS_CURRENT_PROFILE_LOCATION; setting.u32CurrentValue = *swapchain_data->undo_value; - status = NvAPI_DRS_SetSetting(session_handle, profile_handle, &setting); + status = api->call_interface("NvAPI_DRS_SetSetting", session_handle, profile_handle, &setting); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_SetSetting() OGL_CPL_PREFER_DXPRESENT failed"); return false; } } else { - status = NvAPI_DRS_DeleteProfileSetting(session_handle, profile_handle, OGL_CPL_PREFER_DXPRESENT_ID); + status = api->call_interface("NvAPI_DRS_DeleteProfileSetting", session_handle, profile_handle, OGL_CPL_PREFER_DXPRESENT_ID); if (status != NVAPI_OK && status != NVAPI_SETTING_NOT_FOUND) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_DeleteProfileSetting() OGL_CPL_PREFER_DXPRESENT failed"); return false; } @@ -169,16 +173,16 @@ namespace nvprefs { } NvDRSProfileHandle profile_handle = nullptr; - status = NvAPI_DRS_GetBaseProfile(session_handle, &profile_handle); + status = api->call_interface("NvAPI_DRS_GetBaseProfile", session_handle, &profile_handle); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_GetBaseProfile() failed"); return false; } NVDRS_SETTING setting = {}; setting.version = NVDRS_SETTING_VER; - status = NvAPI_DRS_GetSetting(session_handle, profile_handle, OGL_CPL_PREFER_DXPRESENT_ID, &setting); + status = api->call_interface("NvAPI_DRS_GetSetting", session_handle, profile_handle, OGL_CPL_PREFER_DXPRESENT_ID, &setting); // Remember current OpenGL/Vulkan DXGI swapchain setting and change it if needed if (status == NVAPI_SETTING_NOT_FOUND || (status == NVAPI_OK && setting.u32CurrentValue != OGL_CPL_PREFER_DXPRESENT_PREFER_ENABLED)) { @@ -196,16 +200,16 @@ namespace nvprefs { setting.settingLocation = NVDRS_CURRENT_PROFILE_LOCATION; setting.u32CurrentValue = OGL_CPL_PREFER_DXPRESENT_PREFER_ENABLED; - status = NvAPI_DRS_SetSetting(session_handle, profile_handle, &setting); + status = api->call_interface("NvAPI_DRS_SetSetting", session_handle, profile_handle, &setting); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_SetSetting() OGL_CPL_PREFER_DXPRESENT failed"); return false; } info_message("Changed OGL_CPL_PREFER_DXPRESENT to OGL_CPL_PREFER_DXPRESENT_PREFER_ENABLED for base profile"); } else if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_GetSetting() OGL_CPL_PREFER_DXPRESENT failed"); return false; } @@ -225,16 +229,16 @@ namespace nvprefs { fill_nvapi_string(profile_name, sunshine_application_profile_name); NvDRSProfileHandle profile_handle = nullptr; - status = NvAPI_DRS_FindProfileByName(session_handle, profile_name, &profile_handle); + status = api->call_interface("NvAPI_DRS_FindProfileByName", session_handle, profile_name, &profile_handle); if (status != NVAPI_OK) { // Create application profile if missing NVDRS_PROFILE profile = {}; profile.version = NVDRS_PROFILE_VER1; fill_nvapi_string(profile.profileName, sunshine_application_profile_name); - status = NvAPI_DRS_CreateProfile(session_handle, &profile, &profile_handle); + status = api->call_interface("NvAPI_DRS_CreateProfile", session_handle, &profile, &profile_handle); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_CreateProfile() failed"); return false; } @@ -246,7 +250,7 @@ namespace nvprefs { NVDRS_APPLICATION application = {}; application.version = NVDRS_APPLICATION_VER_V1; - status = NvAPI_DRS_GetApplicationInfo(session_handle, profile_handle, sunshine_path, &application); + status = api->call_interface("NvAPI_DRS_GetApplicationInfo", session_handle, profile_handle, sunshine_path, &application); if (status != NVAPI_OK) { // Add application to application profile if missing @@ -256,9 +260,9 @@ namespace nvprefs { fill_nvapi_string(application.userFriendlyName, sunshine_application_path); fill_nvapi_string(application.launcher, L""); - status = NvAPI_DRS_CreateApplication(session_handle, profile_handle, &application); + status = api->call_interface("NvAPI_DRS_CreateApplication", session_handle, profile_handle, &application); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_CreateApplication() failed"); return false; } @@ -267,16 +271,16 @@ namespace nvprefs { NVDRS_SETTING setting = {}; setting.version = NVDRS_SETTING_VER1; - status = NvAPI_DRS_GetSetting(session_handle, profile_handle, PREFERRED_PSTATE_ID, &setting); + status = api->call_interface("NvAPI_DRS_GetSetting", session_handle, profile_handle, PREFERRED_PSTATE_ID, &setting); if (!get_nvprefs_options().sunshine_high_power_mode) { if (status == NVAPI_OK && setting.settingLocation == NVDRS_CURRENT_PROFILE_LOCATION) { // User requested to not use high power mode for sunshine.exe, // remove the setting from application profile if it's been set previously - status = NvAPI_DRS_DeleteProfileSetting(session_handle, profile_handle, PREFERRED_PSTATE_ID); + status = api->call_interface("NvAPI_DRS_DeleteProfileSetting", session_handle, profile_handle, PREFERRED_PSTATE_ID); if (status != NVAPI_OK && status != NVAPI_SETTING_NOT_FOUND) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_DeleteProfileSetting() PREFERRED_PSTATE failed"); return false; } @@ -293,9 +297,9 @@ namespace nvprefs { setting.settingLocation = NVDRS_CURRENT_PROFILE_LOCATION; setting.u32CurrentValue = PREFERRED_PSTATE_PREFER_MAX; - status = NvAPI_DRS_SetSetting(session_handle, profile_handle, &setting); + status = api->call_interface("NvAPI_DRS_SetSetting", session_handle, profile_handle, &setting); if (status != NVAPI_OK) { - nvapi_error_message(status); + nvapi_error_message(*api, status); error_message("NvAPI_DRS_SetSetting() PREFERRED_PSTATE failed"); return false; } diff --git a/src/platform/windows/nvprefs/driver_settings.h b/src/platform/windows/nvprefs/driver_settings.h index 7e1f4b214..82b5373f1 100644 --- a/src/platform/windows/nvprefs/driver_settings.h +++ b/src/platform/windows/nvprefs/driver_settings.h @@ -5,35 +5,9 @@ #pragma once // local includes first so standard library headers are pulled in before nvapi's SAL macros +#include "nvapi_opensource_wrapper.h" #include "undo_data.h" -// nvapi headers -// disable clang-format header reordering -// as needs types from -// clang-format off - -// With GCC/MinGW, nvapi_lite_salend.h (included transitively via nvapi_lite_d3dext.h) -// undefines all SAL annotation macros (e.g. __success, __in, __out, __inout) after -// nvapi_lite_salstart.h had defined them. This leaves NVAPI_INTERFACE and other macros -// that use SAL annotations broken for the rest of nvapi.h. Defining __NVAPI_EMPTY_SAL -// makes nvapi_lite_salend.h a no-op, preserving the SAL macro definitions throughout. -// After nvapi.h, we include nvapi_lite_salend.h explicitly (without __NVAPI_EMPTY_SAL) -// to clean up the SAL macros and prevent them from polluting subsequent includes. -#if defined(__GNUC__) - #define __NVAPI_EMPTY_SAL -#endif - -#include -#include - -#if defined(__GNUC__) - #undef __NVAPI_EMPTY_SAL - // Clean up SAL macros that nvapi_lite_salstart.h defined and salend.h was - // prevented from cleaning up (due to __NVAPI_EMPTY_SAL above). - #include -#endif -// clang-format on - namespace nvprefs { /** @@ -41,6 +15,16 @@ namespace nvprefs { */ class driver_settings_t { public: + /** + * @brief Construct an empty driver-settings owner. + */ + driver_settings_t() = default; + driver_settings_t(const driver_settings_t &) = delete; + driver_settings_t &operator=(const driver_settings_t &) = delete; + + /** + * @brief Destroy the session before releasing the driver library. + */ ~driver_settings_t(); /** @@ -94,7 +78,8 @@ namespace nvprefs { bool check_and_modify_application_profile(bool &modified); private: - NvDRSSessionHandle session_handle = nullptr; + std::shared_ptr api; ///< API owner retained until the DRS session is destroyed. + NvDRSSessionHandle session_handle = nullptr; ///< Native driver-settings session owned by this instance. }; } // namespace nvprefs diff --git a/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp b/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp index 735a58056..acaa806bc 100644 --- a/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp +++ b/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp @@ -1,243 +1,57 @@ /** * @file src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp - * @brief Definitions for the NVAPI wrapper. + * @brief Definitions for the instance-owned NVAPI wrapper. */ -// standard includes -#include - // local includes -#include "driver_settings.h" +#include "nvapi_opensource_wrapper.h" + #include "nvprefs_common.h" // special nvapi header that should be the last include #include -namespace { - - std::map interfaces; - HMODULE dll = nullptr; - - template - NvAPI_Status call_interface(const char *name, Args... args) { - auto func = (Func *) interfaces[name]; - - if (!func) { - return interfaces.empty() ? NVAPI_API_NOT_INITIALIZED : NVAPI_NOT_SUPPORTED; - } - - return func(args...); - } - -} // namespace - -#undef NVAPI_INTERFACE -/** - * @def NVAPI_INTERFACE - * @brief Macro for NVAPI INTERFACE. - */ -#define NVAPI_INTERFACE NvAPI_Status __cdecl - -/** - * @brief NVAPI export used to resolve function pointers by interface ID. - * - * @param id NVAPI interface ID from the generated interface table. - * @return Function pointer for the requested NVAPI interface, or nullptr. - */ -extern void *__cdecl nvapi_QueryInterface(NvU32 id); - -NVAPI_INTERFACE - -/** - * @brief Load NVAPI and resolve the subset of interfaces used by Sunshine. - * - * @return NVAPI_OK on success, or NVAPI_LIBRARY_NOT_FOUND when the DLL cannot be loaded. - */ -NvAPI_Initialize() { - if (dll) { - return NVAPI_OK; +namespace nvprefs { + std::shared_ptr api_t::load() { + const loader_t loader { + [](const char *name) -> std::shared_ptr { + auto module = LoadLibraryEx(name, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!module) { + return {}; + } + return {module, [](void *value) { + FreeLibrary(static_cast(value)); + }}; + }, + [](void *module, const char *name) { + return reinterpret_cast(GetProcAddress(static_cast(module), name)); + }, + }; + return load(loader); } + std::shared_ptr api_t::load(const loader_t &loader) { #if defined(_M_ARM64) || defined(__aarch64__) - auto dll_name = "nvapia64.dll"; + const auto dll_name = "nvapia64.dll"; #elif defined(_WIN64) - auto dll_name = "nvapi64.dll"; + const auto dll_name = "nvapi64.dll"; #else - auto dll_name = "nvapi.dll"; + const auto dll_name = "nvapi.dll"; #endif - - if ((dll = LoadLibraryEx(dll_name, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32))) { - if (auto query_interface = (decltype(nvapi_QueryInterface) *) GetProcAddress(dll, "nvapi_QueryInterface")) { - for (const auto &item : nvapi_interface_table) { - interfaces[item.func] = query_interface(item.id); - } - return NVAPI_OK; + auto library = loader.open(dll_name); + if (!library) { + return {}; } + + using query_interface_fn = void *(__cdecl *) (NvU32); + auto query_interface = reinterpret_cast(loader.symbol(library.get(), "nvapi_QueryInterface")); + if (!query_interface) { + return {}; + } + + interfaces_t interfaces; + for (const auto &item : nvapi_interface_table) { + interfaces.emplace(item.func, query_interface(item.id)); + } + return std::make_shared(std::move(library), std::move(interfaces)); } - - NvAPI_Unload(); - return NVAPI_LIBRARY_NOT_FOUND; -} - -/** - * @brief Unload NVAPI and clear all resolved interface pointers. - * - * @return NVAPI_OK after cleanup. - */ -NVAPI_INTERFACE NvAPI_Unload() { - if (dll) { - interfaces.clear(); - FreeLibrary(dll); - dll = nullptr; - } - return NVAPI_OK; -} - -/** - * @brief Forward NvAPI_GetErrorMessage to the loaded NVAPI DLL. - * - * @param nr Controller index assigned by the client. - * @param szDesc Output buffer receiving the human-readable error string. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_GetErrorMessage(NvAPI_Status nr, NvAPI_ShortString szDesc) { - return call_interface("NvAPI_GetErrorMessage", nr, szDesc); -} - -// This is only a subset of NvAPI_DRS_* functions, more can be added if needed - -/** - * @brief Forward NvAPI_DRS_CreateSession to the loaded NVAPI DLL. - * - * @param phSession Output handle for the created DRS session. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_CreateSession(NvDRSSessionHandle *phSession) { - return call_interface("NvAPI_DRS_CreateSession", phSession); -} - -/** - * @brief Forward NvAPI_DRS_DestroySession to the loaded NVAPI DLL. - * - * @param hSession DRS session handle to destroy. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_DestroySession(NvDRSSessionHandle hSession) { - return call_interface("NvAPI_DRS_DestroySession", hSession); -} - -/** - * @brief Forward NvAPI_DRS_LoadSettings to the loaded NVAPI DLL. - * - * @param hSession DRS session whose settings are loaded. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_LoadSettings(NvDRSSessionHandle hSession) { - return call_interface("NvAPI_DRS_LoadSettings", hSession); -} - -/** - * @brief Forward NvAPI_DRS_SaveSettings to the loaded NVAPI DLL. - * - * @param hSession DRS session whose settings are saved. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_SaveSettings(NvDRSSessionHandle hSession) { - return call_interface("NvAPI_DRS_SaveSettings", hSession); -} - -/** - * @brief Forward NvAPI_DRS_CreateProfile to the loaded NVAPI DLL. - * - * @param hSession DRS session that owns the profile. - * @param pProfileInfo Profile definition to create. - * @param phProfile Output handle for the created profile. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_CreateProfile(NvDRSSessionHandle hSession, NVDRS_PROFILE *pProfileInfo, NvDRSProfileHandle *phProfile) { - return call_interface("NvAPI_DRS_CreateProfile", hSession, pProfileInfo, phProfile); -} - -/** - * @brief Forward NvAPI_DRS_FindProfileByName to the loaded NVAPI DLL. - * - * @param hSession DRS session to search. - * @param profileName Profile name. - * @param phProfile Output handle for the matched profile. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_FindProfileByName(NvDRSSessionHandle hSession, NvAPI_UnicodeString profileName, NvDRSProfileHandle *phProfile) { - return call_interface("NvAPI_DRS_FindProfileByName", hSession, profileName, phProfile); -} - -/** - * @brief Forward NvAPI_DRS_CreateApplication to the loaded NVAPI DLL. - * - * @param hSession DRS session that owns the profile. - * @param hProfile Profile receiving the application entry. - * @param pApplication Application entry to create. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_CreateApplication(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NVDRS_APPLICATION *pApplication) { - return call_interface("NvAPI_DRS_CreateApplication", hSession, hProfile, pApplication); -} - -/** - * @brief Forward NvAPI_DRS_GetApplicationInfo to the loaded NVAPI DLL. - * - * @param hSession DRS session that owns the profile. - * @param hProfile Profile containing the application entry. - * @param appName App name. - * @param pApplication Output application information. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_GetApplicationInfo(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvAPI_UnicodeString appName, NVDRS_APPLICATION *pApplication) { - return call_interface("NvAPI_DRS_GetApplicationInfo", hSession, hProfile, appName, pApplication); -} - -/** - * @brief Forward NvAPI_DRS_SetSetting to the loaded NVAPI DLL. - * - * @param hSession DRS session that owns the profile. - * @param hProfile Profile receiving the setting. - * @param pSetting Setting value to apply. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_SetSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NVDRS_SETTING *pSetting) { - return call_interface("NvAPI_DRS_SetSetting", hSession, hProfile, pSetting); -} - -/** - * @brief Forward NvAPI_DRS_GetSetting to the loaded NVAPI DLL. - * - * @param hSession DRS session that owns the profile. - * @param hProfile Profile containing the setting. - * @param settingId Setting ID. - * @param pSetting Output setting value. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_GetSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvU32 settingId, NVDRS_SETTING *pSetting) { - return call_interface("NvAPI_DRS_GetSetting", hSession, hProfile, settingId, pSetting); -} - -/** - * @brief Forward NvAPI_DRS_DeleteProfileSetting to the loaded NVAPI DLL. - * - * @param hSession DRS session that owns the profile. - * @param hProfile Profile containing the setting. - * @param settingId Setting ID. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_DeleteProfileSetting(NvDRSSessionHandle hSession, NvDRSProfileHandle hProfile, NvU32 settingId) { - return call_interface("NvAPI_DRS_DeleteProfileSetting", hSession, hProfile, settingId); -} - -/** - * @brief Forward NvAPI_DRS_GetBaseProfile to the loaded NVAPI DLL. - * - * @param hSession DRS session to query. - * @param phProfile Output handle for the base profile. - * @return NVAPI status returned by the loaded function. - */ -NVAPI_INTERFACE NvAPI_DRS_GetBaseProfile(NvDRSSessionHandle hSession, NvDRSProfileHandle *phProfile) { - return call_interface("NvAPI_DRS_GetBaseProfile", hSession, phProfile); -} +} // namespace nvprefs diff --git a/src/platform/windows/nvprefs/nvapi_opensource_wrapper.h b/src/platform/windows/nvprefs/nvapi_opensource_wrapper.h new file mode 100644 index 000000000..20a5147c3 --- /dev/null +++ b/src/platform/windows/nvprefs/nvapi_opensource_wrapper.h @@ -0,0 +1,94 @@ +/** + * @file src/platform/windows/nvprefs/nvapi_opensource_wrapper.h + * @brief Instance-owned NVIDIA driver API tables. + */ +#pragma once + +// standard includes +#include +#include +#include +#include +#include + +// nvapi headers +// clang-format off +#if defined(__GNUC__) + #define __NVAPI_EMPTY_SAL +#endif +#include +#include +#if defined(__GNUC__) + #undef __NVAPI_EMPTY_SAL + #include +#endif +// clang-format on + +namespace nvprefs { + /** + * @brief Resolved NVAPI interfaces and the loaded library that implements them. + */ + class api_t { + public: + /** + * @brief Library loading operations that can be supplied by a fake driver in tests. + */ + struct loader_t { + std::function(const char *)> open; ///< Load a library with its owning deleter. + std::function symbol; ///< Resolve the interface-query entry point. + }; + + /** + * @brief Function table keyed by interface names with string-value comparison. + */ + using interfaces_t = std::map>; + + /** + * @brief Construct an immutable table for a library or injected driver implementation. + * + * @param library Owner that keeps resolved interface pointers alive. + * @param interfaces Resolved functions, including null entries for unsupported interfaces. + */ + api_t(std::shared_ptr library, interfaces_t interfaces): + library {std::move(library)}, + interfaces {std::move(interfaces)} { + } + + /** + * @brief Load the system driver and resolve its NVAPI interface table. + * + * @return Immutable API, or nullptr when the driver library or resolver is unavailable. + */ + static std::shared_ptr load(); + + /** + * @brief Resolve an API using the supplied library-loading operations. + * + * @param loader Driver loader used by this initialization attempt. + * @return Immutable API, or nullptr when loading or resolver lookup fails. + */ + static std::shared_ptr load(const loader_t &loader); + + /** + * @brief Invoke a resolved interface without modifying the immutable table. + * + * @tparam Func NVAPI function type whose arguments are forwarded. + * @tparam Args Forwarded argument types. + * @param name NVAPI function name. + * @param args Arguments passed to the loaded driver. + * @return Driver status, or the appropriate unavailable-interface status. + */ + template + NvAPI_Status call_interface(std::string_view name, Args... args) const { + const auto found = interfaces.find(name); + if (found == interfaces.end() || !found->second) { + return interfaces.empty() ? NVAPI_API_NOT_INITIALIZED : NVAPI_NOT_SUPPORTED; + } + return reinterpret_cast(found->second)(args...); + } + + private: + const std::shared_ptr library; ///< Keep the driver loaded while sessions use its interfaces. + const interfaces_t interfaces; ///< Immutable function table resolved at initialization. + }; +} // namespace nvprefs diff --git a/tests/unit/test_linux_dynamic_apis.cpp b/tests/unit/test_linux_dynamic_apis.cpp new file mode 100644 index 000000000..fadfc5492 --- /dev/null +++ b/tests/unit/test_linux_dynamic_apis.cpp @@ -0,0 +1,319 @@ +/** + * @file tests/unit/test_linux_dynamic_apis.cpp + * @brief Tests for optional Linux API loading and resource ownership. + */ +#ifdef __linux__ + + // standard includes + #include + #include + + // lib includes + #include + + // local includes + #include "src/platform/linux/graphics.h" + #include "src/platform/linux/nvfbc_api.h" + +namespace { + /** + * @brief Fake device with an instance-specific cleanup observer. + */ + struct fake_gbm_device_t { + int fd; ///< Descriptor supplied to the allocation function. + std::function on_destroy; ///< Observer invoked when the device is released. + + /** + * @brief Notify the test that the API released its device. + */ + ~fake_gbm_device_t() { + if (on_destroy) { + on_destroy(); + } + } + }; + + /** + * @brief Allocate a fake device or simulate an invalid descriptor. + * + * @param fd Descriptor supplied by the device owner. + * @return Opaque fake device, or nullptr for a negative descriptor. + */ + gbm::device *create_fake_device(int fd) { + return fd < 0 ? nullptr : reinterpret_cast(new fake_gbm_device_t {fd, {}}); + } + + /** + * @brief Release a fake device through its loaded API. + * + * @param value Device created by create_fake_device. + */ + void destroy_fake_device(gbm::device *value) { + delete reinterpret_cast(value); + } + + /** + * @brief Resolve fake GBM functions into the unpublished table. + * + * @param library Fake loaded-library handle. + * @param symbols Destinations for the two required functions. + * @return Success after both destinations have been populated. + */ + int resolve_fake_gbm([[maybe_unused]] void *library, const dyn::symbols_t &symbols) { + for (const auto &[destination, name] : symbols) { + if (std::string_view(name) == "gbm_device_destroy") { + *destination = reinterpret_cast(&destroy_fake_device); + } else if (std::string_view(name) == "gbm_create_device") { + *destination = reinterpret_cast(&create_fake_device); + } else { + ADD_FAILURE() << "Unexpected GBM symbol: " << name; + return -1; + } + } + return 0; + } + + /** + * @brief Fake successful NvFBC session operation. + * + * @tparam Params Parameters for the selected session operation. + * @param handle Session being operated on. + * @param params Parameters supplied by the capture owner. + * @return Success without accessing a GPU. + */ + template + NVFBCSTATUS NVFBCAPI fake_session_operation([[maybe_unused]] NVFBC_SESSION_HANDLE handle, [[maybe_unused]] Params *params) { + return NVFBC_SUCCESS; + } + + /** + * @brief Fake NvFBC session allocation. + * + * @param handle Receives a deterministic session handle. + * @param params Parameters supplied by the capture owner. + * @return Success without accessing a GPU. + */ + NVFBCSTATUS NVFBCAPI fake_create_handle(NVFBC_SESSION_HANDLE *handle, [[maybe_unused]] NVFBC_CREATE_HANDLE_PARAMS *params) { + *handle = 1; + return NVFBC_SUCCESS; + } + + /** + * @brief Return a deterministic fake-driver error string. + * + * @param handle Session being queried. + * @return Fake error description. + */ + const char *NVFBCAPI fake_last_error([[maybe_unused]] NVFBC_SESSION_HANDLE handle) { + return "fake driver"; + } + + /** + * @brief Populate a complete or deliberately incomplete NvFBC API table. + * + * @tparam Missing Index of a required function to omit, or -1 for a complete table. + * @tparam Status Result returned by API creation. + * @param functions Function table whose version is set by the API loader. + * @return Configured creation status. + */ + template + NVFBCSTATUS NVFBCAPI fake_create_instance(NVFBC_API_FUNCTION_LIST *functions) { + EXPECT_EQ(functions->dwVersion, NVFBC_VERSION); + functions->nvFBCCreateHandle = Missing == 0 ? nullptr : &fake_create_handle; + functions->nvFBCDestroyHandle = Missing == 1 ? nullptr : &fake_session_operation; + functions->nvFBCGetStatus = Missing == 2 ? nullptr : &fake_session_operation; + functions->nvFBCGetLastErrorStr = Missing == 3 ? nullptr : &fake_last_error; + functions->nvFBCBindContext = Missing == 4 ? nullptr : &fake_session_operation; + functions->nvFBCReleaseContext = Missing == 5 ? nullptr : &fake_session_operation; + functions->nvFBCCreateCaptureSession = Missing == 6 ? nullptr : &fake_session_operation; + functions->nvFBCDestroyCaptureSession = Missing == 7 ? nullptr : &fake_session_operation; + functions->nvFBCToCudaSetUp = Missing == 8 ? nullptr : &fake_session_operation; + functions->nvFBCToCudaGrabFrame = Missing == 9 ? nullptr : &fake_session_operation; + return Status; + } + + /** + * @brief Parameterized failures for each function required by the NvFBC capture owner. + */ + class NvfbcIncompleteApiTest: public ::testing::TestWithParam {}; +} // namespace + +TEST(GbmApiTest, EmptyApiDoesNotAllocateADevice) { + EXPECT_FALSE(gbm::make_device({}, 7)); +} + +TEST(GbmApiTest, DeviceRetainsItsApiAndDestroysBeforeUnloading) { + bool destroyed = false; + bool unloaded = false; + auto library = std::shared_ptr(new int(1), [&](void *value) { + EXPECT_TRUE(destroyed); + unloaded = true; + delete static_cast(value); + }); + auto api = std::make_shared(library, &destroy_fake_device, &create_fake_device); + auto device = gbm::make_device(api, 42); + ASSERT_TRUE(device); + auto fake = reinterpret_cast(device.get()); + EXPECT_EQ(fake->fd, 42); + fake->on_destroy = [&]() { + EXPECT_FALSE(unloaded); + destroyed = true; + }; + library.reset(); + api.reset(); + EXPECT_FALSE(unloaded); + device = gbm::gbm_t {}; + EXPECT_TRUE(destroyed); + EXPECT_TRUE(unloaded); +} + +TEST(GbmApiTest, DeviceAllocationCanFailWithoutCallingItsDeleter) { + const auto api = std::make_shared(nullptr, &destroy_fake_device, &create_fake_device); + EXPECT_FALSE(gbm::make_device(api, -1)); +} + +TEST(GbmApiTest, LibraryFailureCanBeRetriedAndPartialSymbolsAreDiscarded) { + int attempts = 0; + int unloads = 0; + int resolutions = 0; + const dyn::loader_t loader { + [&](const std::vector &names) -> std::shared_ptr { + EXPECT_STREQ(names[0], "libgbm.so.1"); + EXPECT_STREQ(names[1], "libgbm.so"); + if (++attempts == 1) { + return {}; + } + return {new int(7), [&](void *value) { + ++unloads; + delete static_cast(value); + }}; + }, + [&](void *library, const dyn::symbols_t &symbols) { + EXPECT_EQ(*static_cast(library), 7); + if (++resolutions == 1) { + *std::get<0>(symbols.front()) = reinterpret_cast(&destroy_fake_device); + return -1; + } + return resolve_fake_gbm(library, symbols); + }, + }; + EXPECT_FALSE(gbm::api_t::load(loader)); + EXPECT_EQ(resolutions, 0); + EXPECT_FALSE(gbm::api_t::load(loader)); + EXPECT_EQ(unloads, 1); + auto api = gbm::api_t::load(loader); + ASSERT_TRUE(api); + EXPECT_EQ(attempts, 3); + EXPECT_EQ(unloads, 1); + api.reset(); + EXPECT_EQ(unloads, 2); +} + +TEST(GbmApiTest, RejectsIncompleteTablesEvenWhenResolverReportsSuccess) { + for (const std::string_view missing_name : {"gbm_device_destroy", "gbm_create_device"}) { + const dyn::loader_t loader { + [](const std::vector &) { + return std::make_shared(1); + }, + [&](void *library, const dyn::symbols_t &symbols) { + resolve_fake_gbm(library, symbols); + for (const auto &[destination, name] : symbols) { + if (missing_name == name) { + *destination = nullptr; + } + } + return 0; + }, + }; + EXPECT_FALSE(gbm::api_t::load(loader)); + } +} + +TEST(NvfbcApiTest, RejectsAnUnresolvedEntryPointEvenWhenResolverReportsSuccess) { + const dyn::loader_t loader { + [](const std::vector &) { + return std::make_shared(1); + }, + [](void *, const dyn::symbols_t &) { + return 0; + }, + }; + EXPECT_FALSE(cuda::nvfbc::api_t::load(loader)); +} + +TEST(NvfbcApiTest, LibraryAndSymbolFailuresCanBeRetried) { + int attempts = 0; + int resolutions = 0; + int unloads = 0; + const dyn::loader_t loader { + [&](const std::vector &names) -> std::shared_ptr { + EXPECT_STREQ(names[0], "libnvidia-fbc.so.1"); + EXPECT_STREQ(names[1], "libnvidia-fbc.so"); + if (++attempts == 1) { + return {}; + } + return {new int(1), [&](void *value) { + ++unloads; + delete static_cast(value); + }}; + }, + [&](void *, const dyn::symbols_t &symbols) { + if (++resolutions == 1) { + return -1; + } + EXPECT_STREQ(std::get<1>(symbols.front()), "NvFBCCreateInstance"); + *std::get<0>(symbols.front()) = reinterpret_cast(&fake_create_instance<>); + return 0; + }, + }; + EXPECT_FALSE(cuda::nvfbc::api_t::load(loader)); + EXPECT_EQ(resolutions, 0); + EXPECT_FALSE(cuda::nvfbc::api_t::load(loader)); + EXPECT_EQ(unloads, 1); + auto api = cuda::nvfbc::api_t::load(loader); + ASSERT_TRUE(api); + EXPECT_EQ(api->functions.nvFBCGetLastErrorStr(1), std::string_view("fake driver")); + EXPECT_EQ(unloads, 1); + api.reset(); + EXPECT_EQ(unloads, 2); +} + +TEST(NvfbcApiTest, ApiCreationFailureReleasesTheLibrary) { + bool unloaded = false; + const dyn::loader_t loader { + [&](const std::vector &) { + return std::shared_ptr(new int(1), [&](void *value) { + unloaded = true; + delete static_cast(value); + }); + }, + [](void *, const dyn::symbols_t &symbols) { + *std::get<0>(symbols.front()) = reinterpret_cast(&fake_create_instance<-1, NVFBC_ERR_API_VERSION>); + return 0; + }, + }; + EXPECT_FALSE(cuda::nvfbc::api_t::load(loader)); + EXPECT_TRUE(unloaded); +} + +TEST_P(NvfbcIncompleteApiTest, MissingRequiredFunctionReleasesTheLibrary) { + bool unloaded = false; + const dyn::loader_t loader { + [&](const std::vector &) { + return std::shared_ptr(new int(1), [&](void *value) { + unloaded = true; + delete static_cast(value); + }); + }, + [&](void *, const dyn::symbols_t &symbols) { + *std::get<0>(symbols.front()) = reinterpret_cast(GetParam()); + return 0; + }, + }; + EXPECT_FALSE(cuda::nvfbc::api_t::load(loader)); + EXPECT_TRUE(unloaded); +} + +INSTANTIATE_TEST_SUITE_P(RequiredFunctions, NvfbcIncompleteApiTest, ::testing::Values(&fake_create_instance<0>, &fake_create_instance<1>, &fake_create_instance<2>, &fake_create_instance<3>, &fake_create_instance<4>, &fake_create_instance<5>, &fake_create_instance<6>, &fake_create_instance<7>, &fake_create_instance<8>, &fake_create_instance<9>)); + +#endif diff --git a/tests/unit/test_nvapi_opensource_wrapper.cpp b/tests/unit/test_nvapi_opensource_wrapper.cpp new file mode 100644 index 000000000..4c991ed11 --- /dev/null +++ b/tests/unit/test_nvapi_opensource_wrapper.cpp @@ -0,0 +1,150 @@ +/** + * @file tests/unit/test_nvapi_opensource_wrapper.cpp + * @brief Tests for immutable NVAPI tables and loaded-driver lifetime. + */ +#ifdef _WIN32 + + // standard includes + #include + + // lib includes + #include + + // local includes + #include "src/platform/windows/nvprefs/nvapi_opensource_wrapper.h" + +namespace { + /** + * @brief Return a status and output value through an injected driver interface. + * + * @param value Value forwarded by the API wrapper. + * @param output Receives the incremented value. + * @return A deterministic driver status. + */ + NvAPI_Status __cdecl fake_interface(NvU32 value, NvU32 *output) { + *output = value + 1; + return NVAPI_INVALID_ARGUMENT; + } + + /** + * @brief Simulate a driver that exposes its resolver but supports none of the interfaces. + * + * @param id Requested interface identifier. + * @return nullptr for each unsupported driver interface. + */ + void *__cdecl unsupported_query_interface([[maybe_unused]] NvU32 id) { + return nullptr; + } +} // namespace + +TEST(NvapiApiTest, EmptyTableReportsNotInitialized) { + const nvprefs::api_t api {{}, {}}; + NvU32 output = 0; + EXPECT_EQ(api.call_interface("missing", 4u, &output), NVAPI_API_NOT_INITIALIZED); + EXPECT_EQ(output, 0u); +} + +TEST(NvapiApiTest, MissingAndNullInterfacesReportNotSupported) { + const nvprefs::api_t api {{}, {{"null", nullptr}}}; + NvU32 output = 0; + EXPECT_EQ(api.call_interface("missing", 4u, &output), NVAPI_NOT_SUPPORTED); + EXPECT_EQ(api.call_interface("null", 4u, &output), NVAPI_NOT_SUPPORTED); + EXPECT_EQ(output, 0u); +} + +TEST(NvapiApiTest, LooksUpNamesByValueAndForwardsArguments) { + const nvprefs::api_t api {{}, {{"fake_interface", reinterpret_cast(&fake_interface)}}}; + const std::string separately_allocated_name {"fake_interface"}; + NvU32 output = 0; + EXPECT_EQ(api.call_interface(separately_allocated_name, 41u, &output), NVAPI_INVALID_ARGUMENT); + EXPECT_EQ(output, 42u); +} + +TEST(NvapiApiTest, RetainsTheLibraryUntilItsLastApiOwnerIsReleased) { + bool unloaded = false; + auto library = std::shared_ptr(new int(1), [&](void *value) { + unloaded = true; + delete static_cast(value); + }); + auto api = std::make_shared(library, nvprefs::api_t::interfaces_t {{"fake", reinterpret_cast(&fake_interface)}}); + library.reset(); + EXPECT_FALSE(unloaded); + NvU32 output = 0; + EXPECT_EQ(api->call_interface("fake", 8u, &output), NVAPI_INVALID_ARGUMENT); + EXPECT_EQ(output, 9u); + api.reset(); + EXPECT_TRUE(unloaded); +} + +TEST(NvapiApiTest, MissingLibrarySkipsSymbolLookup) { + bool resolved = false; + const nvprefs::api_t::loader_t loader { + [](const char *) -> std::shared_ptr { + return {}; + }, + [&](void *, const char *) -> void * { + resolved = true; + return nullptr; + }, + }; + EXPECT_FALSE(nvprefs::api_t::load(loader)); + EXPECT_FALSE(resolved); +} + +TEST(NvapiApiTest, MissingResolverReleasesTheLibrary) { + bool unloaded = false; + const nvprefs::api_t::loader_t loader { + [&](const char *) { + return std::shared_ptr(new int(7), [&](void *value) { + unloaded = true; + delete static_cast(value); + }); + }, + [](void *module, const char *name) -> void * { + EXPECT_EQ(*static_cast(module), 7); + EXPECT_STREQ(name, "nvapi_QueryInterface"); + return nullptr; + }, + }; + EXPECT_FALSE(nvprefs::api_t::load(loader)); + EXPECT_TRUE(unloaded); +} + +TEST(NvapiApiTest, FailedLoadingCanBeRetriedWithoutPublishingPartialState) { + int attempts = 0; + int unloads = 0; + const nvprefs::api_t::loader_t loader { + [&](const char *name) -> std::shared_ptr { + #if defined(_M_ARM64) || defined(__aarch64__) + EXPECT_STREQ(name, "nvapia64.dll"); + #elif defined(_WIN64) + EXPECT_STREQ(name, "nvapi64.dll"); + #else + EXPECT_STREQ(name, "nvapi.dll"); + #endif + if (++attempts == 1) { + return {}; + } + return {new int(11), [&](void *value) { + ++unloads; + delete static_cast(value); + }}; + }, + [](void *module, const char *name) { + EXPECT_EQ(*static_cast(module), 11); + EXPECT_STREQ(name, "nvapi_QueryInterface"); + return reinterpret_cast(&unsupported_query_interface); + }, + }; + EXPECT_FALSE(nvprefs::api_t::load(loader)); + auto api = nvprefs::api_t::load(loader); + ASSERT_TRUE(api); + NvU32 output = 0; + EXPECT_EQ(api->call_interface("missing", 4u, &output), NVAPI_NOT_SUPPORTED); + EXPECT_EQ(attempts, 2); + EXPECT_EQ(unloads, 0); + api.reset(); + EXPECT_EQ(unloads, 1); +} + +#endif