diff --git a/src-tauri/src/audio.rs b/src-tauri/src/audio.rs index d1938cd..2b0b27a 100644 --- a/src-tauri/src/audio.rs +++ b/src-tauri/src/audio.rs @@ -96,11 +96,25 @@ impl AudioSession { } fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> { - // SAFETY: WAVEFORMATEX is repr(packed); read_unaligned avoids UB from unaligned field access. - let w_format_tag = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wFormatTag)) }; - let n_channels = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nChannels)) }; - let n_samples_per_sec = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nSamplesPerSec)) }; - let w_bits_per_sample = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wBitsPerSample)) }; + // WAVEFORMATEX is repr(packed), so the fields have to be read with + // read_unaligned rather than through references. `fmt` comes from + // GetMixFormat and stays valid for the whole call. + // + // Kept in one block because the four reads share one invariant. + #[allow( + clippy::multiple_unsafe_ops_per_block, + reason = "one packed-struct readout; splitting would repeat the same safety argument four times" + )] + // SAFETY: `fmt` is a valid, fully-initialized WAVEFORMATEX for the duration + // of this function, and each read copies an integer out by value. + let (w_format_tag, n_channels, n_samples_per_sec, w_bits_per_sample) = unsafe { + ( + std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wFormatTag)), + std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nChannels)), + std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nSamplesPerSec)), + std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wBitsPerSample)), + ) + }; let is_float = if w_format_tag == WAVE_FORMAT_IEEE_FLOAT { true diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 5a719fd..e25229b 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -363,6 +363,10 @@ impl TonemapPipeline { // -> viewport+scissor -> draw. Every stage is set explicitly because the // frame's device/context still carries state from prior frames. // + #[allow( + clippy::multiple_unsafe_ops_per_block, + reason = "the bind sequence only makes sense as one unit; splitting it would imply the intermediate states are reachable" + )] // SAFETY: every resource bound here was created on this same device and // is kept alive by `self` for the duration of the draw; the slices and // viewport/scissor arrays are stack locals that outlive each call. @@ -388,10 +392,15 @@ impl TonemapPipeline { } // Copy to the SDR staging texture and read it back. + let row_bytes = self.width * 4; + #[allow( + clippy::multiple_unsafe_ops_per_block, + reason = "copy/map/read/unmap must stay paired; the map guard has to be released in the same scope" + )] // SAFETY: both textures live on this device and share dimensions and // format, so the copy is well-defined; `mapped` is a zeroed local that - // Map fills before any field of it is read. - let row_bytes = self.width * 4; + // Map fills before any field of it is read, and the slice is sized from + // the mapped pitch and this pipeline's own height. unsafe { context.CopyResource(&self.staging, &self.render_target); let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); diff --git a/src-tauri/src/clicks.rs b/src-tauri/src/clicks.rs index 3a612c9..73d8cde 100644 --- a/src-tauri/src/clicks.rs +++ b/src-tauri/src/clicks.rs @@ -52,10 +52,14 @@ pub(crate) fn start() -> ClickRecorder { while running_clone.load(Ordering::Relaxed) { for (i, &(vk, button)) in buttons.iter().enumerate() { + // SAFETY: both calls are self-contained Win32 queries. `pt` is + // a local that GetCursorPos writes, and it is only read after + // the call reports success. let state = unsafe { GetAsyncKeyState(vk) }; let pressed = (state.cast_unsigned() & 0x8000) != 0; if pressed && !last_pressed[i] { let mut pt = POINT::default(); + // SAFETY: `pt` is a live local the call writes through. if unsafe { GetCursorPos(&raw mut pt) }.is_ok() { let click = Click { time_secs: start.elapsed().as_secs_f64(), diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 49ddcb9..1d90c90 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1212,6 +1212,7 @@ fn start_overlay_clickthrough_poll( } let mut pt = POINT::default(); + // SAFETY: `pt` is a live local that GetCursorPos writes through. if unsafe { GetCursorPos(&raw mut pt) }.is_err() { continue; } @@ -1225,6 +1226,7 @@ fn start_overlay_clickthrough_poll( None => continue, }; + // SAFETY: `raw` is the overlay's own live HWND from Tauri. let dpi = unsafe { GetDpiForWindow(HWND(raw.0.cast::())) }; let scale = if dpi > 0 { f64::from(dpi) / 96.0 } else { 1.0 }; let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; @@ -1256,6 +1258,8 @@ fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(), }; let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; let hwnd = HWND(raw.0.cast::()); + // SAFETY: `hwnd` is the overlay's live window handle and the affinity flag + // is a plain enum with no pointer arguments. unsafe { SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) .map_err(|e| format!("SetWindowDisplayAffinity: {e}"))?; @@ -1288,11 +1292,21 @@ fn show_overlay(app: AppHandle) -> Result<(), String> { if let Ok(raw) = win.hwnd() { if let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) { let center = POINT { x: i32::midpoint(vl, vr), y: i32::midpoint(vt, vb) }; + // MonitorFromPoint only reads the POINT by value and returns null + // for "no monitor", which the next branch handles. + // + // SAFETY: the POINTs passed in are plain values constructed here. let hmon = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) }; if hmon.0.is_null() { let hwnd = HWND(raw.0.cast::()); + // SAFETY: same value-only call; MONITOR_DEFAULTTOPRIMARY cannot + // fail on a running desktop. let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) }; + // cbSize is required by GetMonitorInfoW and is set from the + // actual struct size, so the write below stays in bounds. let mut mi = MONITORINFO { cbSize: size_of::() as u32, ..Default::default() }; + // SAFETY: `mi` is a live local of the declared size, and the + // result is checked with as_bool() before mi is read. if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() { let work = mi.rcWork; let w = vr - vl; @@ -1300,6 +1314,8 @@ fn show_overlay(app: AppHandle) -> Result<(), String> { let cx = i32::midpoint(work.left, work.right) - w / 2; let cy = i32::midpoint(work.top, work.bottom) - h / 2; drop( + // SAFETY: `hwnd` is the overlay's live handle; the flags + // keep this a size-only, non-activating move. unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) }, ); } @@ -1400,6 +1416,8 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result< let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let outer_w = sz.width.cast_signed().max(2); let outer_h = (target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0).round() as i32; + // SAFETY: `hwnd` is the overlay's live handle; the flags keep the resize + // non-activating and non-reordering, and no pointers are involved. unsafe { SetWindowPos(hwnd, Some(HWND_TOP), 0, 0, outer_w, outer_h, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE) @@ -1454,8 +1472,11 @@ fn open_window_picker( use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; let hwnd = HWND(h.0.cast::()); let mut gr = RECT::default(); + // SAFETY: `gr` is a live local that GetWindowRect writes through. drop(unsafe { GetWindowRect(hwnd, &raw mut gr) }); let mut dr = RECT::default(); + // SAFETY: `dr` is a live RECT local, the attribute is the documented + // DWMWA_EXTENDED_FRAME_BOUNDS, and the size passed matches its type. drop(unsafe { DwmGetWindowAttribute( hwnd, @@ -1501,6 +1522,8 @@ fn visible_window_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> { use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void); let mut dwm = RECT::default(); + // SAFETY: `dwm` is a live RECT local and the size argument matches it; the + // result is checked and the rect is only read when it is well-formed. if unsafe { DwmGetWindowAttribute( hwnd, @@ -1516,6 +1539,7 @@ fn visible_window_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> { return Some((dwm.left, dwm.top, dwm.right, dwm.bottom)); } let mut outer = RECT::default(); + // SAFETY: `outer` is a live RECT local that the call writes through. if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_ok() { Some((outer.left, outer.top, outer.right, outer.bottom)) } else { @@ -1530,10 +1554,12 @@ fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) { let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void); let mut outer = RECT::default(); + // SAFETY: `outer` is a live RECT local that the call writes through. if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_err() { return (0, 0, 0, 0); } let mut dwm = RECT::default(); + // SAFETY: `dwm` is a live RECT local and the size argument matches it. let r = unsafe { DwmGetWindowAttribute( hwnd, @@ -1560,12 +1586,15 @@ fn scale_factor_at_point(x: i32, y: i32) -> f64 { use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MONITOR_DPI_TYPE}; let pt = POINT { x, y }; + // SAFETY: value-only call; a null result is handled on the next line. let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) }; if hmonitor.0.is_null() { return 1.0; } let mut dpi_x = 0u32; let mut dpi_y = 0u32; + // SAFETY: both out-params are live u32 locals that the call writes through, + // and `hmonitor` was checked non-null above. let hr = unsafe { GetDpiForMonitor( hmonitor, @@ -1627,6 +1656,8 @@ fn set_overlay_to_window( SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER, }; let hwnd = HWND(raw.0.cast::()); + // SAFETY: `hwnd` is the overlay's live handle and every dimension is a + // plain integer computed above; no pointers are passed. unsafe { SetWindowPos( hwnd, diff --git a/src-tauri/src/window_picker.rs b/src-tauri/src/window_picker.rs index 1189433..b4615f0 100644 --- a/src-tauri/src/window_picker.rs +++ b/src-tauri/src/window_picker.rs @@ -14,24 +14,34 @@ use windows::Win32::UI::WindowsAndMessaging::{ IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW, }; -unsafe fn visible_window_rect(hwnd: HWND) -> Option { unsafe { +/// Resolve the visible frame of a window: the DWM extended frame when the +/// compositor reports one, otherwise the raw window rect. +/// +/// # Safety +/// +/// The caller must pass a live `HWND`. +unsafe fn visible_window_rect(hwnd: HWND) -> Option { let mut rect = RECT::default(); - let r = DwmGetWindowAttribute( - hwnd, - DWMWA_EXTENDED_FRAME_BOUNDS, - (&raw mut rect).cast::(), - size_of::() as u32, - ); + // SAFETY: `rect` is a live RECT local and the size argument matches it. + let r = unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_EXTENDED_FRAME_BOUNDS, + (&raw mut rect).cast::(), + size_of::() as u32, + ) + }; if r.is_ok() && rect.right > rect.left && rect.bottom > rect.top { return Some(rect); } let mut fallback = RECT::default(); - if GetWindowRect(hwnd, &raw mut fallback).is_ok() { + // SAFETY: `fallback` is a live RECT local that the call writes through. + if unsafe { GetWindowRect(hwnd, &raw mut fallback) }.is_ok() { Some(fallback) } else { None } -}} +} const VK_LBUTTON: i32 = 0x01; const VK_ESCAPE: i32 = 0x1B; @@ -68,17 +78,33 @@ const SHELL_CLASSES: &[&str] = &[ "Windows.UI.Core.CoreWindow", ]; -unsafe fn class_of(hwnd: HWND) -> String { unsafe { +/// Read a window's class name into a fixed buffer. +/// +/// # Safety +/// +/// The caller must pass a live `HWND`. +unsafe fn class_of(hwnd: HWND) -> String { let mut buf = [0u16; 128]; - let n = GetClassNameW(hwnd, &mut buf); + // SAFETY: GetClassNameW writes at most buf.len() UTF-16 units into `buf`; + // it returns the count written, which is bounds-checked before slicing. + let n = unsafe { GetClassNameW(hwnd, &mut buf) }; if n <= 0 { return String::new(); } String::from_utf16_lossy(&buf[..n as usize]) -}} +} -unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { - let ctx = &mut *(lparam.0 as *mut EnumCtx); +/// `EnumWindows` callback: records the first top-level window containing the +/// target point. Returning FALSE stops the enumeration. +/// +/// # Safety +/// +/// `EnumWindows` hands back the `LPARAM` that `top_window_at` passed in, which +/// is a live `*mut EnumCtx` for the duration of the enumeration. +unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { + // SAFETY: `lparam` is the pointer passed to EnumWindows by top_window_at, + // and that EnumCtx outlives the call. + let ctx = unsafe { &mut *(lparam.0 as *mut EnumCtx) }; if ctx.found.is_some() { return BOOL(1); } @@ -86,21 +112,29 @@ unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { un if ctx.exclude.contains(&id) { return BOOL(1); } - if !IsWindowVisible(hwnd).as_bool() { + // The checks below are all read-only queries against the window handle + // EnumWindows just handed us, so it is live for this call. + // + // SAFETY: `hwnd` is a live top-level window handle. + if !unsafe { IsWindowVisible(hwnd) }.as_bool() { return BOOL(1); } - if IsIconic(hwnd).as_bool() { + // SAFETY: same live handle. + if unsafe { IsIconic(hwnd) }.as_bool() { return BOOL(1); } - let ex = GetWindowLongW(hwnd, GWL_EXSTYLE).cast_unsigned(); + // SAFETY: same live handle; GWL_EXSTYLE reads a window style word. + let ex = unsafe { GetWindowLongW(hwnd, GWL_EXSTYLE) }.cast_unsigned(); if (ex & WS_EX_TOOLWINDOW.0) != 0 { return BOOL(1); } - let class_name = class_of(hwnd); + // SAFETY: `hwnd` is the live handle described above. + let class_name = unsafe { class_of(hwnd) }; if SHELL_CLASSES.iter().any(|c| class_name == *c) { return BOOL(1); } - let rect = match visible_window_rect(hwnd) { + // SAFETY: `hwnd` is the live handle described above. + let rect = match unsafe { visible_window_rect(hwnd) } { Some(r) => r, None => return BOOL(1), }; @@ -118,7 +152,7 @@ unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { un } ctx.found = Some((id, rect)); BOOL(0) -}} +} fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> { let mut ctx = EnumCtx { @@ -126,6 +160,8 @@ fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> { exclude: exclude.to_vec(), found: None, }; + // SAFETY: `ctx` is a live local of exactly the type enum_at_point expects, + // and it outlives the call because EnumWindows runs to completion here. unsafe { drop(EnumWindows( Some(enum_at_point), @@ -149,6 +185,7 @@ pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession } let mut pt = POINT::default(); + // SAFETY: `pt` is a live local that GetCursorPos writes through. if unsafe { GetCursorPos(&raw mut pt) }.is_err() { thread::sleep(Duration::from_millis(30)); continue; @@ -158,6 +195,7 @@ pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession if let Some((id, rect)) = target { if id != last_hwnd { + // SAFETY: `id` came from EnumWindows, so it is a live HWND. let class = unsafe { class_of(HWND(id as *mut std::ffi::c_void)) }; tracing::info!( "picker hover: hwnd={:x} class={} rect=({},{}) {}x{}", @@ -185,6 +223,7 @@ pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession } let pressed = + // SAFETY: a self-contained query with no pointer arguments. unsafe { (GetAsyncKeyState(VK_LBUTTON).cast_unsigned() & 0x8000) != 0 }; if pressed && !last_pressed { if let Some((_, rect)) = target { @@ -203,6 +242,7 @@ pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession last_pressed = pressed; let esc = + // SAFETY: a self-contained query with no pointer arguments. unsafe { (GetAsyncKeyState(VK_ESCAPE).cast_unsigned() & 0x8000) != 0 }; if esc && !last_esc { drop(app.emit("picker-cancel", ())); diff --git a/src-tauri/src/windows_list.rs b/src-tauri/src/windows_list.rs index 0c78a33..0635a55 100644 --- a/src-tauri/src/windows_list.rs +++ b/src-tauri/src/windows_list.rs @@ -18,6 +18,8 @@ pub(crate) struct WindowInfo { pub(crate) fn list_visible_windows() -> Vec { let mut out: Vec = Vec::new(); + // SAFETY: `out` is a live local of exactly the type enum_cb expects, and it + // outlives the call because EnumWindows runs to completion here. unsafe { drop(EnumWindows( Some(enum_cb), @@ -27,16 +29,26 @@ pub(crate) fn list_visible_windows() -> Vec { out } -unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { - if !IsWindowVisible(hwnd).as_bool() { - return BOOL(1); - } - if IsIconic(hwnd).as_bool() { +/// `EnumWindows` callback: appends every visible, titled, non-minimised +/// top-level window to the `Vec` behind `lparam`. +/// +/// # Safety +/// +/// `EnumWindows` hands back the `LPARAM` that `list_visible_windows` passed in, +/// which is a live `*mut Vec` for the duration of the enumeration. +unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { + // SAFETY: `hwnd` comes from the enumerator, so it is a live handle for the + // duration of this call. + let visible = unsafe { IsWindowVisible(hwnd) }; + // SAFETY: same live handle. + let iconic = unsafe { IsIconic(hwnd) }; + if !visible.as_bool() || iconic.as_bool() { return BOOL(1); } let mut rect = RECT::default(); - if GetWindowRect(hwnd, &raw mut rect).is_err() { + // SAFETY: `rect` is a live RECT local that the call writes through. + if unsafe { GetWindowRect(hwnd, &raw mut rect) }.is_err() { return BOOL(1); } let w = rect.right - rect.left; @@ -45,12 +57,15 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { return BOOL(1); } - let title_len = GetWindowTextLengthW(hwnd); + // SAFETY: `hwnd` is the live handle described above. + let title_len = unsafe { GetWindowTextLengthW(hwnd) }; if title_len <= 0 { return BOOL(1); } let mut buf = vec![0u16; (title_len as usize) + 1]; - let copied = GetWindowTextW(hwnd, &mut buf); + // SAFETY: `buf` has room for title_len + 1 UTF-16 units, which is what the + // call is documented to write at most; the result is bounds-checked below. + let copied = unsafe { GetWindowTextW(hwnd, &mut buf) }; if copied <= 0 { return BOOL(1); } @@ -59,7 +74,9 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { return BOOL(1); } - let list = &mut *(lparam.0 as *mut Vec); + // SAFETY: `lparam` is the pointer passed to EnumWindows by + // list_visible_windows, and that Vec outlives the call. + let list = unsafe { &mut *(lparam.0 as *mut Vec) }; list.push(WindowInfo { title, x: rect.left, @@ -68,4 +85,4 @@ unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> BOOL { unsafe { height: h.cast_unsigned(), }); BOOL(1) -}} +}