diff --git a/src/crypto.cpp b/src/crypto.cpp index 6b7dfee7f..6472c8fa7 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -20,10 +20,7 @@ namespace crypto { using x509_name_t = util::safe_ptr; constexpr char UNPAIRED_CERTIFICATE_ERROR[] = "Client certificate identity is not paired"; ///< Error returned when no exact stored certificate matches. - cert_chain_t::cert_chain_t(): - _certs {}, - _cert_ctx {X509_STORE_CTX_new()} { - } + cert_chain_t::cert_chain_t() = default; void cert_chain_t::add(x509_t &&cert) { x509_store_t x509_store {X509_STORE_new()}; @@ -311,7 +308,7 @@ namespace crypto { } ecb_t::ecb_t(const aes_t &key_material, bool use_padding): - cipher_t {EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_new(), key_material, use_padding} { + cipher_t {cipher_ctx_t {EVP_CIPHER_CTX_new()}, cipher_ctx_t {EVP_CIPHER_CTX_new()}, key_material, use_padding} { } cbc_t::cbc_t(const aes_t &key_material, bool use_padding): diff --git a/src/crypto.h b/src/crypto.h index 624e4dfc5..7274d34be 100644 --- a/src/crypto.h +++ b/src/crypto.h @@ -174,7 +174,7 @@ namespace crypto { std::string rand_alphabet(std::size_t bytes, const std::string_view &alphabet = std::string_view {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!%&()=-"}); /** - * @brief Owns the certificate chain returned by Sunshine's TLS certificate loader. + * @brief Owns trusted certificates and a verification context initialized for each chain. */ class cert_chain_t { public: @@ -202,7 +202,7 @@ namespace crypto { private: std::vector> _certs; - x509_store_ctx_t _cert_ctx; + x509_store_ctx_t _cert_ctx {X509_STORE_CTX_new()}; ///< Verification context created for each certificate chain. }; namespace cipher { @@ -249,12 +249,12 @@ namespace crypto { ecb_t &operator=(ecb_t &&) noexcept = default; /** - * @brief Construct an AES-ECB cipher helper with key material. + * @brief Explicitly construct an AES-ECB cipher helper with key material. * * @param key_material AES key material used to initialize the cipher. * @param use_padding Whether the cipher should use block padding. */ - ecb_t(const aes_t &key_material, bool use_padding = true); + explicit ecb_t(const aes_t &key_material, bool use_padding = true); /** * @brief Encrypt plaintext into the supplied ciphertext buffer. @@ -292,12 +292,12 @@ namespace crypto { gcm_t &operator=(gcm_t &&) noexcept = default; /** - * @brief Construct an AES-GCM cipher helper with key material and IV state. + * @brief Explicitly construct an AES-GCM cipher helper with key material and IV state. * * @param key_material AES key material used to initialize the cipher. * @param use_padding Whether the cipher should use block padding. */ - gcm_t(const crypto::aes_t &key_material, bool use_padding = true); + explicit gcm_t(const crypto::aes_t &key_material, bool use_padding = true); /** * @brief Encrypts the plaintext using AES GCM mode. @@ -348,12 +348,12 @@ namespace crypto { cbc_t &operator=(cbc_t &&) noexcept = default; /** - * @brief Construct an AES-CBC cipher helper with key material and IV state. + * @brief Explicitly construct an AES-CBC cipher helper with key material and IV state. * * @param key_material AES key material used to initialize the cipher. * @param use_padding Whether the cipher should use block padding. */ - cbc_t(const crypto::aes_t &key_material, bool use_padding = true); + explicit cbc_t(const crypto::aes_t &key_material, bool use_padding = true); /** * @brief Encrypts the plaintext using AES CBC mode. diff --git a/src/entry_handler.cpp b/src/entry_handler.cpp index b8924b5e7..147809334 100644 --- a/src/entry_handler.cpp +++ b/src/entry_handler.cpp @@ -131,11 +131,11 @@ namespace service_ctrl { class service_controller { public: /** - * @brief Open the Windows service manager and Sunshine service handle. + * @brief Explicitly open the Windows service manager and Sunshine service handle. * * @param service_desired_access SERVICE_* desired access flags. */ - service_controller(DWORD service_desired_access) { + explicit service_controller(DWORD service_desired_access) { scm_handle = OpenSCManagerA(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm_handle) { auto winerr = GetLastError(); diff --git a/src/input.cpp b/src/input.cpp index bb4e32373..8f1b867a6 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -226,12 +226,10 @@ namespace input { * @brief Per-client gamepad slot and feedback state. */ struct gamepad_t { - gamepad_t(): - gamepad_state {}, - back_timeout_id {}, - id {-1}, - back_button_state {button_state_e::NONE} { - } + /** + * @brief Initialize an unassigned gamepad slot with no pending button timeout. + */ + gamepad_t() = default; ~gamepad_t() { if (id >= 0) { @@ -245,18 +243,18 @@ namespace input { } } - platf::gamepad_state_t gamepad_state; ///< Gamepad state. + platf::gamepad_state_t gamepad_state {}; ///< Gamepad state. - thread_pool_util::ThreadPool::task_id_t back_timeout_id; ///< Back timeout ID. + thread_pool_util::ThreadPool::task_id_t back_timeout_id {}; ///< Back timeout ID. - int id; ///< Global gamepad slot assigned to this client controller. + int id {-1}; ///< Global gamepad slot assigned to this client controller, or -1 when unassigned. // When emulating the HOME button, we may need to artificially release the back button. // Afterwards, the gamepad state on sunshine won't match the state on Moonlight. // To prevent Sunshine from sending erroneous input data to the active application, // Sunshine forces the button to be in a specific state until the gamepad state matches that of // Moonlight once more. - button_state_e back_button_state; ///< Back button state. + button_state_e back_button_state {button_state_e::NONE}; ///< Back button state. }; /** @@ -292,7 +290,7 @@ namespace input { }; /** - * @brief Construct input state from the mailbox and platform backend. + * @brief Construct input state with default controller slots and scroll accumulators. * * @param touch_port_event Event carrying the active touch port. * @param feedback_queue Queue used for controller feedback. @@ -301,26 +299,19 @@ namespace input { safe::mail_raw_t::event_t touch_port_event, platf::feedback_queue_t feedback_queue ): - shortcutFlags {}, - gamepads(MAX_GAMEPADS), - client_context {platf::allocate_client_input_context(platf_input)}, touch_port_event {std::move(touch_port_event)}, - feedback_queue {std::move(feedback_queue)}, - mouse_left_button_timeout {}, - touch_port {{0, 0, 0, 0, 0, 0}, 0, 0, 0.0f, 0.0f, 1.0f, 1.0f, 0, 0}, - accumulated_vscroll_delta {}, - accumulated_hscroll_delta {} { + feedback_queue {std::move(feedback_queue)} { } // Keep track of alt+ctrl+shift key combo - int shortcutFlags; ///< Shortcut flags. + int shortcutFlags {}; ///< Shortcut flags. modifier_state_t shift_keys; ///< Client Shift keys contributing to the aggregate Shift flag. modifier_state_t control_keys; ///< Client Control keys contributing to the aggregate Control flag. modifier_state_t alt_keys; ///< Client Alt keys contributing to the aggregate Alt flag. - std::vector gamepads; ///< Virtual gamepad slots tracked for the stream. - std::unique_ptr client_context; ///< Client context. + std::vector gamepads {MAX_GAMEPADS}; ///< Virtual gamepad slots tracked for the stream. + std::unique_ptr client_context {platf::allocate_client_input_context(platf_input)}; ///< Client context. safe::mail_raw_t::event_t touch_port_event; ///< Touch port event. platf::feedback_queue_t feedback_queue; ///< Queue used to deliver controller feedback to the platform backend. @@ -329,12 +320,12 @@ namespace input { std::mutex input_queue_lock; ///< Input queue lock. bool input_task_scheduled {}; ///< Whether one worker task owns packet dispatch for this stream; guarded by input_queue_lock. - thread_pool_util::ThreadPool::task_id_t mouse_left_button_timeout; ///< Mouse left button timeout. + thread_pool_util::ThreadPool::task_id_t mouse_left_button_timeout {}; ///< Mouse left button timeout. - input::touch_port_t touch_port; ///< Touch coordinate bounds for the current stream. + input::touch_port_t touch_port {{0, 0, 0, 0, 0, 0}, 0, 0, 0.0f, 0.0f, 1.0f, 1.0f, 0, 0}; ///< Touch coordinate bounds for the current stream. - int32_t accumulated_vscroll_delta; ///< Accumulated vscroll delta. - int32_t accumulated_hscroll_delta; ///< Accumulated hscroll delta. + int32_t accumulated_vscroll_delta {}; ///< Accumulated vscroll delta. + int32_t accumulated_hscroll_delta {}; ///< Accumulated hscroll delta. }; /** diff --git a/src/move_by_copy.h b/src/move_by_copy.h index a83897ff1..ffb6e1865 100644 --- a/src/move_by_copy.h +++ b/src/move_by_copy.h @@ -73,9 +73,11 @@ namespace move_by_copy_util { } /** - * @brief Move the wrapped object out of this helper. + * @brief Explicitly move the wrapped object out of this helper. + * + * @return Wrapped value whose ownership is transferred to the caller. */ - operator move_type() { + explicit operator move_type() { return std::move(_to_move); } }; diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 0f45b8456..6f6936fb6 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -73,8 +73,7 @@ namespace nvhttp { * @param private_key_file Path to the matching private key file. */ SunshineHTTPSServer(const std::string &certification_file, const std::string &private_key_file): - ServerBase::ServerBase(443), - context(boost::asio::ssl::context::tls_server) { + ServerBase::ServerBase(443) { // Disabling TLS 1.0 and 1.1 (see RFC 8996) context.set_options(boost::asio::ssl::context::no_tlsv1); context.set_options(boost::asio::ssl::context::no_tlsv1_1); @@ -86,7 +85,7 @@ namespace nvhttp { std::function, std::shared_ptr)> on_verify_failed; ///< Handler used to return the pairing challenge when client verification fails. protected: - boost::asio::ssl::context context; ///< TLS server context configured with Sunshine's certificate and protocol policy. + boost::asio::ssl::context context {boost::asio::ssl::context::tls_server}; ///< TLS server context configured with Sunshine's certificate and protocol policy. /** * @brief Enable client-certificate verification after the listening socket is bound. diff --git a/src/platform/common.h b/src/platform/common.h index bdad5ae12..3b1974085 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -1361,10 +1361,10 @@ namespace platf { virtual void sleep_for(const std::chrono::nanoseconds &duration) = 0; /** - * @brief Check if platform-specific timer backend has been initialized successfully + * @brief Explicitly check if platform-specific timer backend has been initialized successfully * @return `true` on success, `false` on error */ - virtual operator bool() = 0; + virtual explicit operator bool() = 0; }; /** diff --git a/src/platform/linux/cuda.cpp b/src/platform/linux/cuda.cpp index 3b5114a36..33de8132f 100644 --- a/src/platform/linux/cuda.cpp +++ b/src/platform/linux/cuda.cpp @@ -752,11 +752,11 @@ namespace cuda { class ctx_t { public: /** - * @brief Create an NvFBC session context for a native capture handle. + * @brief Explicitly create an NvFBC session context for a native capture handle. * * @param session_handle Native library or object handle used by the operation. */ - ctx_t(NVFBC_SESSION_HANDLE session_handle) { + explicit ctx_t(NVFBC_SESSION_HANDLE session_handle) { NVFBC_BIND_CONTEXT_PARAMS params {NVFBC_BIND_CONTEXT_PARAMS_VER}; if (func.nvFBCBindContext(session_handle, ¶ms)) { diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 7c89f31ab..695038840 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -237,9 +237,9 @@ namespace platf { fb {fb}, fb_id {fb->fb_id}, width {fb->width}, - height {fb->height} { - pixel_format = DRM_FORMAT_XRGB8888; - modifier = DRM_FORMAT_MOD_INVALID; + height {fb->height}, + pixel_format {DRM_FORMAT_XRGB8888}, + modifier {DRM_FORMAT_MOD_INVALID} { handles.fill(0); pitches.fill(0); offsets.fill(0); @@ -258,10 +258,9 @@ namespace platf { fb2 {fb2}, fb_id {fb2->fb_id}, width {fb2->width}, - height {fb2->height} { - pixel_format = fb2->pixel_format; - modifier = (fb2->flags & DRM_MODE_FB_MODIFIERS) ? fb2->modifier : DRM_FORMAT_MOD_INVALID; - + height {fb2->height}, + pixel_format {fb2->pixel_format}, + modifier {(fb2->flags & DRM_MODE_FB_MODIFIERS) ? fb2->modifier : DRM_FORMAT_MOD_INVALID} { std::copy_n(fb2->handles, handles.size(), handles.begin()); std::copy_n(fb2->pitches, pitches.size(), pitches.begin()); std::copy_n(fb2->offsets, offsets.size(), offsets.begin()); @@ -510,7 +509,7 @@ namespace platf { this->plane.reset(); for (; plane_p != end; ++plane_p) { - plane_t next_plane = drmModeGetPlane(fd, *plane_p); + plane_t next_plane {drmModeGetPlane(fd, *plane_p)}; if (!next_plane) { BOOST_LOG(error) << "Couldn't get drm plane ["sv << (end - plane_p) << "]: "sv << strerror(errno); continue; @@ -776,7 +775,7 @@ namespace platf { * @return Owning pointer to the DRM CRTC object. */ crtc_t crtc(std::uint32_t id) { - return drmModeGetCrtc(fd.el, id); + return crtc_t {drmModeGetCrtc(fd.el, id)}; } /** @@ -786,7 +785,7 @@ namespace platf { * @return Owning pointer to the DRM encoder object. */ encoder_t encoder(std::uint32_t id) { - return drmModeGetEncoder(fd.el, id); + return encoder_t {drmModeGetEncoder(fd.el, id)}; } /** @@ -795,7 +794,7 @@ namespace platf { * @return DRM card resource list. */ res_t res() { - return drmModeGetResources(fd.el); + return res_t {drmModeGetResources(fd.el)}; } /** @@ -885,7 +884,7 @@ namespace platf { * @return Owning pointer to the DRM connector object. */ connector_interal_t connector(std::uint32_t id) { - return drmModeGetConnector(fd.el, id); + return connector_interal_t {drmModeGetConnector(fd.el, id)}; } /** @@ -953,7 +952,7 @@ namespace platf { * @return DRM properties and their current values. */ std::vector> props(std::uint32_t id, std::uint32_t type) { - obj_prop_t obj_prop = drmModeObjectGetProperties(fd.el, id, type); + obj_prop_t obj_prop {drmModeObjectGetProperties(fd.el, id, type)}; if (!obj_prop) { return {}; } @@ -1005,7 +1004,7 @@ namespace platf { * @return Plane metadata for the requested DRM plane. */ plane_t operator[](std::uint32_t index) { - return drmModeGetPlane(fd.el, plane_res->planes[index]); + return plane_t {drmModeGetPlane(fd.el, plane_res->planes[index])}; } /** @@ -1138,11 +1137,11 @@ namespace platf { class display_t: public platf::display_t { public: /** - * @brief Initialize common KMS display state for the requested memory type. + * @brief Explicitly initialize common KMS display state for the requested memory type. * * @param mem_type Mem type. */ - display_t(mem_type_e mem_type): + explicit display_t(mem_type_e mem_type): platf::display_t(), mem_type {mem_type} { } @@ -1372,7 +1371,7 @@ namespace platf { return false; } - prop_blob_t hdr_metadata_blob = drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id); + prop_blob_t hdr_metadata_blob {drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id)}; if (hdr_metadata_blob == nullptr) { BOOST_LOG(error) << "Unable to get HDR metadata blob: "sv << strerror(errno); return false; @@ -1425,7 +1424,7 @@ namespace platf { return false; } - prop_blob_t hdr_metadata_blob = drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id); + prop_blob_t hdr_metadata_blob {drmModeGetPropertyBlob(card.fd.el, *hdr_metadata_blob_id)}; if (hdr_metadata_blob == nullptr) { BOOST_LOG(error) << "Unable to get HDR metadata blob: "sv << strerror(errno); return false; @@ -1456,7 +1455,7 @@ namespace platf { return; } - plane_t plane = drmModeGetPlane(card.fd.el, cursor_plane_id); + plane_t plane {drmModeGetPlane(card.fd.el, cursor_plane_id)}; std::optional prop_crtc_x; std::optional prop_crtc_y; @@ -1658,7 +1657,7 @@ namespace platf { } } - plane_t plane = drmModeGetPlane(card.fd.el, plane_id); + plane_t plane {drmModeGetPlane(card.fd.el, plane_id)}; frame_timestamp = std::chrono::steady_clock::now(); // A plane that stays without a framebuffer will not get the picture back by itself: @@ -1750,11 +1749,11 @@ namespace platf { class display_ram_t: public display_t { public: /** - * @brief Initialize a KMS display backend that copies frames through RAM. + * @brief Explicitly initialize a KMS display backend that copies frames through RAM. * * @param mem_type Mem type. */ - display_ram_t(mem_type_e mem_type): + explicit display_ram_t(mem_type_e mem_type): display_t(mem_type) { } @@ -2004,11 +2003,11 @@ namespace platf { class display_vram_t: public display_t { public: /** - * @brief Initialize a KMS display backend that exports frames as GPU resources. + * @brief Explicitly initialize a KMS display backend that exports frames as GPU resources. * * @param mem_type Mem type. */ - display_vram_t(mem_type_e mem_type): + explicit display_vram_t(mem_type_e mem_type): display_t(mem_type) { } diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 85f11cc7f..1de4e5d12 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -1534,7 +1534,7 @@ namespace platf { } /** - * @brief Linux high-precision timer implementation backed by `timerfd`. + * @brief Explicitly linux high-precision timer implementation backed by `timerfd`. */ class linux_high_precision_timer: public high_precision_timer { public: @@ -1542,7 +1542,7 @@ namespace platf { std::this_thread::sleep_for(duration); } - operator bool() override { + explicit operator bool() override { return true; } }; diff --git a/src/platform/linux/publish.cpp b/src/platform/linux/publish.cpp index ea00bd240..803752c09 100644 --- a/src/platform/linux/publish.cpp +++ b/src/platform/linux/publish.cpp @@ -532,11 +532,11 @@ namespace platf::publish { std::jthread poll_thread; ///< Poll thread. /** - * @brief Store the Avahi polling thread for shutdown on destruction. + * @brief Explicitly store the Avahi polling thread for shutdown on destruction. * * @param poll_thread Poll thread. */ - deinit_t(std::jthread poll_thread): + explicit deinit_t(std::jthread poll_thread): poll_thread {std::move(poll_thread)} { } diff --git a/src/platform/linux/wayland.cpp b/src/platform/linux/wayland.cpp index 686d32f57..f9362ce7e 100644 --- a/src/platform/linux/wayland.cpp +++ b/src/platform/linux/wayland.cpp @@ -359,8 +359,6 @@ namespace wl { } dmabuf_t::dmabuf_t(): - status {READY}, - frames {}, current_frame {&frames[0]}, listener { &CLASS_CALL(dmabuf_t, buffer), diff --git a/src/platform/linux/wayland.h b/src/platform/linux/wayland.h index 36f4b4552..aba5fc0e0 100644 --- a/src/platform/linux/wayland.h +++ b/src/platform/linux/wayland.h @@ -401,9 +401,9 @@ namespace wl { return current_frame == &frames[0] ? &frames[1] : &frames[0]; } - status_e status; ///< Current state of the active screencopy request. + status_e status {READY}; ///< Current state of the active screencopy request, initially ready. bool with_damage {false}; ///< Ask the compositor for the next frame that differs, rather than for a frame now. - std::array frames; ///< Double-buffered frame descriptors. + std::array frames {}; ///< Double-buffered frame descriptors. frame_t *current_frame; ///< Frame descriptor currently being filled by the compositor. zwlr_screencopy_frame_v1_listener listener; ///< Callback table registered on screencopy frames. diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index 7f7587a7f..9f8a75654 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -332,11 +332,11 @@ namespace platf { } /** - * @brief Take ownership of a SysV shared-memory segment ID. + * @brief Explicitly take ownership of a SysV shared-memory segment ID. * * @param id SysV shared-memory segment ID. */ - shm_id_t(int id): + explicit shm_id_t(int id): id {id} { } @@ -370,11 +370,11 @@ namespace platf { } /** - * @brief Take ownership of an attached shared-memory mapping. + * @brief Explicitly take ownership of an attached shared-memory mapping. * * @param data Pointer returned by shmat. */ - shm_data_t(std::uint8_t *data): + explicit shm_data_t(std::uint8_t *data): data {data} { } @@ -505,9 +505,9 @@ namespace platf { struct x11_attr_t: public display_t { std::chrono::nanoseconds delay; ///< Delay before the timer task becomes eligible to run. - x11::xdisplay_t xdisplay; ///< X11 display connection used for capture. - Window xwindow; ///< Root window being captured. - XWindowAttributes xattr; ///< Cached X11 window attributes used to detect size changes. + x11::xdisplay_t xdisplay {x11::OpenDisplay(nullptr)}; ///< X11 display connection opened for capture. + Window xwindow {}; ///< Root window being captured. + XWindowAttributes xattr {}; ///< Cached X11 window attributes used to detect size changes. mem_type_e mem_type; ///< Mem type. @@ -518,14 +518,11 @@ namespace platf { // int env_width, env_height; /** - * @brief Open the X11 display and initialize capture attributes. + * @brief Explicitly open the X11 display and initialize capture attributes. * * @param mem_type Requested memory path for the capture backend. */ - x11_attr_t(mem_type_e mem_type): - xdisplay {x11::OpenDisplay(nullptr)}, - xwindow {}, - xattr {}, + explicit x11_attr_t(mem_type_e mem_type): mem_type {mem_type} { x11::InitThreads(); } @@ -742,7 +739,7 @@ namespace platf { * @brief X11 shared-memory image dimensions and identifiers. */ struct shm_attr_t: public x11_attr_t { - x11::xdisplay_t shm_xdisplay; ///< X11 display held separately to prevent races with x11_attr_t::xdisplay. + x11::xdisplay_t shm_xdisplay {x11::OpenDisplay(nullptr)}; ///< 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. std::uint32_t seg; ///< XCB shared-memory segment ID attached to the image. @@ -763,13 +760,12 @@ namespace platf { } /** - * @brief Open an X11 shared-memory capture backend. + * @brief Explicitly open an X11 shared-memory capture backend. * * @param mem_type Requested memory path for the capture backend. */ - shm_attr_t(mem_type_e mem_type): - x11_attr_t(mem_type), - shm_xdisplay {x11::OpenDisplay(nullptr)} { + explicit shm_attr_t(mem_type_e mem_type): + x11_attr_t(mem_type) { refresh_task_id = task_pool.pushDelayed(&shm_attr_t::delayed_refresh, 2s, this).task_id; } @@ -1073,7 +1069,7 @@ namespace platf { void cursor_t::capture(egl::cursor_t &img) { auto display = (xdisplay_t::pointer) ctx.get(); - xcursor_t xcursor = fix::GetCursorImage(display); + xcursor_t xcursor {fix::GetCursorImage(display)}; if (img.serial != xcursor->cursor_serial) { auto buf_size = xcursor->width * xcursor->height * sizeof(int); @@ -1105,7 +1101,7 @@ namespace platf { * @brief Open and initialize the display connection used for capture. */ xdisplay_t make_display() { - return OpenDisplay(nullptr); + return xdisplay_t {OpenDisplay(nullptr)}; } /** diff --git a/src/platform/macos/misc.mm b/src/platform/macos/misc.mm index 703ace5e2..21012d503 100644 --- a/src/platform/macos/misc.mm +++ b/src/platform/macos/misc.mm @@ -887,7 +887,12 @@ namespace platf { std::this_thread::sleep_for(duration); } - operator bool() override { + /** + * @brief Explicitly report that the thread-based timer is always available. + * + * @return True because sleeping needs no additional timer resource. + */ + explicit operator bool() override { return true; } }; diff --git a/src/platform/macos/publish.cpp b/src/platform/macos/publish.cpp index 1ce5429b5..206ee28af 100644 --- a/src/platform/macos/publish.cpp +++ b/src/platform/macos/publish.cpp @@ -33,14 +33,15 @@ namespace platf::publish { */ class deinit_t: public ::platf::deinit_t, std::unique_ptr { public: - /** @brief Construct deinit_t object. + /** + * @brief Explicitly construct deinit_t object. * * Create a thread that will use `select(2)` to wait for a response from the mDNS service. * The thread will give up if an error is received or if `_stopRequested` becomes true. * * @param serviceRef An initialized reference to the mDNS service. */ - deinit_t(DNSServiceRef serviceRef): + explicit deinit_t(DNSServiceRef serviceRef): unique_ptr(serviceRef) { _thread = std::jthread {[serviceRef, &_stopRequested = std::as_const(_stopRequested)]() { platf::set_thread_name("publish::mdns"); diff --git a/src/platform/virtualhid_input.cpp b/src/platform/virtualhid_input.cpp index 30ab2c4f9..7e255df52 100644 --- a/src/platform/virtualhid_input.cpp +++ b/src/platform/virtualhid_input.cpp @@ -1125,8 +1125,13 @@ namespace platf { } // namespace + /** + * @brief Create the libvirtualhid backend with explicit input-handle ownership. + * + * @return Owning handle for the global virtual input backend. + */ input_t input() { - return {new input_raw_t {}}; + return input_t {new input_raw_t {}}; } std::unique_ptr allocate_client_input_context(input_t &input) { diff --git a/src/platform/windows/display.h b/src/platform/windows/display.h index 26f9f2ecb..ba6b9bfbb 100644 --- a/src/platform/windows/display.h +++ b/src/platform/windows/display.h @@ -229,8 +229,10 @@ namespace platf::dxgi { */ class gpu_cursor_t { public: - gpu_cursor_t(): - cursor_view {0, 0, 0, 0, 0.0f, 1.0f} {}; + /** + * @brief Initialize a cursor viewport with no area and the full depth range. + */ + gpu_cursor_t() = default; /** * @brief Update the cursor position and display geometry used for rendering. @@ -315,7 +317,7 @@ namespace platf::dxgi { shader_res_t input_res; ///< Input res. - D3D11_VIEWPORT cursor_view; ///< Cursor view. + D3D11_VIEWPORT cursor_view {0, 0, 0, 0, 0.0f, 1.0f}; ///< Cursor view with the full depth range. bool visible; ///< Whether the cursor is visible. }; diff --git a/src/platform/windows/display_vram.cpp b/src/platform/windows/display_vram.cpp index d4ca30021..3dbb7d442 100644 --- a/src/platform/windows/display_vram.cpp +++ b/src/platform/windows/display_vram.cpp @@ -209,9 +209,9 @@ namespace platf::dxgi { * * @param other Helper whose acquired keyed mutex is transferred. */ - texture_lock_helper(texture_lock_helper &&other) { + texture_lock_helper(texture_lock_helper &&other): + _locked {other._locked} { _mutex.reset(other._mutex.release()); - _locked = other._locked; other._locked = false; } @@ -232,11 +232,11 @@ namespace platf::dxgi { } /** - * @brief Acquire a D3D keyed mutex for scoped texture access. + * @brief Explicitly acquire a D3D keyed mutex for scoped texture access. * * @param mutex Keyed mutex to acquire for texture access. */ - texture_lock_helper(IDXGIKeyedMutex *mutex): + explicit texture_lock_helper(IDXGIKeyedMutex *mutex): _mutex(mutex) { if (_mutex) { _mutex->AddRef(); @@ -1550,7 +1550,7 @@ namespace platf::dxgi { // Finish creating the image (if it hasn't happened already), // also creates synchronization primitives for shared access from multiple direct3d devices. if (complete_img(d3d_img.get(), dummy)) { - return {nullptr, nullptr}; + return {nullptr, texture_lock_helper {nullptr}}; } // This image is shared between capture direct3d device and encoders direct3d devices, @@ -1558,7 +1558,7 @@ namespace platf::dxgi { texture_lock_helper lock_helper(d3d_img->capture_mutex.get()); if (!lock_helper.lock()) { BOOST_LOG(error) << "Failed to lock capture texture"; - return {nullptr, nullptr}; + return {nullptr, texture_lock_helper {nullptr}}; } // Clear the blank flag now that we're ready to capture into the image diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index b31b13bd5..9fdc466b1 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -1633,11 +1633,11 @@ namespace platf { class qos_t: public deinit_t { public: /** - * @brief Store a Windows QoS flow ID for cleanup on destruction. + * @brief Explicitly store a Windows QoS flow ID for cleanup on destruction. * * @param flow_id Flow ID. */ - qos_t(QOS_FLOWID flow_id): + explicit qos_t(QOS_FLOWID flow_id): flow_id(flow_id) { } @@ -1843,7 +1843,12 @@ namespace platf { WaitForSingleObject(timer, INFINITE); } - operator bool() override { + /** + * @brief Explicitly check whether the timer backend is initialized. + * + * @return True when the platform timer is available. + */ + explicit operator bool() override { return timer != nullptr; } diff --git a/src/platform/windows/publish.cpp b/src/platform/windows/publish.cpp index 2cc164be7..7509893fe 100644 --- a/src/platform/windows/publish.cpp +++ b/src/platform/windows/publish.cpp @@ -220,8 +220,10 @@ namespace platf::publish { */ class mdns_registration_t: public ::platf::deinit_t { public: - mdns_registration_t(): - existing_instance(nullptr) { + /** + * @brief Register Sunshine's DNS-SD service with no existing registration. + */ + mdns_registration_t() { if (service(true, existing_instance)) { BOOST_LOG(error) << "Unable to register Sunshine mDNS service"sv; return; @@ -242,7 +244,7 @@ namespace platf::publish { } private: - PDNS_SERVICE_INSTANCE existing_instance; + PDNS_SERVICE_INSTANCE existing_instance {nullptr}; ///< DNS-SD registration owned by this publisher. }; /** diff --git a/src/sync.h b/src/sync.h index 23ed8666b..7774a69b7 100644 --- a/src/sync.h +++ b/src/sync.h @@ -36,12 +36,12 @@ namespace sync_util { } /** - * @brief Initialize the protected object from forwarded arguments. + * @brief Explicitly initialize the protected object from forwarded arguments. * * @param args Arguments forwarded to the protected object's constructor. */ template - sync_t(Args &&...args): + explicit sync_t(Args &&...args): raw {std::forward(args)...} { } diff --git a/src/task_pool.h b/src/task_pool.h index 745bc66dd..200d73eb1 100644 --- a/src/task_pool.h +++ b/src/task_pool.h @@ -45,11 +45,11 @@ namespace task_pool_util { public: /** - * @brief Store a concrete callable behind the task type-erasure interface. + * @brief Explicitly store a concrete callable behind the task type-erasure interface. * * @param f Callable executed by the helper. */ - _Impl(Function &&f): + explicit _Impl(Function &&f): _func(std::forward(f)) { } diff --git a/src/thread_safe.h b/src/thread_safe.h index f3061e2b6..fa432ee7e 100644 --- a/src/thread_safe.h +++ b/src/thread_safe.h @@ -645,9 +645,9 @@ namespace safe { } /** - * @brief Check whether this shared pointer wrapper owns a live object. + * @brief Explicitly check whether this shared pointer wrapper owns a live object. */ - operator bool() const { + explicit operator bool() const { return owner != nullptr; } @@ -766,13 +766,13 @@ namespace safe { class post_t: public T { public: /** - * @brief Construct a message-posting wrapper around an existing type. + * @brief Explicitly construct a message-posting wrapper around an existing type. * * @param mail Mailbox used to exchange messages with worker threads. * @param args Arguments forwarded to the wrapped type constructor. */ template - post_t(mail_t mail, Args &&...args): + explicit post_t(mail_t mail, Args &&...args): T(std::forward(args)...), mail {std::move(mail)} { } diff --git a/src/utility.h b/src/utility.h index 0cf50485c..c688b8a5e 100644 --- a/src/utility.h +++ b/src/utility.h @@ -330,11 +330,11 @@ namespace util { FailGuard() = delete; /** - * @brief Construct a fail guard that owns the cleanup callback. + * @brief Explicitly construct a fail guard that owns the cleanup callback. * * @param f Callable executed by the helper. */ - FailGuard(T &&f) noexcept: + explicit FailGuard(T &&f) noexcept: _func {std::forward(f)} { } @@ -344,9 +344,8 @@ namespace util { * @param other Source object whose state is copied or moved into this object. */ FailGuard(FailGuard &&other) noexcept: + failure {other.failure}, _func {std::move(other._func)} { - this->failure = other.failure; - other.failure = false; } @@ -896,14 +895,18 @@ namespace util { */ using deleter_type = D; - constexpr uniq_ptr() noexcept: - _p {nullptr} { - } + /** + * @brief Initialize an empty unique ownership wrapper. + */ + constexpr uniq_ptr() noexcept = default; /** - * @brief Construct a unique ownership wrapper. + * @brief Construct an empty wrapper implicitly from nullptr, matching std::unique_ptr. */ - constexpr uniq_ptr(std::nullptr_t) noexcept: +#ifndef DOXYGEN + explicit(false) +#endif + constexpr uniq_ptr(std::nullptr_t) noexcept: _p {nullptr} { } @@ -911,34 +914,40 @@ namespace util { uniq_ptr &operator=(const uniq_ptr &other) noexcept = delete; /** - * @brief Construct a unique ownership wrapper. + * @brief Explicitly construct a unique ownership wrapper. * * @param p Pointer passed to the deleter or conversion helper. */ template - uniq_ptr(V *p) noexcept: + explicit uniq_ptr(V *p) noexcept: _p {p} { static_assert(std::is_same_v || std::is_same_v || std::is_base_of_v, "element_type must be base class of V"); } /** - * @brief Construct a unique ownership wrapper. + * @brief Transfer compatible standard unique-pointer ownership implicitly. * * @param uniq Unique pointer whose owned value is transferred. */ template - uniq_ptr(std::unique_ptr &&uniq) noexcept: +#ifndef DOXYGEN + explicit(false) +#endif + uniq_ptr(std::unique_ptr &&uniq) noexcept: _p {uniq.release()} { static_assert(std::is_same_v || std::is_same_v || std::is_base_of_v, "element_type must be base class of V"); } /** - * @brief Construct a unique ownership wrapper. + * @brief Transfer compatible Sunshine unique-pointer ownership implicitly. * * @param other Source object whose state is copied or moved into this object. */ template - uniq_ptr(uniq_ptr &&other) noexcept: +#ifndef DOXYGEN + explicit(false) +#endif + uniq_ptr(uniq_ptr &&other) noexcept: _p {other.release()} { static_assert(std::is_same_v || std::is_same_v || std::is_base_of_v, "element_type must be base class of V"); } @@ -1098,7 +1107,7 @@ namespace util { } protected: - pointer _p; ///< Pointer currently owned by the wrapper. + pointer _p {nullptr}; ///< Pointer currently owned by the wrapper, initially empty. deleter_type _deleter; ///< Callable used to release `_p`. }; @@ -1268,21 +1277,21 @@ namespace util { } /** - * @brief Construct an owning or non-owning wrapper around a raw pointer. + * @brief Explicitly construct an owning or non-owning wrapper around a raw pointer. * * @param p Pointer passed to the deleter or conversion helper. */ - wrap_ptr(pointer p): + explicit wrap_ptr(pointer p): _own_ptr {false}, _p {p} { } /** - * @brief Construct an owning or non-owning wrapper around a raw pointer. + * @brief Explicitly construct an owning or non-owning wrapper around a raw pointer. * * @param uniq_p Uniq p. */ - wrap_ptr(std::unique_ptr &&uniq_p): + explicit wrap_ptr(std::unique_ptr &&uniq_p): _own_ptr {true}, _p {uniq_p.release()} { } diff --git a/src/video.cpp b/src/video.cpp index 854d15616..71066b488 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -546,11 +546,11 @@ namespace video { class nvenc_encode_session_t: public encode_session_t { public: /** - * @brief Initialize an NVENC encode session and take ownership of its device. + * @brief Explicitly initialize an NVENC encode session and take ownership of its device. * * @param encode_device Encode device. */ - nvenc_encode_session_t(std::unique_ptr encode_device): + explicit nvenc_encode_session_t(std::unique_ptr encode_device): device(std::move(encode_device)) { } diff --git a/tests/unit/test_constructor_contracts.cpp b/tests/unit/test_constructor_contracts.cpp new file mode 100644 index 000000000..0926c3cc2 --- /dev/null +++ b/tests/unit/test_constructor_contracts.cpp @@ -0,0 +1,196 @@ +/** + * @file tests/unit/test_constructor_contracts.cpp + * @brief Tests for explicit conversions, ownership transfers, and member initialization. + */ + +// standard includes +#include +#include +#include +#include +#include +#include +#include + +// lib includes +#include + +// local includes +#include "src/crypto.h" +#include "src/move_by_copy.h" +#include "src/platform/common.h" +#include "src/sync.h" +#include "src/task_pool.h" +#include "src/thread_safe.h" +#include "src/utility.h" + +#ifdef _WIN32 + #include "src/platform/windows/display.h" +#endif + +namespace { + using callback_t = std::function; ///< Callable used by task and cleanup wrappers. + using int_ptr_t = util::uniq_ptr>; ///< Integer owned by a Sunshine unique pointer. + using shared_ptr_t = safe::shared_t::ptr_t; ///< Reference to shared integer storage. + using move_wrapper_t = move_by_copy_util::MoveByCopy>; ///< Copy-shaped owner of a move-only integer. + + static_assert(std::is_constructible_v); + static_assert(!std::is_convertible_v); + static_assert(std::is_convertible_v); + static_assert(std::is_convertible_v, int_ptr_t>); + static_assert(!std::is_convertible_v>); + static_assert(!std::is_convertible_v, util::wrap_ptr>); + static_assert(!std::is_convertible_v>); + static_assert(!std::is_convertible_v>); + static_assert(!std::is_convertible_v>); + static_assert(!std::is_convertible_v>>); + static_assert(!std::is_convertible_v); + static_assert(!std::is_convertible_v>); + static_assert(!std::is_convertible_v); + static_assert(!std::is_convertible_v); + static_assert(!std::is_convertible_v); + static_assert(!std::is_convertible_v); + + /** + * @brief Polymorphic resource used to check ownership-preserving pointer conversions. + */ + struct base_t { + virtual ~base_t() = default; + int value {42}; ///< Value retained when ownership is moved to a base pointer. + }; + + /** + * @brief Derived resource that can be owned through its base class. + */ + struct derived_t: base_t {}; + + using base_ptr_t = util::uniq_ptr>; ///< Base-class owner with a virtual destructor. + using derived_ptr_t = util::uniq_ptr>; ///< Compatible derived-class owner. + + static_assert(std::is_convertible_v); + static_assert(std::is_convertible_v>, base_ptr_t>); +} // namespace + +TEST(ConstructorContracts, EmptyUniquePointersHaveNoOwnedResource) { + int_ptr_t default_pointer; + int_ptr_t null_pointer = nullptr; + + EXPECT_EQ(default_pointer.get(), nullptr); + EXPECT_EQ(null_pointer.get(), nullptr); +} + +TEST(ConstructorContracts, ExplicitRawPointerConstructionTakesOwnership) { + auto original = std::make_unique(7); + const auto address = original.get(); + int_ptr_t pointer {original.release()}; + + EXPECT_EQ(pointer.get(), address); + EXPECT_EQ(*pointer, 7); +} + +TEST(ConstructorContracts, CompatibleUniquePointerMovesPreserveOwnership) { + std::unique_ptr> original {std::make_unique()}; + const auto address = original.get(); + derived_ptr_t derived = std::move(original); + base_ptr_t base = std::move(derived); + + EXPECT_EQ(original.get(), nullptr); + EXPECT_EQ(derived.get(), nullptr); + EXPECT_EQ(base.get(), address); + EXPECT_EQ(base->value, 42); +} + +TEST(ConstructorContracts, CompatibleStandardPointerMovesCanTargetBaseOwners) { + std::unique_ptr> original {std::make_unique()}; + const auto address = original.get(); + base_ptr_t base = std::move(original); + + EXPECT_EQ(original.get(), nullptr); + EXPECT_EQ(base.get(), address); +} + +TEST(ConstructorContracts, WrapPointersKeepBorrowedAndOwnedValuesAccessible) { + int borrowed_value = 7; + util::wrap_ptr borrowed {&borrowed_value}; + util::wrap_ptr owned {std::make_unique(42)}; + + EXPECT_EQ(*borrowed, 7); + EXPECT_EQ(*owned, 42); +} + +TEST(ConstructorContracts, MovingDisabledFailGuardsKeepsCleanupDisabled) { + int calls = 0; + { + auto original = util::fail_guard([&calls]() { + ++calls; + }); + original.disable(); + auto moved = std::move(original); + EXPECT_FALSE(moved.failure); + } + EXPECT_EQ(calls, 0); +} + +TEST(ConstructorContracts, ExplicitTaskConstructionRunsTheSuppliedCallable) { + int calls = 0; + task_pool_util::_Impl task {callback_t {[&calls]() { + ++calls; + }}}; + task.run(); + + EXPECT_EQ(calls, 1); +} + +TEST(ConstructorContracts, ExplicitSynchronizedConstructionKeepsTheInitialValue) { + sync_util::sync_t value {42}; + EXPECT_EQ(value.raw, 42); +} + +TEST(ConstructorContracts, ExplicitMoveWrapperConversionTransfersTheValue) { + auto original = std::make_unique(42); + auto wrapper = move_by_copy_util::cmove(original); + auto value = static_cast>(wrapper); + + EXPECT_EQ(original.get(), nullptr); + ASSERT_NE(value.get(), nullptr); + EXPECT_EQ(*value, 42); +} + +TEST(ConstructorContracts, SharedPointersSupportExplicitBooleanChecks) { + shared_ptr_t pointer; + + EXPECT_FALSE(static_cast(pointer)); +} + +TEST(ConstructorContracts, ExplicitCipherConstructionKeepsEncryptionWorking) { + const crypto::aes_t key {16}; + crypto::aes_t iv {16}; + constexpr std::string_view plaintext = "0123456789abcdef"; + crypto::cipher::ecb_t ecb {key, false}; + crypto::cipher::cbc_t cbc {key, false}; + crypto::cipher::gcm_t gcm {key, false}; + std::vector encrypted; + std::vector decrypted; + std::array cipher {}; + std::array tag {}; + + ASSERT_EQ(ecb.encrypt(plaintext, encrypted), 0); + const std::string ciphertext {encrypted.begin(), encrypted.end()}; + ASSERT_EQ(ecb.decrypt(ciphertext, decrypted), 0); + EXPECT_EQ((std::string {decrypted.begin(), decrypted.end()}), plaintext); + EXPECT_EQ(cbc.encrypt(plaintext, cipher.data(), &iv), plaintext.size()); + EXPECT_EQ(gcm.encrypt(plaintext, tag.data(), cipher.data(), &iv), plaintext.size()); +} + +#ifdef _WIN32 +TEST(ConstructorContracts, CursorViewportsStartEmptyWithTheFullDepthRange) { + platf::dxgi::gpu_cursor_t cursor; + + EXPECT_FLOAT_EQ(cursor.cursor_view.TopLeftX, 0.0f); + EXPECT_FLOAT_EQ(cursor.cursor_view.TopLeftY, 0.0f); + EXPECT_FLOAT_EQ(cursor.cursor_view.Width, 0.0f); + EXPECT_FLOAT_EQ(cursor.cursor_view.Height, 0.0f); + EXPECT_FLOAT_EQ(cursor.cursor_view.MinDepth, 0.0f); + EXPECT_FLOAT_EQ(cursor.cursor_view.MaxDepth, 1.0f); +} +#endif