From f1383d5754f16ec21b65adbcb8b7bad9a37468ad Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Fri, 20 Nov 2026 00:15:39 -0500 Subject: [PATCH 1/3] obs-hotkey: RED Tier 1 mirrors of the key-translation query and store (Refs #5321) Safe Rust mirrors of every assertion of the unchanged test_hotkey_key_translation.c, plus the original's slot access order, against a todo!() core for obs_get_hotkey_translation and obs_hotkeys_store_key_translation. soldr cargo test -p obs-data --test obs-tests-core -- hotkey::key_translation:: test result: FAILED. 0 passed; 6 failed Co-Authored-By: Claude Opus 5.5 --- rust/obs-hotkey/src/key_translation.rs | 43 ++++ rust/obs-hotkey/src/lib.rs | 6 +- .../tests/hotkey/key_translation.rs | 205 ++++++++++++++++++ rust/obs-hotkey/tests/hotkey/main.rs | 1 + 4 files changed, 253 insertions(+), 2 deletions(-) create mode 100644 rust/obs-hotkey/src/key_translation.rs create mode 100644 rust/obs-hotkey/tests/hotkey/key_translation.rs diff --git a/rust/obs-hotkey/src/key_translation.rs b/rust/obs-hotkey/src/key_translation.rs new file mode 100644 index 0000000000..ac5540fa84 --- /dev/null +++ b/rust/obs-hotkey/src/key_translation.rs @@ -0,0 +1,43 @@ +//! The key name store, `obs->hotkeys.translations[]`, and its query +//! (`libobs/obs-hotkey-key-translation.c.h`). +//! +//! The table, its allocator and the key range stay with the caller: the +//! query takes no lock and checks no range, as in C. A stored name is +//! borrowed by the query, never copied. + +/// `OBS_KEY_NONE` in `obs-hotkeys.h`. +pub const OBS_KEY_NONE: i32 = 0; + +/// Access to the caller's per-key name slots and their allocator. +pub trait KeyTranslations { + /// A stored or caller-owned name (never null). + type Text: Copy; + /// The current slot of `key`; one read of the table per call. + fn get(&mut self, key: i32) -> Option; + /// Overwrite the slot of `key`. + fn set(&mut self, key: i32, value: Option); + /// Release a stored name; `None` is released too, as `bfree(NULL)`. + fn release(&mut self, value: Option); + /// An owned copy of `value` in the table's allocator. + fn duplicate(&mut self, value: Self::Text) -> Self::Text; +} + +/// The stored name of `key`, else `default`. `OBS_KEY_NONE` returns `None` +/// without touching the table. +#[expect(clippy::todo, reason = "RED stub")] +pub fn translation( + table: &mut T, + key: i32, + default: Option, +) -> Option { + let _ = (table, key, default); + todo!() +} + +/// Replace the stored name of `key` with a copy of `translation`, or clear +/// it for `None`. The old name is released first. +#[expect(clippy::todo, reason = "RED stub")] +pub fn store(table: &mut T, key: i32, translation: Option) { + let _ = (table, key, translation); + todo!() +} diff --git a/rust/obs-hotkey/src/lib.rs b/rust/obs-hotkey/src/lib.rs index a74ef967e0..7beffbedff 100644 --- a/rust/obs-hotkey/src/lib.rs +++ b/rust/obs-hotkey/src/lib.rs @@ -11,7 +11,8 @@ //! `libobs/obs-nix-wayland-keys.c.h`, `libobs/obs-nix-wayland-seats.c.h`, //! `libobs/obs-nix-x11-hotkeys.c.h`, `libobs/obs-nix-x11-input.c.h`, //! `libobs/obs-nix-x11-keys.c.h`, `libobs/obs-cocoa-keys.c.h`, -//! `libobs/obs-key-combination-host-posix.c.h` and +//! `libobs/obs-key-combination-host-posix.c.h`, +//! `libobs/obs-hotkey-key-translation.c.h` and //! `libobs/obs-windows-keys.c.h`. //! //! The safe cores are [`name_map`], [`bindings`], [`translations`], @@ -21,7 +22,7 @@ //! [`portal_shortcut_status`], [`nix_wayland_key_names`], //! [`nix_wayland_keys`], [`nix_wayland_seats`], //! [`nix_x11_hotkeys`], [`nix_x11_input`], [`nix_x11_keys`], [`cocoa_keys`], -//! [`key_combination`] and [`windows_keys`]. +//! [`key_combination`], [`key_translation`] and [`windows_keys`]. //! The X11 and Wayland key names share one crate-private table, //! `key_route`. The C ABI shims live in [`ffi`]. @@ -52,6 +53,7 @@ pub mod identity_getters; pub mod identity_setters; pub mod inject_entry; pub mod key_combination; +pub mod key_translation; mod key_route; pub mod name_map; pub mod nix_hotkey_state; diff --git a/rust/obs-hotkey/tests/hotkey/key_translation.rs b/rust/obs-hotkey/tests/hotkey/key_translation.rs new file mode 100644 index 0000000000..1f8beb656b --- /dev/null +++ b/rust/obs-hotkey/tests/hotkey/key_translation.rs @@ -0,0 +1,205 @@ +//! Tier 1: every assertion of the unchanged test_hotkey_key_translation.c +//! against the safe query and store. The table hands out handles into an +//! arena of owned strings, so identity (a handle) and content (its bytes) +//! are checked apart, as the C test checks pointers and strings. Live +//! allocations stand in for `bnum_allocs()`. +use obs_hotkey::key_translation::{KeyTranslations, OBS_KEY_NONE, store, translation}; + +/// Any two distinct keys other than `OBS_KEY_NONE`. +const OBS_KEY_A: i32 = 0x41; +const OBS_KEY_B: i32 = 0x42; +const KEYS: usize = 0x200; + +/// A name: its arena slot. Caller-owned names live in the arena too but are +/// never counted as allocations. +type Handle = usize; + +struct Table { + slots: Vec>, + arena: Vec>>, + /// Handles the table allocated and has not released. + owned: Vec, + forbid_reads: bool, + reads: u32, + releases: u32, +} + +impl Table { + fn new() -> Self { + Self { + slots: vec![None; KEYS], + arena: Vec::new(), + owned: Vec::new(), + forbid_reads: false, + reads: 0, + releases: 0, + } + } + + /// A caller-owned name (`char translation[] = "..."`). + fn caller(&mut self, text: &str) -> Handle { + self.arena.push(Some(text.as_bytes().to_vec())); + self.arena.len() - 1 + } + + fn text(&self, handle: Handle) -> &[u8] { + self.arena[handle].as_deref().expect("live name") + } + + fn slot(&self, key: i32) -> Option { + self.slots[usize::try_from(key).unwrap()] + } + + fn allocations(&self) -> usize { + self.owned.len() + } + + /// The C teardown: free each stored name, as obs_hotkeys_free does. + fn teardown(mut self, before: usize) { + for key in 0..KEYS { + if let Some(handle) = self.slots[key].take() { + self.owned.retain(|h| *h != handle); + } + } + assert_eq!(self.allocations(), before); + } +} + +impl KeyTranslations for Table { + type Text = Handle; + fn get(&mut self, key: i32) -> Option { + assert!(!self.forbid_reads, "core read"); + self.reads += 1; + self.slot(key) + } + fn set(&mut self, key: i32, value: Option) { + assert!(!self.forbid_reads, "core read"); + self.reads += 1; + self.slots[usize::try_from(key).unwrap()] = value; + } + fn release(&mut self, value: Option) { + self.releases += 1; + if let Some(handle) = value { + let before = self.owned.len(); + self.owned.retain(|h| *h != handle); + assert_eq!(self.owned.len() + 1, before, "release of an owned name"); + self.arena[handle] = None; + } + } + fn duplicate(&mut self, value: Handle) -> Handle { + let copy = self.text(value).to_vec(); + self.arena.push(Some(copy)); + let handle = self.arena.len() - 1; + self.owned.push(handle); + handle + } +} + +#[test] +fn none_without_core() { + let mut t = Table::new(); + let before = t.allocations(); + let fallback = t.caller("default"); + t.forbid_reads = true; + assert_eq!(translation(&mut t, OBS_KEY_NONE, Some(fallback)), None); + assert_eq!(translation(&mut t, OBS_KEY_NONE, None), None); + assert_eq!(t.reads, 0); + t.forbid_reads = false; + t.teardown(before); +} + +#[test] +fn stored_pointer() { + let mut t = Table::new(); + let before = t.allocations(); + let name = t.caller("translated A"); + let fallback = t.caller("default"); + store(&mut t, OBS_KEY_A, Some(name)); + let stored = t.slot(OBS_KEY_A).expect("stored"); + assert_ne!(stored, name); + assert_eq!(t.text(stored), t.text(name)); + assert_eq!(translation(&mut t, OBS_KEY_A, Some(fallback)), Some(stored)); + assert_eq!(translation(&mut t, OBS_KEY_A, None), Some(stored)); + assert_eq!(t.allocations(), before + 1); + t.teardown(before); +} + +#[test] +fn unset_fallback() { + let mut t = Table::new(); + let before = t.allocations(); + let fallback = t.caller("default"); + let empty = t.caller(""); + assert_eq!( + translation(&mut t, OBS_KEY_B, Some(fallback)), + Some(fallback) + ); + assert_eq!(translation(&mut t, OBS_KEY_B, Some(empty)), Some(empty)); + assert_eq!(t.slot(OBS_KEY_B), None); + t.teardown(before); +} + +#[test] +fn null_default() { + let mut t = Table::new(); + let before = t.allocations(); + assert_eq!(translation(&mut t, OBS_KEY_B, None), None); + t.teardown(before); +} + +#[test] +fn restore_pointer() { + let mut t = Table::new(); + let before = t.allocations(); + let first = t.caller("first"); + let second = t.caller("a longer replacement translation"); + let empty = t.caller(""); + let fallback = t.caller("default"); + for value in [first, second, empty] { + store(&mut t, OBS_KEY_A, Some(value)); + let stored = t.slot(OBS_KEY_A).expect("stored"); + assert_ne!(stored, value); + assert_eq!(t.text(stored), t.text(value)); + // Compare with the CURRENT slot, as the C test does. + assert_eq!(translation(&mut t, OBS_KEY_A, Some(fallback)), Some(stored)); + assert_eq!(t.allocations(), before + 1); + } + store(&mut t, OBS_KEY_A, None); + assert_eq!(t.slot(OBS_KEY_A), None); + assert_eq!( + translation(&mut t, OBS_KEY_A, Some(fallback)), + Some(fallback) + ); + assert_eq!(translation(&mut t, OBS_KEY_A, None), None); + assert_eq!(t.allocations(), before); + t.teardown(before); +} + +/// The original's access order: the store frees the old slot (NULL too), +/// clears it, then writes the copy; the query reads the slot again to +/// return it. No other key is touched. +#[test] +fn access_order_matches_the_original() { + let mut t = Table::new(); + let name = t.caller("name"); + t.reads = 0; + store(&mut t, OBS_KEY_A, Some(name)); + assert_eq!((t.reads, t.releases), (3, 1)); + t.reads = 0; + store(&mut t, OBS_KEY_A, None); + assert_eq!((t.reads, t.releases), (2, 2)); + t.reads = 0; + assert_eq!(translation(&mut t, OBS_KEY_A, Some(name)), Some(name)); + assert_eq!(t.reads, 1); + store(&mut t, OBS_KEY_A, Some(name)); + t.reads = 0; + let stored = t.slot(OBS_KEY_A); + assert_eq!(translation(&mut t, OBS_KEY_A, None), stored); + assert_eq!(t.reads, 2); + for key in 0..KEYS { + if key != usize::try_from(OBS_KEY_A).unwrap() { + assert_eq!(t.slots[key], None, "key {key}"); + } + } + t.teardown(0); +} diff --git a/rust/obs-hotkey/tests/hotkey/main.rs b/rust/obs-hotkey/tests/hotkey/main.rs index db57cadbae..d1d5ff4737 100644 --- a/rust/obs-hotkey/tests/hotkey/main.rs +++ b/rust/obs-hotkey/tests/hotkey/main.rs @@ -35,6 +35,7 @@ mod inject_entry; mod inject_entry_parity; mod key_combination; mod key_combination_parity; +mod key_translation; mod nix_hotkey_state; mod nix_hotkey_state_parity; mod nix_wayland_key_names; From 4626b387f49305df1efbf459ccfe19a19117f135 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Fri, 20 Nov 2026 00:33:34 -0500 Subject: [PATCH 2/3] obs-hotkey: swap hotkey key-translation query and store to safe Rust (Refs #5321) obs_get_hotkey_translation and obs_hotkeys_store_key_translation (both hidden, obs-internal.h) now come from obs-hotkey in hybrid libobs. The query returns NULL for OBS_KEY_NONE without touching the core, else the stored pointer (read again to return it, as C's ternary) or the default. The store frees the old name (NULL too), clears the slot and stores a bstrdup copy. No lock, no key range check, as before. The name array and bfree/bstrdup stay in C behind private adapters (obs-hotkey-key-translation-fields.c.h, core group and a shared Rust-static support member). The original moves to libobs.ported-hotkey-key-translation for the C reference. The unchanged test_hotkey_key_translation keeps testing the C source; a new test_hotkey_key_translation_rust twin selects its HOTKEY_KEY_TRANSLATION_EXTERNAL seam and binds the real adapters to the test's own core in one unity group, so the same assertions run on the Rust symbols. The translations shim calls the Rust store directly; the store stand-ins in the hotkey test binary, the bench and windows-keys-rust-stubs.c are gone (the real definition replaces them). Tier 3 runs the original and the shims on one recording core through the real-named adapters (free/copy trace, read count, returned pointer, stored slot, allocation balance, other keys) with eight mutants. soldr cargo test -p obs-data --test obs-tests-core -- hotkey::key_translation hotkey::translations test result: ok. 48 passed; 0 failed Co-Authored-By: Claude Opus 5.5 Ci-Attestation: {"at":1795154791,"gate":"data/all/compatibility","host":"linux-x86_64","key":"","lane":"client-checks","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":96,"stamp":"60038850620514c8f2ef91bda1f34e74","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154791,"gate":"data/all/flatpak-manifest","host":"linux-x86_64","key":"","lane":"client-checks","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":96,"stamp":"7cd019a9b2cceba8636e9c289b98ea63","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154791,"gate":"data/all/qt-xml","host":"linux-x86_64","key":"","lane":"client-checks","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":96,"stamp":"b67296b2234a3fcb2ba47b0915298ea9","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154791,"gate":"data/all/services-schema","host":"linux-x86_64","key":"","lane":"client-checks","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":96,"stamp":"22108fc11e554a23654ca39d6d832188","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"general/all/client-lint","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"59910c1e57d34ddc1965b970e8013aa0","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154791,"gate":"python/all/self-test","host":"linux-x86_64","key":"","lane":"client-checks","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":96,"stamp":"184efd6f471a757cb80bbc4096b9bfe1","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/aarch64-apple-darwin/client-clippy","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"6ee985a7cf873e9d6b8458e84e05c0dc","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/aarch64-apple-darwin/client-dylint","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"a38a28642b81e0641da18bbaa97fccba","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/aarch64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"81013b65e87f99ad00788fe07df794aa","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/aarch64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"41153ce2466c5d729c70dfe3de29b85f","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/aarch64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"046cadd9317e8607d0670dbe85b3b9c6","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/aarch64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"bf09de774cbc2890db0e3cad5a179723","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/x86_64-apple-darwin/client-clippy","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"94c5c3c737b10074d1f9ad3d15e530f3","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/x86_64-apple-darwin/client-dylint","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"5dd42ec31d9444ae826815316eb669f5","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/x86_64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"f5dedca47bbe961719d4ebb9e770317b","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/x86_64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"b7bb52dfff5542176822e68846c4bf70","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/x86_64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"04d3f8d71bbb577e13851d0396e24854","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795154695,"gate":"rust/x86_64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"5d7c34f32aa73072551f9d058df55976992661c8a1b8d61bfda01a15f172180b","lane":"client-lint","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":90,"stamp":"ec79a9d15a7c61c5fde8bfcafd518fac","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Ci-Attestation: {"at":1795155038,"gate":"rust/x86_64-unknown-linux-gnu/client-test","host":"linux-x86_64","key":"84dc5b179dc5a94323476e7391a206b1eb91cda323678101ad4f5ea9723dc73d","lane":"client-test-x86_64-unknown-linux-gnu","parents":["3885e487237cd05a3ff7febf000fbf6a3fab85c6"],"secs":246,"stamp":"fc1922c91d740b22516db9cf60b30c95","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2","v":1,"via":"run"} Client-Checks: {"checks":{"base":"7dffa4d67d6ccc3a53f85dcc41a95f26e6a36f0b","coverage":"all-tracked-applicable-files","diff":["ci/test_bench_libobs_stand_ins.py","libobs/build/libobs.core+.h.c","libobs/build/libobs.ported-hotkey-key-translation+.h.c","libobs/build/ported-source-sets/hotkey-key-translation.json","libobs/cmake/rust-hidden.d/obs-hotkey-key_translation.txt","libobs/obs-hotkey-key-translation-fields.c.h","rust/README.md","rust/obs-build/tests/native.rs","rust/obs-build/tests/native/registration/canonical_hotkey_key_translation_swap_is_registered.rs","rust/obs-build/tests/native/registration/rust-static/cases/hotkey-control/test_hotkey_key_translation_rust.json","rust/obs-c-oracle/benches/port_comparison.rs","rust/obs-c-oracle/oracle/hotkey_key_translation.c","rust/obs-c-oracle/oracle/hotkey_translations.c","rust/obs-c-oracle/src/hotkey_translations.rs","rust/obs-hotkey/src/ffi/key_translation.rs","rust/obs-hotkey/src/ffi/mod.rs","rust/obs-hotkey/src/ffi/translations.rs","rust/obs-hotkey/src/key_translation.rs","rust/obs-hotkey/src/lib.rs","rust/obs-hotkey/tests/hotkey/key_translation.rs","rust/obs-hotkey/tests/hotkey/key_translation_parity.rs","rust/obs-hotkey/tests/hotkey/main.rs","rust/obs-hotkey/tests/hotkey/translations_parity.rs","test/cmocka/build/rust-static-support.json","test/cmocka/build/test-graph.json","test/cmocka/hotkey-key-translation-link-support.c","test/cmocka/hotkey-key-translation-record-support.c","test/cmocka/windows-keys-rust-stubs.c"],"head":"7804e244dab46057649d49af9022070931906b27","tools":{"orchestrator-python":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]","schema-dependencies":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]\n{'jsonschema': '4.26.0', 'json_source_map': '1.0.5'}","uv":"uv 0.13.5 (x86_64-unknown-linux-gnu)","xmllint":"xmllint: using libxml version 21504-GITv2.15.4\n compiled with: Threads Tree Output Push Reader Patterns Writer SAXv1 DTDValid HTML C14N Catalog XPath XPointer XInclude Iconv ICU ISO8859X Regexps Automata RelaxNG Schemas Schematron Modules Debug Zlib"},"tracked-digest":"21adc2c6ebf2fedddde2b0515db3aa93cfc60bc97ea65e94f4936999b08371d8","tree":"fe46a2769cc2d4063fa311ff22cee23cd2778bc2"}} --- ci/test_bench_libobs_stand_ins.py | 3 +- libobs/build/libobs.core+.h.c | 2 +- .../libobs.ported-hotkey-key-translation+.h.c | 5 + .../hotkey-key-translation.json | 5 + .../obs-hotkey-key_translation.txt | 5 + libobs/obs-hotkey-key-translation-fields.c.h | 22 ++ rust/README.md | 1 + rust/obs-build/tests/native.rs | 2 + ...tkey_key_translation_swap_is_registered.rs | 90 +++++ .../test_hotkey_key_translation_rust.json | 45 +++ rust/obs-c-oracle/benches/port_comparison.rs | 5 - .../oracle/hotkey_key_translation.c | 259 ++++++++++++++ .../obs-c-oracle/oracle/hotkey_translations.c | 6 +- rust/obs-c-oracle/src/hotkey_translations.rs | 2 +- rust/obs-hotkey/src/ffi/key_translation.rs | 69 ++++ rust/obs-hotkey/src/ffi/mod.rs | 1 + rust/obs-hotkey/src/ffi/translations.rs | 11 +- rust/obs-hotkey/src/key_translation.rs | 30 +- rust/obs-hotkey/src/lib.rs | 2 +- .../tests/hotkey/key_translation.rs | 4 +- .../tests/hotkey/key_translation_parity.rs | 319 ++++++++++++++++++ rust/obs-hotkey/tests/hotkey/main.rs | 57 ++-- .../tests/hotkey/translations_parity.rs | 6 +- test/cmocka/build/rust-static-support.json | 3 +- test/cmocka/build/test-graph.json | 38 +++ .../hotkey-key-translation-link-support.c | 2 + .../hotkey-key-translation-record-support.c | 7 + test/cmocka/windows-keys-rust-stubs.c | 7 - 28 files changed, 942 insertions(+), 66 deletions(-) create mode 100644 libobs/build/libobs.ported-hotkey-key-translation+.h.c create mode 100644 libobs/build/ported-source-sets/hotkey-key-translation.json create mode 100644 libobs/cmake/rust-hidden.d/obs-hotkey-key_translation.txt create mode 100644 libobs/obs-hotkey-key-translation-fields.c.h create mode 100644 rust/obs-build/tests/native/registration/canonical_hotkey_key_translation_swap_is_registered.rs create mode 100644 rust/obs-build/tests/native/registration/rust-static/cases/hotkey-control/test_hotkey_key_translation_rust.json create mode 100644 rust/obs-c-oracle/oracle/hotkey_key_translation.c create mode 100644 rust/obs-hotkey/src/ffi/key_translation.rs create mode 100644 rust/obs-hotkey/tests/hotkey/key_translation_parity.rs create mode 100644 test/cmocka/hotkey-key-translation-link-support.c create mode 100644 test/cmocka/hotkey-key-translation-record-support.c diff --git a/ci/test_bench_libobs_stand_ins.py b/ci/test_bench_libobs_stand_ins.py index 2793607381..901f47e958 100644 --- a/ci/test_bench_libobs_stand_ins.py +++ b/ci/test_bench_libobs_stand_ins.py @@ -34,6 +34,8 @@ # obs-encoder, which the bench links through obs-data. # The encoder name getter is absent too: #5253 exports it from obs-encoder; # the synthetic interleaver replaces only its private name seam. +# The key-name store is absent: #5321 exports it from obs-hotkey (hidden in +# libobs, defined by the workspace). SYMBOLS = ( "obs_encoder_group_num_started", "obs_encoder_interleave_info", @@ -59,7 +61,6 @@ "obs_hotkey_seam_unlock", "obs_hotkeys_mutex_lock", "obs_hotkeys_mutex_unlock", - "obs_hotkeys_store_key_translation", "obs_output_actual_start", "obs_output_actual_stop", "obs_output_begin_data_capture", diff --git a/libobs/build/libobs.core+.h.c b/libobs/build/libobs.core+.h.c index dfde3e21ee..c67302c51b 100644 --- a/libobs/build/libobs.core+.h.c +++ b/libobs/build/libobs.core+.h.c @@ -32,7 +32,7 @@ #include "libobs/obs-hotkey-identity-fields.c.h" #include "libobs/obs-hotkey-identity-setter-fields.c.h" #include "libobs/obs-hotkey-inject-entry-fields.c.h" -#include "libobs/obs-hotkey-key-translation.c.h" +#include "libobs/obs-hotkey-key-translation-fields.c.h" #include "libobs/obs-hotkey-object-fields.c.h" #include "libobs/obs-hotkey-owned-translations-fields.c.h" #include "libobs/obs-hotkey-pair-meta-setter-calls.c.h" diff --git a/libobs/build/libobs.ported-hotkey-key-translation+.h.c b/libobs/build/libobs.ported-hotkey-key-translation+.h.c new file mode 100644 index 0000000000..67d4379bc0 --- /dev/null +++ b/libobs/build/libobs.ported-hotkey-key-translation+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): original key-translation query and store for the C reference. */ + +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-hotkey-key-translation.c.h" diff --git a/libobs/build/ported-source-sets/hotkey-key-translation.json b/libobs/build/ported-source-sets/hotkey-key-translation.json new file mode 100644 index 0000000000..7dc63ed0ae --- /dev/null +++ b/libobs/build/ported-source-sets/hotkey-key-translation.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-hotkey-key-translation+.h.c" + ] +} diff --git a/libobs/cmake/rust-hidden.d/obs-hotkey-key_translation.txt b/libobs/cmake/rust-hidden.d/obs-hotkey-key_translation.txt new file mode 100644 index 0000000000..95d542b4c4 --- /dev/null +++ b/libobs/cmake/rust-hidden.d/obs-hotkey-key_translation.txt @@ -0,0 +1,5 @@ +# obs-hotkey-key-translation.c: the platform key name functions and +# obs_hotkeys_set_translations_s() call them inside libobs. Declared in +# obs-internal.h without EXPORT, so the shims stay hidden the same way. +obs_get_hotkey_translation +obs_hotkeys_store_key_translation diff --git a/libobs/obs-hotkey-key-translation-fields.c.h b/libobs/obs-hotkey-key-translation-fields.c.h new file mode 100644 index 0000000000..47a05523c9 --- /dev/null +++ b/libobs/obs-hotkey-key-translation-fields.c.h @@ -0,0 +1,22 @@ +#include "libobs/build/libobs.pch.h" + +/* Private adapters for the Rust key-translation query and store. The name + * array, obs->hotkeys.translations[], and its bmalloc/bfree ownership stay in + * C. As in the original, no lock is taken and the key is not range-checked. */ +char **obs_hotkey_key_translation_slot(obs_key_t key); +char **obs_hotkey_key_translation_slot(obs_key_t key) +{ + return &obs->hotkeys.translations[key]; +} + +void obs_hotkey_key_translation_free(char *translation); +void obs_hotkey_key_translation_free(char *translation) +{ + bfree(translation); +} + +char *obs_hotkey_key_translation_dup(const char *translation); +char *obs_hotkey_key_translation_dup(const char *translation) +{ + return bstrdup(translation); +} diff --git a/rust/README.md b/rust/README.md index c9aaeed620..f50a4b52ed 100644 --- a/rust/README.md +++ b/rust/README.md @@ -129,6 +129,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-hotkey-background-query.c.h` | `obs-hotkey::background_query` | Swapped in hybrid libobs (#3969). The public combination query preserves the native short circuit, identifier lookup and release. Actual-library native fallback characterization, real-header combination layout, callback-based differential parity and isolated allocation accounting. No exclusions or intentional differences. | | `libobs/obs-hotkey-background-trigger.c.h` | `obs-hotkey::background_trigger` | Owned background trigger retrieval under the existing hotkey mutex. Preserves exact combo/wake_data, callback-before-unlock, rejected-output cleanup and exact allocation transfer, including allocated empty and successful NULL results. Unchanged C characterization, safe-core assertions, real-header layouts and differential ownership/dispatch parity. No intentional differences. | | `libobs/obs-hotkey-combination-background-id.c.h` | `obs-hotkey::combination_background_id` | Swapped in hybrid `libobs` (group `libobs.ported-hotkey-combination-background-id` keeps the original for the C reference). Safe Rust takes the existing hotkey mutex, captures the backend's `shortcut_id` callback, releases the lock and only then calls the saved callback once with the combination by value. A failed lock returns NULL with no field read; a missing callback or a false result frees the partial dstr and returns NULL; a true result transfers `id.array` unchanged, NULL or an allocated empty string included. The mutex, the callback slot and `dstr_free` stay in C behind private adapters (`obs-hotkey-combination-background-id-fields.c.h`), so the caller's bfree always matches the callback's allocator. Tier 1 mirrors every assertion of the unchanged `test_hotkey_combination_background_id`; Tier 3 runs the original and the shim on one recording fixture (trace, returned pointer and text) with real-header `dstr`/combination layout checks and mutants for a call under the lock, a read after unlock, a leaked partial id, a dropped result, a read after a failed lock and an altered combination. `background_query_parity` now drives this real getter instead of a same-named fake. No intentional differences; no network protocol (Tier 4 inapplicable). | +| `libobs/obs-hotkey-key-translation.c.h` | `obs-hotkey::key_translation` | Swapped in hybrid `libobs` (group `libobs.ported-hotkey-key-translation` keeps the original for the C reference). The hidden key name store `obs_hotkeys_store_key_translation` and its query `obs_get_hotkey_translation` (both `obs-internal.h`, listed in `rust-hidden.d`). The query returns NULL for `OBS_KEY_NONE` without touching the core, else the stored pointer itself (read again to return it, as C's ternary) or the caller's default; the store frees the old name (NULL too), clears the slot and stores a `bstrdup` copy. No lock and no key range check, as in C. The `obs->hotkeys.translations[]` array and `bfree`/`bstrdup` stay in C behind private adapters (`obs-hotkey-key-translation-fields.c.h`), also a shared Rust-static support member. The unchanged `test_hotkey_key_translation` keeps testing the C source; its `HOTKEY_KEY_TRANSLATION_EXTERNAL` twin `test_hotkey_key_translation_rust` runs the same assertions on the Rust symbols, with the real adapters bound to the test's own core. Tier 1 mirrors every assertion; Tier 3 runs the original and the shims on one recording core (free/copy trace, read count, returned pointer, stored slot, allocation balance, other keys) with mutants. The translations shim now calls this store directly, and its parity records the store calls through the oracle core. No intentional differences; no network protocol (Tier 4 inapplicable). | | `libobs/obs-hotkey-binding-getters.c.h` | `obs-hotkey::binding_getters` | Three public binding getters: exact stored combination, independent binding ID and pointer identity. No intentional differences. Null stored hotkeys are preserved; null binding inputs remain outside the C contract. Full real-header binding/combination layouts and differential parity, with actual-library C characterization. | | `libobs/obs-service-module-lookup.c.h` | `obs-output::service_module_lookup` | #3839: enabled/disabled list selection, next link, service count/id and load state. C supplies both global roots without selection; Rust reads the unchanged private module layout, checked field by field against `obs-internal.h`. No intended differences on defined C inputs; NULL modules and out-of-range id indexes are excluded as C UB. | | `libobs/util/bitstream.c` | `obs-util::bitstream` | C ABI keeps the `uint8_t pos` wrap past byte 255; the safe API does not wrap | diff --git a/rust/obs-build/tests/native.rs b/rust/obs-build/tests/native.rs index 8d35a7d60d..6b2afa3050 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -359,6 +359,8 @@ mod canonical_hotkey_backtab_is_registered; mod canonical_hotkey_combination_background_id_swap_is_registered; #[path = "native/registration/canonical_hotkey_identity_getters_is_registered.rs"] mod canonical_hotkey_identity_getters_is_registered; +#[path = "native/registration/canonical_hotkey_key_translation_swap_is_registered.rs"] +mod canonical_hotkey_key_translation_swap_is_registered; #[path = "native/registration/canonical_hotkey_mnemonic_is_registered.rs"] mod canonical_hotkey_mnemonic_is_registered; #[path = "native/registration/canonical_hotkey_pair_latch_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_hotkey_key_translation_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_hotkey_key_translation_swap_is_registered.rs new file mode 100644 index 0000000000..04d9bc66a6 --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_hotkey_key_translation_swap_is_registered.rs @@ -0,0 +1,90 @@ +use super::*; + +#[test] +fn canonical_hotkey_key_translation_swap_is_registered() { + use obs_build::validation::graph::{Graph, Source}; + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut graph = Graph::load(&root.join("test/cmocka/build/test-graph.json")).unwrap(); + let c_test = "test_hotkey_key_translation"; + let rust_test = "test_hotkey_key_translation_rust"; + graph + .targets + .retain(|key, _| key == c_test || key == rust_test); + graph + .tests + .retain(|key, _| key == c_test || key == rust_test); + let test_source = "test/cmocka/test_hotkey_key_translation.c"; + let record = "test/cmocka/hotkey-key-translation-record-support.c"; + for os in ["OS_LINUX", "OS_MACOS", "OS_WINDOWS"] { + for available in [false, true] { + let facts = [ + (os.into(), true), + ("HAVE_LIBOBS_RUST_STATIC".into(), available), + ] + .into(); + let selected = graph.select(&facts).unwrap(); + // The unchanged characterization keeps testing the original C source. + assert!( + matches!(selected.targets[c_test].sources.as_slice(), [Source::Path(path)] + if path == test_source) + ); + assert_eq!(selected.tests[c_test].target, c_test); + assert_eq!(selected.targets.contains_key(rust_test), available); + if !available { + continue; + } + // Its external seam reaches the Rust symbols through the real + // adapters, bound to the test's own core in one unity group. + let target = &selected.targets[rust_test]; + assert!(matches!(target.sources.as_slice(), + [Source::Path(a), Source::Path(b)] if a == test_source && b == record)); + assert_eq!( + target.unity_groups["key_translation"], + [test_source, record] + ); + assert_eq!(target.definitions, ["HOTKEY_KEY_TRANSLATION_EXTERNAL"]); + assert_eq!(selected.tests[rust_test].target, rust_test); + } + } + let record_text = fs::read_to_string(root.join(record)).unwrap(); + let fields = "#include \"libobs/obs-hotkey-key-translation-fields.c.h\""; + assert!(record_text.contains("#define obs record_core()")); + assert!(record_text.contains(fields)); + let test_text = fs::read_to_string(root.join(test_source)).unwrap(); + assert!(test_text.contains("#ifndef HOTKEY_KEY_TRANSLATION_EXTERNAL")); + let ported = fs::read_to_string( + root.join("libobs/build/ported-source-sets/hotkey-key-translation.json"), + ) + .unwrap(); + assert!(ported.contains("build/libobs.ported-hotkey-key-translation+.h.c")); + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-hotkey-key-translation+.h.c")) + .unwrap(); + let original = "#include \"libobs/obs-hotkey-key-translation.c.h\""; + assert!(group.contains(original)); + let hybrid = fs::read_to_string(root.join("libobs/build/libobs.core+.h.c")).unwrap(); + assert!(!hybrid.contains(original)); + // The C-owned name array and its allocator stay in the production group. + assert!(hybrid.contains(fields)); + // Standalone Rust-static consumers get the same real adapters. + let support = + fs::read_to_string(root.join("test/cmocka/build/rust-static-support.json")).unwrap(); + assert!(support.contains("\"test/cmocka/hotkey-key-translation-link-support.c\"")); + let link = + fs::read_to_string(root.join("test/cmocka/hotkey-key-translation-link-support.c")).unwrap(); + assert!(link.contains(fields)); + let hidden = + fs::read_to_string(root.join("libobs/cmake/rust-hidden.d/obs-hotkey-key_translation.txt")) + .unwrap(); + let names: Vec<_> = hidden + .lines() + .filter(|line| !line.starts_with('#') && !line.trim().is_empty()) + .collect(); + assert_eq!( + names, + [ + "obs_get_hotkey_translation", + "obs_hotkeys_store_key_translation" + ] + ); +} diff --git a/rust/obs-build/tests/native/registration/rust-static/cases/hotkey-control/test_hotkey_key_translation_rust.json b/rust/obs-build/tests/native/registration/rust-static/cases/hotkey-control/test_hotkey_key_translation_rust.json new file mode 100644 index 0000000000..a8a0431c30 --- /dev/null +++ b/rust/obs-build/tests/native/registration/rust-static/cases/hotkey-control/test_hotkey_key_translation_rust.json @@ -0,0 +1,45 @@ +{ + "schema": 1, + "targets": { + "test_hotkey_key_translation_rust": { + "sources": [ + "test/cmocka/test_hotkey_key_translation.c", + "test/cmocka/hotkey-key-translation-record-support.c" + ], + "pch": "libobs/build/libobs.pch.h", + "unity_groups": { + "key_translation": [ + "test/cmocka/test_hotkey_key_translation.c", + "test/cmocka/hotkey-key-translation-record-support.c" + ] + }, + "definitions": [ + "HOTKEY_KEY_TRANSLATION_EXTERNAL" + ], + "libraries": [ + "libobs_rust-static", + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ], + "header_libraries": [ + "SIMDe::SIMDe" + ], + "requires": "HAVE_LIBOBS_RUST_STATIC" + } + }, + "tests": { + "test_hotkey_key_translation_rust": { + "target": "test_hotkey_key_translation_rust", + "command": [ + "${target}" + ], + "requires": "HAVE_LIBOBS_RUST_STATIC" + } + } +} diff --git a/rust/obs-c-oracle/benches/port_comparison.rs b/rust/obs-c-oracle/benches/port_comparison.rs index b893a4ca4d..5c88026b8f 100644 --- a/rust/obs-c-oracle/benches/port_comparison.rs +++ b/rust/obs-c-oracle/benches/port_comparison.rs @@ -273,11 +273,6 @@ mod libobs_stand_ins { called("obs_hotkeys_mutex_unlock") } - #[unsafe(no_mangle)] - pub extern "C" fn obs_hotkeys_store_key_translation() -> ! { - called("obs_hotkeys_store_key_translation") - } - #[unsafe(no_mangle)] pub extern "C" fn obs_output_interleave_first_audio_encoder_index() -> ! { called("obs_output_interleave_first_audio_encoder_index") diff --git a/rust/obs-c-oracle/oracle/hotkey_key_translation.c b/rust/obs-c-oracle/oracle/hotkey_key_translation.c new file mode 100644 index 0000000000..fe214ceaff --- /dev/null +++ b/rust/obs-c-oracle/oracle/hotkey_key_translation.c @@ -0,0 +1,259 @@ +/* Original key-translation query and store and the real-header adapters of + * obs-hotkey-key-translation-fields.c.h on one recording fixture core. The + * probes run the original and a candidate through the same core reads, bfree + * and bstrdup, and report every difference instead of aborting, so mutants + * are observable. Under cargo test these adapters are the only definitions of + * their real names, so the Rust shims and anything calling them (the + * translations shim, through the store) reach this fixture. */ +#include "libobs/build/libobs.pch.h" +#include +#include + +typedef const char *(*kt_query_fn)(obs_key_t key, const char *def); +typedef void (*kt_store_fn)(obs_key_t key, const char *translation); +/* Called with NULL when a store frees the old name, then with the string a + * store copies. */ +typedef void (*kt_hook_fn)(int key, const char *translation); + +static _Thread_local struct obs_core kt_core; +static _Thread_local bool kt_forbid; +static _Thread_local int kt_key, kt_last_key; +static _Thread_local const char *kt_arg; +static _Thread_local long kt_live; +static _Thread_local unsigned kt_reads; +static _Thread_local char kt_events[32]; +static _Thread_local size_t kt_event_count; +static _Thread_local kt_hook_fn kt_hook; + +static void kt_event(char value) +{ + if (kt_event_count + 1 < sizeof(kt_events)) { + kt_events[kt_event_count++] = value; + kt_events[kt_event_count] = '\0'; + } +} + +/* Reads are counted, not traced: C leaves the order of a slot read and the + * bstrdup on the right of the same assignment unspecified. 'X' marks a read + * of the core for OBS_KEY_NONE. */ +static struct obs_core *kt_read_core(void) +{ + if (kt_forbid) + kt_event('X'); + kt_reads++; + return &kt_core; +} + +/* 'F' frees a name, 'f' frees NULL; 'P' marks a freed pointer that was not + * the key's current slot. */ +static void kt_free(void *ptr) +{ + if (kt_hook) { + kt_hook(kt_last_key, NULL); + } else if (ptr != kt_core.hotkeys.translations[kt_key]) { + kt_event('P'); + } + kt_event(ptr ? 'F' : 'f'); + if (ptr) + kt_live--; + bfree(ptr); +} + +/* 'D' copies a name; 'A' marks a copy of anything but the caller's string. */ +static char *kt_dup(const char *str) +{ + if (kt_hook) { + kt_hook(kt_last_key, str); + } else if (str != kt_arg) { + kt_event('A'); + } + kt_event('D'); + char *copy = bstrdup(str); + if (copy) + kt_live++; + return copy; +} + +const char *oracle_obs_get_hotkey_translation(obs_key_t key, const char *def); +void oracle_obs_hotkeys_store_key_translation(obs_key_t key, const char *translation); +char **oracle_kt_fields_slot(obs_key_t key); + +#define obs kt_read_core() +#define bfree kt_free +#define bstrdup kt_dup +#define obs_get_hotkey_translation oracle_obs_get_hotkey_translation +#define obs_hotkeys_store_key_translation oracle_obs_hotkeys_store_key_translation +#include "libobs/obs-hotkey-key-translation.c.h" +#undef obs_hotkeys_store_key_translation +#undef obs_get_hotkey_translation +#define obs_hotkey_key_translation_slot oracle_kt_fields_slot +#include "hotkey_key_translation_fields.inc" +#undef obs_hotkey_key_translation_slot +#undef bstrdup +#undef bfree +#undef obs + +/* The real-named slot adapter: the fields adapter, remembering the key for + * the store hook. */ +char **obs_hotkey_key_translation_slot(obs_key_t key); +char **obs_hotkey_key_translation_slot(obs_key_t key) +{ + kt_last_key = key; + return oracle_kt_fields_slot(key); +} + +static void kt_clear(void) +{ + for (size_t i = 0; i < OBS_KEY_LAST_VALUE; i++) { + bfree(kt_core.hotkeys.translations[i]); + kt_core.hotkeys.translations[i] = NULL; + } +} + +static void kt_arm(int key, const char *initial, const char *arg, bool forbid) +{ + kt_hook = NULL; + kt_clear(); + if (initial) + kt_core.hotkeys.translations[key] = bstrdup(initial); + kt_key = key; + kt_last_key = key; + kt_arg = arg; + kt_live = 0; + kt_reads = 0; + kt_forbid = forbid; + kt_event_count = 0; + kt_events[0] = '\0'; +} + +/* Every slot but `key` is still NULL. */ +static bool kt_others_clear(int key) +{ + for (int i = 0; i < OBS_KEY_LAST_VALUE; i++) { + if (i != key && kt_core.hotkeys.translations[i]) + return false; + } + return true; +} + +/* Free every slot and route each later store to `hook`, or stop with NULL. */ +void oracle_hotkey_key_translation_record(kt_hook_fn hook); +void oracle_hotkey_key_translation_record(kt_hook_fn hook) +{ + kt_hook = NULL; + kt_clear(); + kt_hook = hook; +} + +struct kt_query_result { + char events[32]; + unsigned reads; + int kind; /* 0 NULL, 1 the default, 2 the stored slot, 3 anything else */ + bool state; +}; + +static void kt_run_query(kt_query_fn query, int key, const char *stored, const char *def, struct kt_query_result *out) +{ + kt_arm(key, stored, NULL, key == OBS_KEY_NONE); + char *before = kt_core.hotkeys.translations[key]; + const char *result = query((obs_key_t)key, def); + memset(out, 0, sizeof(*out)); + memcpy(out->events, kt_events, sizeof(out->events)); + out->reads = kt_reads; + out->kind = !result ? 0 : result == def ? 1 : result == before ? 2 : 3; + out->state = kt_core.hotkeys.translations[key] == before && kt_live == 0 && kt_others_clear(key); + kt_clear(); +} + +/* Bits of the result: 1 trace or read count, 2 returned pointer, 4 slot or + * allocations changed. */ +unsigned oracle_hotkey_key_translation_query_probe(int key, const char *stored, const char *def, kt_query_fn candidate); +unsigned oracle_hotkey_key_translation_query_probe(int key, const char *stored, const char *def, kt_query_fn candidate) +{ + struct kt_query_result original, other; + kt_run_query(oracle_obs_get_hotkey_translation, key, stored, def, &original); + kt_run_query(candidate, key, stored, def, &other); + unsigned diff = 0; + if (strcmp(original.events, other.events) != 0 || original.reads != other.reads || strchr(other.events, 'X')) + diff |= 1; + if (original.kind != other.kind) + diff |= 2; + if (!original.state || !other.state) + diff |= 4; + return diff; +} + +struct kt_store_result { + char events[32]; + unsigned reads; + long live; + bool null_slot, same_text, own_copy, others_clear; +}; + +static void kt_run_store(kt_store_fn store, int key, const char *initial, const char *arg, struct kt_store_result *out) +{ + kt_arm(key, initial, arg, false); + store((obs_key_t)key, arg); + const char *slot = kt_core.hotkeys.translations[key]; + memset(out, 0, sizeof(*out)); + memcpy(out->events, kt_events, sizeof(out->events)); + out->reads = kt_reads; + out->live = kt_live; + out->null_slot = !slot; + out->same_text = slot && arg && strcmp(slot, arg) == 0; + out->own_copy = !slot || slot != arg; + out->others_clear = kt_others_clear(key); + kt_clear(); +} + +/* Bits of the result: 1 trace or read count, 2 stored slot, 4 allocation + * balance or another key touched. */ +unsigned oracle_hotkey_key_translation_store_probe(int key, const char *initial, const char *arg, + kt_store_fn candidate); +unsigned oracle_hotkey_key_translation_store_probe(int key, const char *initial, const char *arg, kt_store_fn candidate) +{ + struct kt_store_result original, other; + kt_run_store(oracle_obs_hotkeys_store_key_translation, key, initial, arg, &original); + kt_run_store(candidate, key, initial, arg, &other); + unsigned diff = 0; + if (strcmp(original.events, other.events) != 0 || original.reads != other.reads || strpbrk(other.events, "PA")) + diff |= 1; + if (original.null_slot != other.null_slot || original.same_text != other.same_text || !other.own_copy) + diff |= 2; + long expected = (arg ? 1 : 0) - (initial ? 1 : 0); + if (original.live != other.live || other.live != expected || !other.others_clear) + diff |= 4; + return diff; +} + +/* One store's or query's trace and read count, for exact expectations. */ +void oracle_hotkey_key_translation_trace(bool query, int key, const char *initial, const char *arg, char *out, + size_t size, unsigned *reads); +void oracle_hotkey_key_translation_trace(bool query, int key, const char *initial, const char *arg, char *out, + size_t size, unsigned *reads) +{ + if (query) { + struct kt_query_result run; + kt_run_query(oracle_obs_get_hotkey_translation, key, initial, arg, &run); + strncpy(out, run.events, size - 1); + *reads = run.reads; + } else { + struct kt_store_result run; + kt_run_store(oracle_obs_hotkeys_store_key_translation, key, initial, arg, &run); + strncpy(out, run.events, size - 1); + *reads = run.reads; + } + out[size - 1] = '\0'; +} + +void oracle_hotkey_key_translation_layout(size_t *out); +void oracle_hotkey_key_translation_layout(size_t *out) +{ + out[0] = OBS_KEY_LAST_VALUE; + out[1] = sizeof(kt_core.hotkeys.translations); + out[2] = sizeof(kt_core.hotkeys.translations[0]); + out[3] = sizeof(obs_key_t); + out[4] = OBS_KEY_NONE; + out[5] = OBS_KEY_A; + out[6] = OBS_KEY_B; +} diff --git a/rust/obs-c-oracle/oracle/hotkey_translations.c b/rust/obs-c-oracle/oracle/hotkey_translations.c index 20b997fd99..9924b52247 100644 --- a/rust/obs-c-oracle/oracle/hotkey_translations.c +++ b/rust/obs-c-oracle/oracle/hotkey_translations.c @@ -3,9 +3,9 @@ * can link next to the Rust shim. Its dstr calls are renamed to the C dstr * oracle (oracle/dstr.c, the same renames), so the expansion runs on the * original util/dstr.c, not on its Rust port. The store it calls, - * obs_hotkeys_store_key_translation, keeps its name: under cargo test the - * test binary defines it and records each call, for this oracle and the - * shim alike. */ + * obs_hotkeys_store_key_translation, keeps its name: under cargo test it is + * the Rust store, whose adapters run on the key-translation oracle's core + * and report each call, for this oracle and the shim alike. */ #ifndef _WIN32 #define _GNU_SOURCE #endif diff --git a/rust/obs-c-oracle/src/hotkey_translations.rs b/rust/obs-c-oracle/src/hotkey_translations.rs index e840a696f6..de21e1a16a 100644 --- a/rust/obs-c-oracle/src/hotkey_translations.rs +++ b/rust/obs-c-oracle/src/hotkey_translations.rs @@ -4,7 +4,7 @@ //! The struct is passed as an untyped pointer: callers pass the shim's //! `#[repr(C)]` struct, whose layout `oracle_hotkey_translations_layout` //! checks. The store, `obs_hotkeys_store_key_translation`, is the caller's: -//! the test binary defines it. +//! the Rust store of obs-hotkey, on oracle/hotkey_key_translation.c's core. use core::ffi::c_void; diff --git a/rust/obs-hotkey/src/ffi/key_translation.rs b/rust/obs-hotkey/src/ffi/key_translation.rs new file mode 100644 index 0000000000..e06b4f8c7a --- /dev/null +++ b/rust/obs-hotkey/src/ffi/key_translation.rs @@ -0,0 +1,69 @@ +//! The key name store and its query over C-owned state: +//! `obs->hotkeys.translations[]` and libobs's allocator, behind the private +//! adapters of `libobs/obs-hotkey-key-translation-fields.c.h`. +//! +//! Both functions are declared in `obs-internal.h` without `EXPORT`, so they +//! stay hidden (`rust-hidden.d/obs-hotkey-key_translation.txt`). As in C, +//! no lock is taken and the key is not range-checked: the slot adapter +//! indexes the array exactly as the original did. `obs_key_t` is a C enum, +//! passed as `int`. +use core::ffi::{c_char, c_int}; +use core::ptr::{NonNull, null, null_mut}; + +unsafe extern "C" { + fn obs_hotkey_key_translation_slot(key: c_int) -> *mut *mut c_char; + fn obs_hotkey_key_translation_free(translation: *mut c_char); + fn obs_hotkey_key_translation_dup(translation: *const c_char) -> *mut c_char; +} + +struct Core; +impl crate::key_translation::KeyTranslations for Core { + type Text = NonNull; + fn get(&mut self, key: i32) -> Option> { + // SAFETY: as for the C function, the core is live and `key` indexes + // its translations array; the adapter reads `obs` once. + NonNull::new(unsafe { *obs_hotkey_key_translation_slot(key) }) + } + fn set(&mut self, key: i32, value: Option>) { + // SAFETY: as in `get`; the slot is C-owned and nothing else holds it. + unsafe { + *obs_hotkey_key_translation_slot(key) = value.map_or(null_mut(), NonNull::as_ptr) + }; + } + fn release(&mut self, value: Option>) { + // SAFETY: the slot held NULL or a bstrdup copy, freed exactly once here. + unsafe { obs_hotkey_key_translation_free(value.map_or(null_mut(), NonNull::as_ptr)) }; + } + fn duplicate(&mut self, value: NonNull) -> Option> { + // SAFETY: `value` is the caller's NUL-terminated string; the copy is + // bmalloc-owned and stored as bstrdup returned it. + NonNull::new(unsafe { obs_hotkey_key_translation_dup(value.as_ptr()) }) + } +} + +/// The stored name of `key` (borrowed from the store), else `def`; +/// `OBS_KEY_NONE` returns NULL without touching the core. +/// +/// # Safety +/// As for the C function: unless `key` is `OBS_KEY_NONE`, the core is live +/// and `key` is a valid `obs_key_t` below `OBS_KEY_LAST_VALUE`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_hotkey_translation( + key: c_int, + def: *const c_char, +) -> *const c_char { + crate::key_translation::translation(&mut Core, key, NonNull::new(def.cast_mut())) + .map_or(null(), |text| text.as_ptr().cast_const()) +} + +/// Replace the stored name of `key` with a bstrdup copy of `translation`, +/// or clear it for NULL, freeing the old name with bfree. +/// +/// # Safety +/// As for the C function: the core is live, `key` is a valid `obs_key_t` +/// below `OBS_KEY_LAST_VALUE`, and `translation` is NULL or a NUL-terminated +/// string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_hotkeys_store_key_translation(key: c_int, translation: *const c_char) { + crate::key_translation::store(&mut Core, key, NonNull::new(translation.cast_mut())); +} diff --git a/rust/obs-hotkey/src/ffi/mod.rs b/rust/obs-hotkey/src/ffi/mod.rs index cc581f56f7..00c82f4975 100644 --- a/rust/obs-hotkey/src/ffi/mod.rs +++ b/rust/obs-hotkey/src/ffi/mod.rs @@ -19,6 +19,7 @@ pub mod identity_setters; pub mod inject_entry; #[cfg(not(target_os = "macos"))] pub mod key_combination; +pub mod key_translation; pub mod nix_hotkey_state; pub mod nix_wayland_key_names; pub mod nix_wayland_keys; diff --git a/rust/obs-hotkey/src/ffi/translations.rs b/rust/obs-hotkey/src/ffi/translations.rs index 44480d4a14..271bd24d59 100644 --- a/rust/obs-hotkey/src/ffi/translations.rs +++ b/rust/obs-hotkey/src/ffi/translations.rs @@ -10,8 +10,8 @@ //! tails, and a larger `size` reads only the struct. A `NULL` struct //! returns. The safe core (`translations::for_each_store`) then gives each //! name, and the shim hands it to libobs's hidden store, -//! `obs_hotkeys_store_key_translation()` (`obs-internal.h`, still C in -//! `obs-hotkey.c.h`), which `bstrdup`s it. A named key's string is passed +//! `obs_hotkeys_store_key_translation()` (`obs-internal.h`, ported in +//! [`super::key_translation`]), which `bstrdup`s it. A named key's string is passed //! on as the caller's pointer, as the C does; an expanded name lives until //! the store call returns. //! @@ -20,14 +20,11 @@ //! //! No intentional differences from C. -use std::ffi::{CStr, c_char, c_int}; +use std::ffi::{CStr, c_char}; +use super::key_translation::obs_hotkeys_store_key_translation; use crate::translations::{self as core, Keypad, MEMBER_COUNT, Translations}; -unsafe extern "C" { - fn obs_hotkeys_store_key_translation(key: c_int, translation: *const c_char); -} - /// The keypad members this host applies (`#ifdef __APPLE__` in the C). #[cfg(target_os = "macos")] pub const KEYPAD: Keypad = Keypad::Apple; diff --git a/rust/obs-hotkey/src/key_translation.rs b/rust/obs-hotkey/src/key_translation.rs index ac5540fa84..77cefa83a7 100644 --- a/rust/obs-hotkey/src/key_translation.rs +++ b/rust/obs-hotkey/src/key_translation.rs @@ -18,26 +18,36 @@ pub trait KeyTranslations { fn set(&mut self, key: i32, value: Option); /// Release a stored name; `None` is released too, as `bfree(NULL)`. fn release(&mut self, value: Option); - /// An owned copy of `value` in the table's allocator. - fn duplicate(&mut self, value: Self::Text) -> Self::Text; + /// An owned copy of `value` in the table's allocator, stored as returned. + fn duplicate(&mut self, value: Self::Text) -> Option; } /// The stored name of `key`, else `default`. `OBS_KEY_NONE` returns `None` -/// without touching the table. -#[expect(clippy::todo, reason = "RED stub")] +/// without touching the table. As C's `slot ? slot : def`, a stored name is +/// read again to return it. pub fn translation( table: &mut T, key: i32, default: Option, ) -> Option { - let _ = (table, key, default); - todo!() + if key == OBS_KEY_NONE { + return None; + } + match table.get(key) { + Some(_) => table.get(key), + None => default, + } } /// Replace the stored name of `key` with a copy of `translation`, or clear -/// it for `None`. The old name is released first. -#[expect(clippy::todo, reason = "RED stub")] +/// it for `None`. The old name is released first, then the slot cleared, +/// then the copy stored. pub fn store(table: &mut T, key: i32, translation: Option) { - let _ = (table, key, translation); - todo!() + let old = table.get(key); + table.release(old); + table.set(key, None); + if let Some(translation) = translation { + let copy = table.duplicate(translation); + table.set(key, copy); + } } diff --git a/rust/obs-hotkey/src/lib.rs b/rust/obs-hotkey/src/lib.rs index 7beffbedff..c97bb0c9ac 100644 --- a/rust/obs-hotkey/src/lib.rs +++ b/rust/obs-hotkey/src/lib.rs @@ -53,8 +53,8 @@ pub mod identity_getters; pub mod identity_setters; pub mod inject_entry; pub mod key_combination; -pub mod key_translation; mod key_route; +pub mod key_translation; pub mod name_map; pub mod nix_hotkey_state; pub mod nix_wayland_key_names; diff --git a/rust/obs-hotkey/tests/hotkey/key_translation.rs b/rust/obs-hotkey/tests/hotkey/key_translation.rs index 1f8beb656b..fd114ad25c 100644 --- a/rust/obs-hotkey/tests/hotkey/key_translation.rs +++ b/rust/obs-hotkey/tests/hotkey/key_translation.rs @@ -86,12 +86,12 @@ impl KeyTranslations for Table { self.arena[handle] = None; } } - fn duplicate(&mut self, value: Handle) -> Handle { + fn duplicate(&mut self, value: Handle) -> Option { let copy = self.text(value).to_vec(); self.arena.push(Some(copy)); let handle = self.arena.len() - 1; self.owned.push(handle); - handle + Some(handle) } } diff --git a/rust/obs-hotkey/tests/hotkey/key_translation_parity.rs b/rust/obs-hotkey/tests/hotkey/key_translation_parity.rs new file mode 100644 index 0000000000..b074e415ab --- /dev/null +++ b/rust/obs-hotkey/tests/hotkey/key_translation_parity.rs @@ -0,0 +1,319 @@ +//! Tier 3: the original extracted `obs_get_hotkey_translation` and +//! `obs_hotkeys_store_key_translation` versus the shims on one recording +//! fixture core (oracle/hotkey_key_translation.c), through the real-named +//! slot, bfree and bstrdup adapters. Compared: the free/copy trace and the +//! number of core reads, the returned pointer (NULL, the default, the stored +//! slot), the stored slot (NULL, its text, never the caller's pointer), the +//! allocation balance and every other key left untouched. +//! +//! Excluded: a key outside `0..OBS_KEY_LAST_VALUE` (an out-of-bounds index in +//! both, unchecked as in C) and a live core missing for any key but +//! `OBS_KEY_NONE` (a NULL dereference in both). No intentional differences. +//! Mutants show the probes catch each broken contract. +use core::ffi::{CStr, c_char, c_int}; +use core::mem::size_of; +use core::ptr::{NonNull, null, null_mut}; +use obs_hotkey::ffi::key_translation::{ + obs_get_hotkey_translation, obs_hotkeys_store_key_translation, +}; +use obs_hotkey::key_translation::{KeyTranslations, OBS_KEY_NONE, store, translation}; +use proptest::prelude::*; +use std::ffi::CString; + +type Query = unsafe extern "C" fn(c_int, *const c_char) -> *const c_char; +type Store = unsafe extern "C" fn(c_int, *const c_char); +unsafe extern "C" { + fn oracle_hotkey_key_translation_query_probe( + key: c_int, + stored: *const c_char, + def: *const c_char, + candidate: Query, + ) -> u32; + fn oracle_hotkey_key_translation_store_probe( + key: c_int, + initial: *const c_char, + arg: *const c_char, + candidate: Store, + ) -> u32; + fn oracle_hotkey_key_translation_trace( + query: bool, + key: c_int, + initial: *const c_char, + arg: *const c_char, + out: *mut c_char, + size: usize, + reads: *mut u32, + ); + fn oracle_hotkey_key_translation_layout(out: *mut usize); + fn obs_hotkey_key_translation_slot(key: c_int) -> *mut *mut c_char; + fn obs_hotkey_key_translation_free(translation: *mut c_char); + fn obs_hotkey_key_translation_dup(translation: *const c_char) -> *mut c_char; +} + +fn layout() -> [usize; 7] { + let mut out = [0; 7]; + // SAFETY: the oracle writes seven size_t measurements from the real headers. + unsafe { oracle_hotkey_key_translation_layout(out.as_mut_ptr()) }; + out +} + +fn last_key() -> c_int { + c_int::try_from(layout()[0]).unwrap() +} + +fn text(value: &Option) -> *const c_char { + value.as_ref().map_or(null(), |s| s.as_ptr()) +} + +fn query_probe(key: c_int, stored: &Option, def: &Option, q: Query) -> u32 { + // SAFETY: key is below OBS_KEY_LAST_VALUE; the strings outlive the call + // and the oracle owns the fixture core every adapter reaches. + unsafe { oracle_hotkey_key_translation_query_probe(key, text(stored), text(def), q) } +} + +fn store_probe(key: c_int, initial: &Option, arg: &Option, s: Store) -> u32 { + // SAFETY: as in `query_probe`. + unsafe { oracle_hotkey_key_translation_store_probe(key, text(initial), text(arg), s) } +} + +fn check(key: c_int, stored: &Option, arg: &Option) { + assert_eq!( + query_probe(key, stored, arg, obs_get_hotkey_translation), + 0, + "query key={key} stored={stored:?} def={arg:?}" + ); + assert_eq!( + store_probe(key, stored, arg, obs_hotkeys_store_key_translation), + 0, + "store key={key} initial={stored:?} arg={arg:?}" + ); +} + +fn trace(query: bool, key: c_int, initial: Option<&str>, arg: Option<&str>) -> (String, u32) { + let initial = initial.map(|s| CString::new(s).unwrap()); + let arg = arg.map(|s| CString::new(s).unwrap()); + let mut out = [0 as c_char; 32]; + let mut reads = 0; + // SAFETY: the oracle writes a terminated trace of at most 31 bytes. + unsafe { + oracle_hotkey_key_translation_trace( + query, + key, + text(&initial), + text(&arg), + out.as_mut_ptr(), + out.len(), + &mut reads, + ); + ( + CStr::from_ptr(out.as_ptr()).to_str().unwrap().to_owned(), + reads, + ) + } +} + +fn some(s: &str) -> Option { + Some(CString::new(s).unwrap()) +} + +#[test] +fn real_header_layout() { + let [last, array, slot, key, none, a, b] = layout(); + assert_eq!(array, last * size_of::<*mut c_char>()); + assert_eq!(slot, size_of::<*mut c_char>()); + assert_eq!(key, size_of::()); + assert_eq!(c_int::try_from(none).unwrap(), OBS_KEY_NONE); + assert!(a != b && a != none && b != none && a < last && b < last); +} + +#[test] +fn original_traces_match_the_characterization() { + let [_, _, _, _, _, a, _] = layout(); + let a = c_int::try_from(a).unwrap(); + // Query: no core access for OBS_KEY_NONE; one read when unset; a stored + // name is read again to return it. + assert_eq!( + trace(true, OBS_KEY_NONE, None, Some("default")), + (String::new(), 0) + ); + assert_eq!(trace(true, a, None, Some("default")), (String::new(), 1)); + assert_eq!(trace(true, a, Some("stored"), None), (String::new(), 2)); + // Store: free the old slot (NULL too), clear it, then copy the caller's. + assert_eq!(trace(false, a, None, Some("first")), ("fD".into(), 3)); + assert_eq!( + trace(false, a, Some("first"), Some("second")), + ("FD".into(), 3) + ); + assert_eq!(trace(false, a, Some("first"), None), ("F".into(), 2)); + assert_eq!(trace(false, a, None, None), ("f".into(), 2)); +} + +#[test] +fn characterized_edges() { + let [last, _, _, _, _, a, b] = layout(); + let keys = [ + OBS_KEY_NONE, + 1, + c_int::try_from(a).unwrap(), + c_int::try_from(b).unwrap(), + c_int::try_from(last - 1).unwrap(), + ]; + let texts = [ + None, + some(""), + some("translated A"), + some("a longer replacement translation"), + some("\u{e9}\u{4e2d}"), + ]; + for key in keys { + for stored in &texts { + for arg in &texts { + check(key, stored, arg); + } + } + } +} + +fn bytes() -> impl Strategy> { + prop::option::of(prop::collection::vec(1u8..=255, 0..48).prop_map(|v| CString::new(v).unwrap())) +} + +proptest! { + #![proptest_config(ProptestConfig { + cases: obs_c_oracle::parity::cases(256), failure_persistence: None, + ..ProptestConfig::default() + })] + #[test] + fn query_and_store_match_c(key in 0..last_key(), stored in bytes(), arg in bytes()) { + check(key, &stored, &arg); + } +} + +/// The adapters as the shim sees them, for the mutants. +struct Adapters; +impl KeyTranslations for Adapters { + type Text = NonNull; + fn get(&mut self, key: i32) -> Option> { + // SAFETY: fixture adapter; key is in range. + NonNull::new(unsafe { *obs_hotkey_key_translation_slot(key) }) + } + fn set(&mut self, key: i32, value: Option>) { + // SAFETY: fixture adapter; key is in range. + unsafe { + *obs_hotkey_key_translation_slot(key) = value.map_or(null_mut(), NonNull::as_ptr) + }; + } + fn release(&mut self, value: Option>) { + // SAFETY: fixture adapter; frees what the slot held. + unsafe { obs_hotkey_key_translation_free(value.map_or(null_mut(), NonNull::as_ptr)) }; + } + fn duplicate(&mut self, value: NonNull) -> Option> { + // SAFETY: fixture adapter; value is NUL-terminated. + NonNull::new(unsafe { obs_hotkey_key_translation_dup(value.as_ptr()) }) + } +} + +unsafe extern "C" fn reads_for_none(key: c_int, def: *const c_char) -> *const c_char { + let _ = Adapters.get(key); + // SAFETY: as the shim. + unsafe { obs_get_hotkey_translation(key, def) } +} + +unsafe extern "C" fn prefers_default(key: c_int, def: *const c_char) -> *const c_char { + if def.is_null() { + // SAFETY: as the shim. + unsafe { obs_get_hotkey_translation(key, def) } + } else { + def + } +} + +unsafe extern "C" fn reads_once(key: c_int, def: *const c_char) -> *const c_char { + if key == OBS_KEY_NONE { + return null(); + } + Adapters + .get(key) + .map_or(def, |text| text.as_ptr().cast_const()) +} + +unsafe extern "C" fn leaks_old(key: c_int, arg: *const c_char) { + let mut table = Adapters; + table.set(key, None); + if let Some(arg) = NonNull::new(arg.cast_mut()) { + let copy = table.duplicate(arg); + table.set(key, copy); + } + let _ = table.get(key); +} + +unsafe extern "C" fn copies_other_text(key: c_int, arg: *const c_char) { + let mut table = Adapters; + let old = table.get(key); + table.release(old); + table.set(key, None); + if !arg.is_null() { + let copy = table.duplicate(NonNull::from(c"other").cast()); + table.set(key, copy); + } +} + +unsafe extern "C" fn copies_before_free(key: c_int, arg: *const c_char) { + let mut table = Adapters; + let copy = NonNull::new(arg.cast_mut()).map(|arg| table.duplicate(arg)); + let old = table.get(key); + table.release(old); + table.set(key, None); + if let Some(copy) = copy { + table.set(key, copy); + } +} + +unsafe extern "C" fn null_keeps_old(key: c_int, arg: *const c_char) { + if arg.is_null() { + let mut table = Adapters; + let _ = table.get(key); + let _ = table.get(key); + let old = table.get(key); + table.release(None); + let _ = old; + return; + } + // SAFETY: as the shim. + unsafe { obs_hotkeys_store_key_translation(key, arg) }; +} + +unsafe extern "C" fn wrong_key(key: c_int, arg: *const c_char) { + // SAFETY: as the shim, on the neighbouring key (in range in every case). + unsafe { obs_hotkeys_store_key_translation(key ^ 1, arg) }; +} + +#[test] +fn mutants_are_caught() { + let [_, _, _, _, _, a, _] = layout(); + let a = c_int::try_from(a).unwrap(); + let stored = some("stored"); + let def = some("default"); + let arg = some("new name"); + assert_eq!( + query_probe(OBS_KEY_NONE, &None, &def, reads_for_none) & 1, + 1 + ); + assert_eq!(query_probe(a, &stored, &def, prefers_default) & 2, 2); + assert_eq!(query_probe(a, &stored, &def, reads_once) & 1, 1); + assert_eq!(store_probe(a, &stored, &arg, leaks_old) & 5, 5); + assert_eq!(store_probe(a, &stored, &arg, copies_other_text) & 3, 3); + assert_eq!(store_probe(a, &stored, &arg, copies_before_free) & 1, 1); + assert_eq!(store_probe(a, &stored, &None, null_keeps_old) & 6, 6); + assert_eq!(store_probe(a, &None, &arg, wrong_key) & 6, 6); + // The safe core through the same adapters agrees with the shims. + assert_eq!( + translation(&mut Adapters, OBS_KEY_NONE, None).map(NonNull::as_ptr), + None + ); + unsafe extern "C" fn core_store(key: c_int, arg: *const c_char) { + store(&mut Adapters, key, NonNull::new(arg.cast_mut())); + } + assert_eq!(store_probe(a, &stored, &arg, core_store), 0); + check(a, &stored, &arg); +} diff --git a/rust/obs-hotkey/tests/hotkey/main.rs b/rust/obs-hotkey/tests/hotkey/main.rs index d1d5ff4737..c375b9c949 100644 --- a/rust/obs-hotkey/tests/hotkey/main.rs +++ b/rust/obs-hotkey/tests/hotkey/main.rs @@ -36,6 +36,7 @@ mod inject_entry_parity; mod key_combination; mod key_combination_parity; mod key_translation; +mod key_translation_parity; mod nix_hotkey_state; mod nix_hotkey_state_parity; mod nix_wayland_key_names; @@ -175,10 +176,11 @@ pub mod hotkey_mutex { } } -/// Cargo-test stand-in for libobs's hidden -/// `obs_hotkeys_store_key_translation` (obs-hotkey.c.h), which the -/// translations shim and its C oracle both call. It records each call per -/// thread, so each test sees only its own. +/// Records each call of libobs's hidden `obs_hotkeys_store_key_translation`, +/// which the translations shim and its C oracle both call. The store is the +/// real Rust one (`obs_hotkey::ffi::key_translation`); under cargo test its +/// C adapters run on the key-translation oracle's per-thread core, which +/// reports each store to this module, so each test sees only its own. pub mod hotkey_store { use std::cell::RefCell; use std::ffi::{CStr, c_char, c_int}; @@ -196,29 +198,36 @@ pub mod hotkey_store { static CALLS: RefCell> = const { RefCell::new(Vec::new()) }; } - /// The calls on this thread since the last `take`. - pub fn take() -> Vec { - CALLS.with(|c| std::mem::take(&mut *c.borrow_mut())) + unsafe extern "C" { + fn oracle_hotkey_key_translation_record( + hook: Option, + ); } - /// # Safety - /// - /// `translation` is null or a NUL-terminated string. - #[unsafe(no_mangle)] - pub unsafe extern "C" fn obs_hotkeys_store_key_translation( - key: c_int, - translation: *const c_char, - ) { - let name = (!translation.is_null()).then(|| { - // SAFETY: the caller passes a NUL-terminated string. - unsafe { CStr::from_ptr(translation) }.to_bytes().to_vec() - }); + /// The store frees the old name first (`NULL`), then copies the + /// caller's string, if any. + unsafe extern "C" fn record(key: c_int, translation: *const c_char) { CALLS.with(|c| { - c.borrow_mut().push(Stored { - key, - ptr: translation as usize, - name, - }) + let mut calls = c.borrow_mut(); + if translation.is_null() { + calls.push(Stored { + key, + ptr: 0, + name: None, + }); + } else if let Some(last) = calls.last_mut() { + // SAFETY: the store copies a NUL-terminated string. + last.name = Some(unsafe { CStr::from_ptr(translation) }.to_bytes().to_vec()); + last.ptr = translation as usize; + } }); } + + /// The calls on this thread since the last `take`. Each `take` empties + /// the fixture's name store and starts recording again. + pub fn take() -> Vec { + // SAFETY: frees only names this thread's fixture stored. + unsafe { oracle_hotkey_key_translation_record(Some(record)) }; + CALLS.with(|c| std::mem::take(&mut *c.borrow_mut())) + } } diff --git a/rust/obs-hotkey/tests/hotkey/translations_parity.rs b/rust/obs-hotkey/tests/hotkey/translations_parity.rs index f50642d41e..da64176bb4 100644 --- a/rust/obs-hotkey/tests/hotkey/translations_parity.rs +++ b/rust/obs-hotkey/tests/hotkey/translations_parity.rs @@ -7,9 +7,9 @@ //! compares the two directly. //! //! The oracle expands its templates on the original `util/dstr.c` (the C -//! dstr oracle), not on the Rust dstr port. Both sides call the same -//! recording stand-in for the store, `obs_hotkeys_store_key_translation` -//! (`super::hotkey_store`). Compared, for the same struct and `size`: every +//! dstr oracle), not on the Rust dstr port. Both sides call the same store, +//! `obs_hotkeys_store_key_translation`, whose calls `super::hotkey_store` +//! records. Compared, for the same struct and `size`: every //! store call, in order: the key, the bytes of the string, and whether the //! pointer passed is one of the caller's members (the C passes a named //! key's string on as it is) and which. The struct must be left as it was. diff --git a/test/cmocka/build/rust-static-support.json b/test/cmocka/build/rust-static-support.json index 2b2135ad24..aa6139a60c 100644 --- a/test/cmocka/build/rust-static-support.json +++ b/test/cmocka/build/rust-static-support.json @@ -38,7 +38,8 @@ "test/cmocka/output-interleave-name-link-support.c", "test/cmocka/graphics-device-queries-link-support.c", "test/cmocka/output-encoder-getters-link-support.c", - "test/cmocka/encoder-last-error-link-support.c" + "test/cmocka/encoder-last-error-link-support.c", + "test/cmocka/hotkey-key-translation-link-support.c" ], "platform_sources": { "OS_WINDOWS": [ diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 6719566313..6f3323a509 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -6892,6 +6892,37 @@ "SIMDe::SIMDe" ] }, + "test_hotkey_key_translation_rust": { + "sources": [ + "test/cmocka/test_hotkey_key_translation.c", + "test/cmocka/hotkey-key-translation-record-support.c" + ], + "pch": "libobs/build/libobs.pch.h", + "unity_groups": { + "key_translation": [ + "test/cmocka/test_hotkey_key_translation.c", + "test/cmocka/hotkey-key-translation-record-support.c" + ] + }, + "definitions": [ + "HOTKEY_KEY_TRANSLATION_EXTERNAL" + ], + "libraries": [ + "libobs_rust-static", + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ], + "header_libraries": [ + "SIMDe::SIMDe" + ], + "requires": "HAVE_LIBOBS_RUST_STATIC" + }, "test_hotkey_load": { "sources": [ "libobs/obs-hotkey-binding-press.c.h", @@ -24784,6 +24815,13 @@ ], "target": "test_hotkey_key_translation" }, + "test_hotkey_key_translation_rust": { + "target": "test_hotkey_key_translation_rust", + "command": [ + "${target}" + ], + "requires": "HAVE_LIBOBS_RUST_STATIC" + }, "test_hotkey_load": { "target": "test_hotkey_load" }, diff --git a/test/cmocka/hotkey-key-translation-link-support.c b/test/cmocka/hotkey-key-translation-link-support.c new file mode 100644 index 0000000000..a385e3cb75 --- /dev/null +++ b/test/cmocka/hotkey-key-translation-link-support.c @@ -0,0 +1,2 @@ +/* Standalone Rust-static consumers use the real private key-translation adapters. */ +#include "libobs/obs-hotkey-key-translation-fields.c.h" diff --git a/test/cmocka/hotkey-key-translation-record-support.c b/test/cmocka/hotkey-key-translation-record-support.c new file mode 100644 index 0000000000..f5ec445ced --- /dev/null +++ b/test/cmocka/hotkey-key-translation-record-support.c @@ -0,0 +1,7 @@ +/* test_hotkey_key_translation_rust: the real private key-translation adapters, + * bound to the unchanged characterization's own core. One unity group includes + * this after the test, so record_core() is the test's own recording reader, + * exactly as its non-external branch binds the original. */ +#define obs record_core() +#include "libobs/obs-hotkey-key-translation-fields.c.h" +#undef obs diff --git a/test/cmocka/windows-keys-rust-stubs.c b/test/cmocka/windows-keys-rust-stubs.c index 3b7deea877..ec389aed59 100644 --- a/test/cmocka/windows-keys-rust-stubs.c +++ b/test/cmocka/windows-keys-rust-stubs.c @@ -72,13 +72,6 @@ bool obs_hotkey_pair_call_func(obs_hotkey_pair_t *pair, size_t half, obs_hotkey_ abort(); } -void obs_hotkeys_store_key_translation(obs_key_t key, const char *translation) -{ - (void)key; - (void)translation; - abort(); -} - void obs_hotkeys_mutex_lock(void) { abort(); From fe5ca4b9e3def83a06cf9221c9b872d2899f3230 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Fri, 20 Nov 2026 01:23:56 -0500 Subject: [PATCH 3/3] obs-c-oracle: cast the key-translation oracle's key to int for macOS (Refs #5321) On Apple targets enum obs_key is unsigned, so storing it in the int kt_last_key tripped -Wsign-conversion and broke the macOS cross lint and artifact lanes. Co-Authored-By: Claude Opus 5.5 Ci-Attestation: {"at":1795156807,"gate":"data/all/compatibility","host":"linux-x86_64","key":"","lane":"client-checks","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":93,"stamp":"8d5d83d0af26cef72527c99d0b1dfd6f","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156807,"gate":"data/all/flatpak-manifest","host":"linux-x86_64","key":"","lane":"client-checks","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":93,"stamp":"27660b6d178a171f96e4b76f669cbcae","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156807,"gate":"data/all/qt-xml","host":"linux-x86_64","key":"","lane":"client-checks","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":93,"stamp":"5ccd40ed1ccda1d713c562ce5663fc76","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156807,"gate":"data/all/services-schema","host":"linux-x86_64","key":"","lane":"client-checks","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":93,"stamp":"3560116aea11d09ca885b1f3f587e1f0","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"general/all/client-lint","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"fb7480029512d87c96bf3f4155748aa1","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156807,"gate":"python/all/self-test","host":"linux-x86_64","key":"","lane":"client-checks","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":93,"stamp":"6cfeab94a050dae2a2a29bc63255f2f8","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/aarch64-apple-darwin/client-clippy","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"20b8b32c9e68bf43b56a396ad4b391ac","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/aarch64-apple-darwin/client-dylint","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"cb0307db011f644610b617245855236b","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/aarch64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"1de9c5db952241f72abce0d1e6f38a62","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/aarch64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"c93b9d7384aeda5e9894692cf42ef50e","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/aarch64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"287ca02cc853af1039415f66d6eaa4dd","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/aarch64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"ed066e7c6989bf999baec5e15915cc1e","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/x86_64-apple-darwin/client-clippy","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"0ed394e914697c5b4b87ada5c7361b4f","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/x86_64-apple-darwin/client-dylint","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"742814af1b7df0ed11fb1b07ce2cb02d","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/x86_64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"6344539b4b020dc99866533a4e836542","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/x86_64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"8cbd89b9ab4ef18f9c4c3acc4a1ef94b","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/x86_64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"9c2d7f2aad01848f0a863e0aa85334cd","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795156713,"gate":"rust/x86_64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"27a8ffbcefe5ff5554b09f7468ae33aedfcf6116fd60cce78aa306e762b0b8c7","lane":"client-lint","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":140,"stamp":"4474ac51b6732250189ada2af350097d","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Ci-Attestation: {"at":1795157044,"gate":"rust/x86_64-unknown-linux-gnu/client-test","host":"linux-x86_64","key":"7a38a25f0f2c387824a8300603bc220cd6129c3762e30a45000608f8fd673c72","lane":"client-test-x86_64-unknown-linux-gnu","parents":["4626b387f49305df1efbf459ccfe19a19117f135"],"secs":236,"stamp":"c604f509b742bd572e8887fd19adc463","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487","v":1,"via":"run"} Client-Checks: {"checks":{"base":"f5edeeb1fa1d8fc96e0dd7d3d951470687a76ee2","coverage":"all-tracked-applicable-files","diff":["ci/test_bench_libobs_stand_ins.py","libobs/build/libobs.core+.h.c","libobs/build/libobs.ported-hotkey-key-translation+.h.c","libobs/build/ported-source-sets/hotkey-key-translation.json","libobs/cmake/rust-hidden.d/obs-hotkey-key_translation.txt","libobs/obs-hotkey-key-translation-fields.c.h","rust/README.md","rust/obs-build/tests/native.rs","rust/obs-build/tests/native/registration/canonical_hotkey_key_translation_swap_is_registered.rs","rust/obs-build/tests/native/registration/rust-static/cases/hotkey-control/test_hotkey_key_translation_rust.json","rust/obs-c-oracle/benches/port_comparison.rs","rust/obs-c-oracle/oracle/hotkey_key_translation.c","rust/obs-c-oracle/oracle/hotkey_translations.c","rust/obs-c-oracle/src/hotkey_translations.rs","rust/obs-hotkey/src/ffi/key_translation.rs","rust/obs-hotkey/src/ffi/mod.rs","rust/obs-hotkey/src/ffi/translations.rs","rust/obs-hotkey/src/key_translation.rs","rust/obs-hotkey/src/lib.rs","rust/obs-hotkey/tests/hotkey/key_translation.rs","rust/obs-hotkey/tests/hotkey/key_translation_parity.rs","rust/obs-hotkey/tests/hotkey/main.rs","rust/obs-hotkey/tests/hotkey/translations_parity.rs","test/cmocka/build/rust-static-support.json","test/cmocka/build/test-graph.json","test/cmocka/hotkey-key-translation-link-support.c","test/cmocka/hotkey-key-translation-record-support.c","test/cmocka/windows-keys-rust-stubs.c"],"head":"a648d8cd03d639e928e6aaea165230732ed26c03","tools":{"orchestrator-python":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]","schema-dependencies":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]\n{'jsonschema': '4.26.0', 'json_source_map': '1.0.5'}","uv":"uv 0.13.5 (x86_64-unknown-linux-gnu)","xmllint":"xmllint: using libxml version 21504-GITv2.15.4\n compiled with: Threads Tree Output Push Reader Patterns Writer SAXv1 DTDValid HTML C14N Catalog XPath XPointer XInclude Iconv ICU ISO8859X Regexps Automata RelaxNG Schemas Schematron Modules Debug Zlib"},"tracked-digest":"0c25aa1f42ec1fbae129f7b86face0ad7113958cb7c1f73295cf1de377d98898","tree":"026f1faf19036b6c6eb20ffbf1016f60082a2487"}} --- rust/obs-c-oracle/oracle/hotkey_key_translation.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/obs-c-oracle/oracle/hotkey_key_translation.c b/rust/obs-c-oracle/oracle/hotkey_key_translation.c index fe214ceaff..30fb1bb71a 100644 --- a/rust/obs-c-oracle/oracle/hotkey_key_translation.c +++ b/rust/obs-c-oracle/oracle/hotkey_key_translation.c @@ -98,7 +98,7 @@ char **oracle_kt_fields_slot(obs_key_t key); char **obs_hotkey_key_translation_slot(obs_key_t key); char **obs_hotkey_key_translation_slot(obs_key_t key) { - kt_last_key = key; + kt_last_key = (int)key; return oracle_kt_fields_slot(key); }