diff --git a/libobs/build/libobs.core+.h.c b/libobs/build/libobs.core+.h.c index 4f39379c9b..ed055d7098 100644 --- a/libobs/build/libobs.core+.h.c +++ b/libobs/build/libobs.core+.h.c @@ -52,7 +52,7 @@ #include "libobs/obs-module.c.h" #include "libobs/obs-object-id-fields.c.h" #include "libobs/obs-object-ref-fields.c.h" -#include "libobs/obs-set-locale.c.h" +#include "libobs/obs-set-locale-fields.c.h" #include "libobs/obs-set-output-source-fields.c.h" #include "libobs/obs-shutdown-detach.c.h" #include "libobs/obs-type-catalog-enum-fields.c.h" diff --git a/libobs/build/libobs.ported-set-locale+.h.c b/libobs/build/libobs.ported-set-locale+.h.c new file mode 100644 index 0000000000..83bc1aad6c --- /dev/null +++ b/libobs/build/libobs.ported-set-locale+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): C reference locale replacement and notification. */ + +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-set-locale.c.h" diff --git a/libobs/build/ported-source-sets/set-locale.json b/libobs/build/ported-source-sets/set-locale.json new file mode 100644 index 0000000000..a91cde9499 --- /dev/null +++ b/libobs/build/ported-source-sets/set-locale.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-set-locale+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-core-set_locale.txt b/libobs/cmake/rust-exports.d/obs-core-set_locale.txt new file mode 100644 index 0000000000..9f7ebf6027 --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-core-set_locale.txt @@ -0,0 +1 @@ +obs_set_locale diff --git a/libobs/obs-set-locale-fields.c.h b/libobs/obs-set-locale-fields.c.h new file mode 100644 index 0000000000..123c76232a --- /dev/null +++ b/libobs/obs-set-locale-fields.c.h @@ -0,0 +1,31 @@ +#include "libobs/build/libobs.pch.h" + +struct obs_core *obs_core_set_locale_core(void); +struct obs_core *obs_core_set_locale_core(void) +{ + return obs; +} + +char **obs_core_set_locale_field(struct obs_core *core); +char **obs_core_set_locale_field(struct obs_core *core) +{ + return &core->locale; +} + +struct obs_module *obs_core_set_locale_first(struct obs_core *core); +struct obs_module *obs_core_set_locale_first(struct obs_core *core) +{ + return core->first_module; +} + +void (*obs_core_set_locale_callback(struct obs_module *module))(const char *); +void (*obs_core_set_locale_callback(struct obs_module *module))(const char *) +{ + return module->set_locale; +} + +struct obs_module *obs_core_set_locale_next(struct obs_module *module); +struct obs_module *obs_core_set_locale_next(struct obs_module *module) +{ + return module->next; +} diff --git a/rust/README.md b/rust/README.md index cba4dec55e..f518a9d715 100644 --- a/rust/README.md +++ b/rust/README.md @@ -597,6 +597,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-video-level-queries.c.h` | `obs-core::video_level_queries` | Video SDR white and HDR nominal peak level queries (#5187). A real private C adapter returns the current core, which safe Rust checks for NULL before a second adapter reads the graphics pointer and both stored levels. Without a core or graphics the queries return exactly 300.0 and 1000.0; otherwise each stored level's exact bits, with no validation, clamping or arithmetic (signed zeros, infinities and NaN payloads verbatim). Tier 1 mirrors the unchanged `test_video_level_queries`, which now links the Rust export and the real adapter; original-C Tier 3 checks real adapter layout, the three core states over edge and random bit patterns, unchanged core bytes and global pointer. `test_no_core_getters` and `test_video_levels_range` keep actual-library coverage. Dead core and concurrent level writes are excluded; signaling NaNs are left out of the random cases (32-bit x86 float returns may quiet them in both). No intentional differences. | | `libobs/obs-get-audio.c.h` | `obs-core::get_audio` | Borrowed current core audio output (#4808). Exact pointer forwarding, including null before setup/after disable, without ownership or activation changes. Safe Tier 1 mirrors the C characterization; original-C Tier 3 checks current-field changes, pointer identity, unchanged bytes and real adapter layout. Unchanged Tier 2 covers real output lifecycles. Initialized core required; no intentional differences. | | `libobs/obs-get-output-source.c.h` | `obs-core::get_output_source` | Legacy main-canvas channel getter (#4756). Forwards the borrowed current canvas and unchanged channel exactly once to the existing getter and returns its acquired source unchanged. Tier 1 mirrors the C characterization; original-C Tier 3 checks return identity, reference effects, full-width forwarding and real adapter layout; unchanged Tier 2 exercises both actual libraries. Uninitialized core, dead canvas/source and overflowing refcounts are original C UB, excluded; no intentional differences. | +| `libobs/obs-set-locale.c.h` | `obs-core::set_locale` | Locale replacement and ordered module notifications through private field adapters. Frees old bmem storage before copying, stores the owned copy before callbacks, forwards the original pointer including NULL, and reads each next link after dispatch. Safe Tier 1 mirrors unchanged `test_set_locale`; Tier 3 compares the original C with the actual Rust FFI over bounded locale/list cases, including callback-time link changes. The common reference-only group covers every host; the native test fixture manifest remains unchanged. No intentional behavior differences; Tier 4 does not apply. | | `libobs/obs-set-output-source.c.h` | `obs-core::set_output_source` | Legacy main-canvas channel setter (#4709). Forwards the borrowed current canvas and unchanged channel/source exactly once to the existing canvas setter, preserving bounds, mutable local/global signals and all reference effects. Tier 1 mirrors the C characterization, callback-only original-C Tier 3 checks real adapter layout and unchanged object bytes, and unchanged Tier 2 runs both actual libraries. Uninitialized core and dead canvas/source are original C UB, excluded; no intentional differences. | | `libobs/obs-get-main-canvas.c.h` | `obs-core::get_main_canvas` | Main-canvas acquired getter (#4780). A real private C adapter borrows the current field and supplies the existing canvas reference operation; safe Rust delegates exactly once and preserves its returned identity and ownership effects. Tier 1 mirrors unchanged `test_get_main_canvas`, Tier 3 includes the original C wrapper and real adapter with exact layout and complete fixture-byte comparisons, and Tier 2 replays both actual libraries. Uninitialized core, dead canvases and overflowing counts are excluded; no intentional differences or Tier 4 surface. | | `libobs/obs-win-crash-report.c.h` | `obs-core::win_crash_report` | Swapped in hybrid `libobs` (group `libobs.ported-win-crash-report`, in the Windows ported sources). Nine pure functions on integers, declared in `obs-win-crash-report.h` without `EXPORT` and hidden; they take no Windows type, so the file, its C test and its oracle build on every OS: `obs_win_crash_report_contains` (`enum_all_modules()`'s and `enum_module()`'s `base <= addr < base + size`, the end a wrapping `uint64_t`), `_is_crashed`, `_in_pass` and `_other_process` (`write_thread_trace()`'s id against `GetCurrentThreadId()`, the crashed thread in the first pass and every other in the second, and the owner against `GetCurrentProcessId()`), `_names_symbol` (`walk_stack()`'s line with the symbol unless `SYMFLAG_EXPORT`, 0x200, `_Static_assert`ed against `dbghelp.h`; the flags still read only after a successful lookup), `_mask_address` and `_mask_param` (a 32-bit build's masks: 36 bits on the stack and PC, 32 on the parameters), `_name_prefix` (`get_thread_name()`'s leading space for a non-empty name) and `_pass_on` (`exception_handler()`'s two early returns: a debugger, or re-entered, reading `*inside` only without a debugger). Each check of `write_thread_trace()` is its own function, so `GetCurrentProcessId()` is still called only for a thread in its pass. `obs-win-crash-handler.c.h` keeps every DbgHelp, toolhelp and thread call, `os_wcs_to_utf8()`, `strlwr()`, `strrchr()`, every `dstr` call and format string, `bcrash()` and both static flags. The core runs inside the unhandled exception filter: no allocation, indexing or panic path, and a per-thread counting allocator in the core test binary checks that no shim or core rule allocates. No intentional differences; characterized, not endorsed and kept: a module whose end wraps past 2^64, or lands on it, holds nothing; the stack and PC masks keep 36 bits where the parameters keep 32; the crashed thread's id under another process is left out of both passes. `test_win_crash_report_steps` compiles the C into itself on every OS; it has no `_rust` variant, as for `test_nix_system_info_steps`. `test_win_crash_sym_info` (Windows) compiles it with the handler. Tier 3 compares every result exactly over every combination of edge bases, sizes and addresses at each module's edges, every pair of edge thread ids, `write_thread_traces()`'s two passes over every snapshot of up to three threads, every flag of the low 16 bits under four high patterns and every pair of bits, both masks around every power of two, name lengths 0 to 4096, the filter with NULL for the flag under a debugger, and proptests over all of it; nothing is skipped on any host. | diff --git a/rust/obs-build/tests/native/registration/canonical_video_info_query_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_video_info_query_is_registered.rs index 34d317f917..d2a45581f0 100644 --- a/rust/obs-build/tests/native/registration/canonical_video_info_query_is_registered.rs +++ b/rust/obs-build/tests/native/registration/canonical_video_info_query_is_registered.rs @@ -92,6 +92,9 @@ function(check_support) message(FATAL_ERROR "${{name}}: missing private video-info adapters") endif() endforeach() + if(NOT "{root}/test/cmocka/set-locale-link-support.c" IN_LIST adapter_sources) + message(FATAL_ERROR "missing real private adapter source: set-locale") + endif() endfunction() cmake_language(DEFER CALL check_support) "#, diff --git a/rust/obs-c-oracle/oracle.d/set-locale.list b/rust/obs-c-oracle/oracle.d/set-locale.list new file mode 100644 index 0000000000..292d40ca58 --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/set-locale.list @@ -0,0 +1 @@ +obs-set-locale.inc|libobs/obs-set-locale.c.h|auto diff --git a/rust/obs-c-oracle/oracle/set_locale.c b/rust/obs-c-oracle/oracle/set_locale.c new file mode 100644 index 0000000000..6acab507b3 --- /dev/null +++ b/rust/obs-c-oracle/oracle/set_locale.c @@ -0,0 +1,117 @@ +/* Original C and the real private adapters over a thread-owned core. Tier 2 + * additionally exercises these same paths in the complete shared libraries. */ +#include "libobs/build/libobs.pch.h" + +static THREAD_LOCAL struct obs_core locale_core; +static THREAD_LOCAL struct obs_module locale_modules[7]; +static THREAD_LOCAL const char *locale_argument; +static THREAD_LOCAL long locale_baseline; +static THREAD_LOCAL size_t locale_count; +static THREAD_LOCAL uint64_t locale_events[64]; +static THREAD_LOCAL bool locale_mutate; + +void oracle_obs_set_locale(const char *locale); +void oracle_set_locale_reset(const unsigned char *order, unsigned count, unsigned callbacks, bool mutate); +size_t oracle_set_locale_step(bool rust, char *locale, uint64_t *out); +void oracle_set_locale_finish(void); +void oracle_set_locale_layout(size_t *out); + +#define obs (&locale_core) +#define obs_set_locale oracle_obs_set_locale +#include "obs-set-locale.inc" +#undef obs_set_locale +#include "set-locale-fields.inc" +#undef obs + +static void locale_record(unsigned id, const char *locale) +{ + const char *owned = locale_core.locale; + locale_events[locale_count++] = id; + locale_events[locale_count++] = locale == locale_argument; + locale_events[locale_count++] = locale ? owned && owned != locale && strcmp(owned, locale) == 0 : !owned; + locale_events[locale_count++] = (uint64_t)(bnum_allocs() - locale_baseline); + /* The C traversal reads next after dispatch, rather than snapshotting it. */ + if (locale_mutate && id < 6) { + struct obs_module *next = locale_modules[id].next; + if (next) + locale_modules[id].next = next->next; + } +} +#define LOCALE_CALLBACK(id) \ + static void locale_callback_##id(const char *locale) \ + { \ + locale_record(id, locale); \ + } +LOCALE_CALLBACK(0) +LOCALE_CALLBACK(1) +LOCALE_CALLBACK(2) +LOCALE_CALLBACK(3) +LOCALE_CALLBACK(4) +LOCALE_CALLBACK(5) +LOCALE_CALLBACK(6) +#undef LOCALE_CALLBACK + +void oracle_set_locale_reset(const unsigned char *order, unsigned count, unsigned callbacks, bool mutate) +{ + memset(&locale_core, 0, sizeof(locale_core)); + memset(locale_modules, 0, sizeof(locale_modules)); + locale_baseline = bnum_allocs(); + locale_core.locale = bstrdup("old"); + void (*handlers[])(const char *) = {locale_callback_0, locale_callback_1, locale_callback_2, locale_callback_3, + locale_callback_4, locale_callback_5, locale_callback_6}; + for (unsigned i = 0; i < 7; ++i) { + locale_modules[i].set_locale = callbacks & (1u << i) ? handlers[i] : NULL; + locale_modules[i].loaded = false; + locale_modules[i].load_state = OBS_MODULE_DISABLED; + } + for (unsigned i = 0; i < count; ++i) + locale_modules[order[i]].next = i + 1 < count ? &locale_modules[order[i + 1]] : NULL; + locale_core.first_module = count ? &locale_modules[order[0]] : NULL; + locale_core.first_disabled_module = &locale_modules[6]; + locale_mutate = mutate; +} + +size_t oracle_set_locale_step(bool rust, char *locale, uint64_t *out) +{ + locale_argument = locale; + locale_count = 0; + if (rust) + obs_set_locale(locale); + else + oracle_obs_set_locale(locale); + size_t n = 0; + out[n++] = locale_core.locale != NULL; + out[n++] = (uint64_t)(bnum_allocs() - locale_baseline); + out[n++] = locale_count; + for (size_t i = 0; i < locale_count; ++i) + out[n++] = locale_events[i]; + /* Mutating caller storage after dispatch must not affect the owned copy. */ + if (locale) { + char *input = locale; + char saved = input[0]; + input[0] = saved ? 'x' : '\0'; + for (const unsigned char *p = (const unsigned char *)locale_core.locale; *p; ++p) + out[n++] = *p; + input[0] = saved; + } + out[n++] = locale_core.first_module ? (uint64_t)(locale_core.first_module - locale_modules) + 1 : 0; + out[n++] = locale_core.first_disabled_module == &locale_modules[6]; + for (unsigned i = 0; i < 7; ++i) { + out[n++] = locale_modules[i].next ? (uint64_t)(locale_modules[i].next - locale_modules) + 1 : 0; + out[n++] = locale_modules[i].loaded; + out[n++] = (uint64_t)locale_modules[i].load_state; + } + return n; +} + +void oracle_set_locale_finish(void) +{ + bfree(locale_core.locale); + locale_core.locale = NULL; +} + +void oracle_set_locale_layout(size_t *out) +{ + out[0] = sizeof(locale_modules[0].set_locale); + out[1] = _Alignof(void (*)(const char *)); +} diff --git a/rust/obs-core/src/ffi/mod.rs b/rust/obs-core/src/ffi/mod.rs index fbd2334ed8..f959dfe1fb 100644 --- a/rust/obs-core/src/ffi/mod.rs +++ b/rust/obs-core/src/ffi/mod.rs @@ -63,6 +63,7 @@ pub mod object_validity_query; pub mod output_protocol_registry; pub mod private_data; pub mod raw_audio_remove; +pub mod set_locale; pub mod set_output_source; pub mod shutdown_detach; pub mod source_load; diff --git a/rust/obs-core/src/ffi/set_locale.rs b/rust/obs-core/src/ffi/set_locale.rs new file mode 100644 index 0000000000..86300e3ecc --- /dev/null +++ b/rust/obs-core/src/ffi/set_locale.rs @@ -0,0 +1,76 @@ +//! C-owned allocation and opaque core/module field access for locale changes. +use super::module_paths::bstrdup; +use crate::set_locale::{self, Host}; +use core::ffi::{c_char, c_void}; +use core::ptr::NonNull; +use obs_util::ffi::darray::bfree; + +pub type Callback = Option; +unsafe extern "C" { + fn obs_core_set_locale_core() -> *mut c_void; + fn obs_core_set_locale_field(core: *mut c_void) -> *mut *mut c_char; + fn obs_core_set_locale_first(core: *mut c_void) -> *mut c_void; + fn obs_core_set_locale_callback(module: *mut c_void) -> Callback; + fn obs_core_set_locale_next(module: *mut c_void) -> *mut c_void; +} +struct Calls { + core: NonNull, +} +impl Host for Calls { + type Locale = *const c_char; + type Owned = *mut c_char; + type Module = NonNull; + type Callback = unsafe extern "C" fn(*const c_char); + fn owned_locale(&mut self) -> Option { + // SAFETY: the API caller keeps the checked core live and exclusive. + NonNull::new(unsafe { obs_core_set_locale_field(self.core.as_ptr()).read() }) + .map(NonNull::as_ptr) + } + fn free_locale(&mut self, owned: Self::Owned) { + // SAFETY: locale storage is owned by libobs and allocated with bmem. + unsafe { bfree(owned.cast()) }; + } + fn copy_locale(&mut self, locale: Self::Locale) -> Self::Owned { + // SAFETY: the caller supplies NULL or a live NUL-terminated string, + // independent of the old locale that the safe core has just released. + NonNull::new(locale.cast_mut()).map_or(core::ptr::null_mut(), |locale| { + // SAFETY: the non-NULL input is NUL-terminated and remains live. + bstrdup(unsafe { core::ffi::CStr::from_ptr(locale.as_ptr()) }.to_bytes()) + }) + } + fn store_locale(&mut self, owned: Self::Owned) { + // SAFETY: the checked core's field receives its new bmem-owned value. + unsafe { obs_core_set_locale_field(self.core.as_ptr()).write(owned) }; + } + fn first_module(&mut self) -> Option { + // SAFETY: the caller keeps the core and its module list live. + NonNull::new(unsafe { obs_core_set_locale_first(self.core.as_ptr()) }) + } + fn callback(&mut self, module: Self::Module) -> Option { + // SAFETY: only non-NULL live list members reach this field accessor. + unsafe { obs_core_set_locale_callback(module.as_ptr()) } + } + fn notify(&mut self, callback: Self::Callback, locale: Self::Locale) { + // SAFETY: this module callback accepts the original caller argument. + // No Rust reference or lock spans the possibly reentrant callback. + unsafe { callback(locale) }; + } + fn next_module(&mut self, module: Self::Module) -> Option { + // SAFETY: the caller retains this node across its callback, as in C. + NonNull::new(unsafe { obs_core_set_locale_next(module.as_ptr()) }) + } +} + +/// Replace the locale and notify present callbacks in linked-list order. +/// +/// # Safety +/// OBS must be initialized and remain live without concurrent locale/list +/// writes. `locale` must be NULL or a live NUL-terminated string that does not +/// alias the old owned locale. Callbacks must retain their current list node. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_set_locale(locale: *const c_char) { + // SAFETY: querying the global pointer does not access any core fields. + let core = NonNull::new(unsafe { obs_core_set_locale_core() }) + .expect("locale replacement requires an initialized core"); + set_locale::set_locale(&mut Calls { core }, locale); +} diff --git a/rust/obs-core/src/lib.rs b/rust/obs-core/src/lib.rs index 64cf4ac8c2..9ad39f9ba4 100644 --- a/rust/obs-core/src/lib.rs +++ b/rust/obs-core/src/lib.rs @@ -178,6 +178,7 @@ pub mod output_protocol_registry; mod platform; pub mod private_data; pub mod raw_audio_remove; +pub mod set_locale; pub mod set_output_source; pub mod shutdown_detach; pub mod source_load; diff --git a/rust/obs-core/src/set_locale.rs b/rust/obs-core/src/set_locale.rs new file mode 100644 index 0000000000..03103073b0 --- /dev/null +++ b/rust/obs-core/src/set_locale.rs @@ -0,0 +1,34 @@ +//! Locale replacement and ordered module notification over host-owned storage. + +/// Access to C-owned storage without exposing its layout to the safe core. +pub trait Host { + type Locale: Copy; + type Owned: Copy; + type Module: Copy; + type Callback; + fn owned_locale(&mut self) -> Option; + fn free_locale(&mut self, owned: Self::Owned); + fn copy_locale(&mut self, locale: Self::Locale) -> Self::Owned; + fn store_locale(&mut self, owned: Self::Owned); + fn first_module(&mut self) -> Option; + fn callback(&mut self, module: Self::Module) -> Option; + fn notify(&mut self, callback: Self::Callback, locale: Self::Locale); + fn next_module(&mut self, module: Self::Module) -> Option; +} + +/// Free before copying, store before notifying, and read each next link after +/// its callback. Notifications receive the original argument, including NULL. +pub fn set_locale(host: &mut H, locale: H::Locale) { + if let Some(old) = host.owned_locale() { + host.free_locale(old); + } + let owned = host.copy_locale(locale); + host.store_locale(owned); + let mut current = host.first_module(); + while let Some(module) = current { + if let Some(callback) = host.callback(module) { + host.notify(callback, locale); + } + current = host.next_module(module); + } +} diff --git a/rust/obs-core/tests/obs_core/main.rs b/rust/obs-core/tests/obs_core/main.rs index e9ee31bbf8..0538a6ec81 100644 --- a/rust/obs-core/tests/obs_core/main.rs +++ b/rust/obs-core/tests/obs_core/main.rs @@ -130,6 +130,8 @@ mod private_data; mod private_data_parity; mod raw_audio_remove; mod raw_audio_remove_parity; +mod set_locale; +mod set_locale_parity; mod set_output_source; mod set_output_source_parity; mod shutdown_detach; diff --git a/rust/obs-core/tests/obs_core/set_locale.rs b/rust/obs-core/tests/obs_core/set_locale.rs new file mode 100644 index 0000000000..80eac8415c --- /dev/null +++ b/rust/obs-core/tests/obs_core/set_locale.rs @@ -0,0 +1,171 @@ +//! Tier 1 mirrors every assertion in test_set_locale.c through safe host calls. +use obs_core::set_locale::{self, Host}; + +#[derive(Clone, Debug, Default, PartialEq)] +struct Module { + next: Option, + callback: Option, + loaded: bool, + disabled: bool, +} +#[derive(Default)] +struct Core<'a> { + owned: Option>, + modules: [Module; 7], + first: Option, + disabled: Option, + visits: Vec, + expected: Option<&'a [u8]>, + events: Vec<&'static str>, +} +impl<'a> Host for Core<'a> { + type Locale = Option<&'a [u8]>; + type Owned = Option; + type Module = usize; + type Callback = usize; + fn owned_locale(&mut self) -> Option { + self.owned.as_ref().map(|_| Some(1)) + } + fn free_locale(&mut self, owned: Self::Owned) { + assert_eq!(owned, Some(1)); + assert!(self.owned.take().is_some()); + self.events.push("free"); + } + fn copy_locale(&mut self, locale: Self::Locale) -> Self::Owned { + assert!(self.owned.is_none(), "free must precede copy"); + self.owned = locale.map(|input| { + let mut copy = Vec::with_capacity(input.len().max(1)); + copy.extend_from_slice(input); + copy + }); + self.events.push("copy"); + locale.map(|_| 1) + } + fn store_locale(&mut self, owned: Self::Owned) { + assert_eq!(owned.is_some(), self.owned.is_some()); + self.events.push("store"); + } + fn first_module(&mut self) -> Option { + self.first + } + fn callback(&mut self, module: usize) -> Option { + self.modules[module].callback + } + fn notify(&mut self, callback: usize, locale: Self::Locale) { + assert_eq!(locale, self.expected); + if let Some(input) = locale { + assert_eq!(input.as_ptr(), self.expected.unwrap().as_ptr()); + assert_ne!(input.as_ptr(), self.owned.as_ref().unwrap().as_ptr()); + } + assert_eq!(self.owned.as_deref(), self.expected); + assert_eq!(self.events.last(), Some(&"store")); + if callback == 2 { + assert_eq!(self.visits.last(), Some(&1)); + } + assert!(self.visits.len() < 12); + assert_ne!(callback, 99, "disabled-list callback must not run"); + self.visits.push(callback); + } + fn next_module(&mut self, module: usize) -> Option { + self.modules[module].next + } +} +fn assert_copy(core: &Core<'_>, input: &[u8]) { + assert_eq!(core.owned.as_deref(), Some(input)); + assert_ne!(core.owned.as_ref().unwrap().as_ptr(), input.as_ptr()); + assert_eq!(usize::from(core.owned.is_some()), 1); +} +#[test] +fn test_set_locale_replacement_owns_one_copy() { + let mut initial = b"en-US".to_vec(); + let mut replacement = b"a-much-longer-replacement-locale".to_vec(); + let empty = b""; + let mut core = Core::default(); + set_locale::set_locale(&mut core, Some(&initial)); + assert_copy(&core, &initial); + let owned = core.owned.take(); + drop(core); + initial[0] = b'x'; + assert_eq!(owned.as_deref(), Some(b"en-US".as_slice())); + let mut core = Core { + owned, + ..Core::default() + }; + set_locale::set_locale(&mut core, Some(&replacement)); + assert_copy(&core, &replacement); + assert_eq!(&core.events, &["free", "copy", "store"]); + let owned = core.owned.take(); + drop(core); + replacement[0] = b'x'; + assert_eq!( + owned.as_deref(), + Some(b"a-much-longer-replacement-locale".as_slice()) + ); + let mut core = Core { + owned, + ..Core::default() + }; + set_locale::set_locale(&mut core, Some(empty)); + assert_copy(&core, empty); + set_locale::set_locale(&mut core, None); + assert!(core.owned.is_none()); + set_locale::set_locale(&mut core, None); + assert!(core.owned.is_none()); + assert_eq!( + &core.events, + &[ + "free", "copy", "store", "free", "copy", "store", "copy", "store" + ] + ); +} +#[test] +fn test_set_locale_ordered_callbacks_skip_missing() { + let locale = b"fr-FR"; + let mut core = Core { + first: Some(5), + disabled: Some(6), + expected: Some(locale), + ..Core::default() + }; + for (module, next, callback) in [ + (5, Some(2), None), + (2, Some(3), Some(3)), + (3, Some(0), None), + (0, Some(1), Some(1)), + (1, Some(4), Some(2)), + (6, None, Some(99)), + ] { + core.modules[module] = Module { + next, + callback, + loaded: false, + disabled: module == 0, + }; + } + let before = core.modules.clone(); + for i in 0..2 { + set_locale::set_locale(&mut core, Some(locale)); + assert_eq!(core.visits.len(), (i + 1) * 3); + assert_eq!(&core.visits[i * 3..], &[3, 1, 2]); + } + core.expected = None; + set_locale::set_locale(&mut core, None); + assert_eq!(core.visits.len(), 9); + assert_eq!(&core.visits[6..], &[3, 1, 2]); + assert_eq!(core.modules, before); + assert_eq!(core.first, Some(5)); + assert_eq!(core.disabled, Some(6)); + assert!(core.owned.is_none()); +} +#[test] +fn test_set_locale_all_callbacks_missing() { + let mut core = Core { + first: Some(0), + ..Core::default() + }; + core.modules[0].next = Some(1); + core.modules[1].next = Some(2); + set_locale::set_locale(&mut core, Some(b"de-DE")); + assert_copy(&core, b"de-DE"); + assert!(core.visits.is_empty()); +} diff --git a/rust/obs-core/tests/obs_core/set_locale_parity.rs b/rust/obs-core/tests/obs_core/set_locale_parity.rs new file mode 100644 index 0000000000..ccd842cb03 --- /dev/null +++ b/rust/obs-core/tests/obs_core/set_locale_parity.rs @@ -0,0 +1,152 @@ +//! Tier 3: original C vs actual Rust FFI, using real field adapters and bmem. +//! NULL core and input aliasing old storage are outside the characterized C +//! domain. No intentional behavior differences. No new test threads. +use obs_core::ffi::set_locale::obs_set_locale; +use proptest::prelude::*; +use proptest::test_runner::{Config, TestRunner}; +use std::ffi::{CString, c_char}; + +unsafe extern "C" { + fn oracle_set_locale_reset(order: *const u8, count: u32, callbacks: u32, mutate: bool); + fn oracle_set_locale_step(rust: bool, locale: *mut c_char, out: *mut u64) -> usize; + fn oracle_set_locale_finish(); + fn oracle_set_locale_layout(out: *mut usize); +} +fn run( + rust: bool, + order: &[u8; 6], + count: u32, + callbacks: u32, + mutate: bool, + steps: &[Option>], +) -> Vec> { + // Reference the real shim explicitly as well as through the C fixture. + let _entry = obs_set_locale; + // SAFETY: order contains six unique valid indices; count <= 6. Each input + // has at most 64 non-NUL bytes and is mutable, live, and independent of the + // old locale. The fixture writes <= 114 u64s and frees its owned locale. + unsafe { + oracle_set_locale_reset(order.as_ptr(), count, callbacks, mutate); + let mut result = Vec::new(); + for step in steps { + let mut input = step + .as_ref() + .map(|bytes| CString::new(bytes.clone()).unwrap().into_bytes_with_nul()); + let ptr = input + .as_mut() + .map_or(std::ptr::null_mut(), |bytes| bytes.as_mut_ptr().cast()); + let mut state = [0u64; 128]; + let n = oracle_set_locale_step(rust, ptr, state.as_mut_ptr()); + result.push(state[..n].to_vec()); + } + oracle_set_locale_finish(); + result + } +} +fn compare(order: &[u8; 6], count: u32, callbacks: u32, mutate: bool, steps: &[Option>]) { + let expected = run(false, order, count, callbacks, mutate, steps); + let actual = run(true, order, count, callbacks, mutate, steps); + assert_eq!( + actual, expected, + "order={order:?}, count={count}, callbacks={callbacks}, mutate={mutate}, steps={steps:?}" + ); + // Pin the snapshot semantics in addition to comparing both sides. + for (state, step) in actual.iter().zip(steps) { + assert_eq!(state[0], u64::from(step.is_some())); + assert_eq!(state[1], u64::from(step.is_some())); + let event_len = state[2] as usize; + for event in state[3..3 + event_len].as_chunks::<4>().0 { + assert!(event[0] < 6, "disabled-list callback must not run"); + assert_eq!(&event[1..], &[1, 1, u64::from(step.is_some())]); + } + if let Some(bytes) = step { + assert_eq!( + &state[3 + event_len..3 + event_len + bytes.len()], + bytes + .iter() + .map(|byte| u64::from(*byte)) + .collect::>() + ); + } + } +} +#[test] +fn original_c_ownership_order_null_and_mutated_links() { + // Allocation counters are process-wide: isolate this case in the existing + // category executable instead of racing other tests or adding a binary. + const CHILD: &str = "OBS_SET_LOCALE_PARITY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + &format!( + "{}::original_c_ownership_order_null_and_mutated_links", + module_path!().split_once("::").unwrap().1 + ), + ]) + .env(CHILD, "1") + .status() + .unwrap(); + assert!(status.success()); + return; + } + // SAFETY: this isolated child has no other bmem users. + let baseline = unsafe { obs_util::ffi::bmem::bnum_allocs() }; + let steps = [ + Some(b"en-US".to_vec()), + Some(b"a-much-longer-replacement-locale".to_vec()), + Some(vec![]), + None, + None, + Some(b"fr-FR".to_vec()), + Some(b"fr-FR".to_vec()), + None, + ]; + for count in [0, 1, 6] { + for callbacks in [0, 1, 0x7f, 0x13] { + for mutate in [false, true] { + compare(&[5, 2, 3, 0, 1, 4], count, callbacks, mutate, &steps); + } + } + } + let mut runner = TestRunner::new(Config { + cases: obs_c_oracle::parity::cases(256), + failure_persistence: None, + ..Config::default() + }); + runner + .run( + &( + any::<[u16; 6]>(), + 0u32..7, + 0u32..128, + any::(), + prop::collection::vec( + prop::option::of(prop::collection::vec(1u8..=255, 0..65)), + 1..17, + ), + ), + |(keys, count, callbacks, mutate, steps)| { + let mut order = [0, 1, 2, 3, 4, 5]; + order.sort_by_key(|index| keys[usize::from(*index)]); + compare(&order, count, callbacks, mutate, &steps); + Ok(()) + }, + ) + .unwrap(); + // SAFETY: all fixture-owned strings were freed and the child is isolated. + assert_eq!(unsafe { obs_util::ffi::bmem::bnum_allocs() }, baseline); +} +#[test] +fn callback_layout_matches_real_c_header() { + let mut layout = [0usize; 2]; + // SAFETY: the oracle writes two size_t values measured from the C header. + unsafe { oracle_set_locale_layout(layout.as_mut_ptr()) }; + assert_eq!( + layout, + [ + size_of::(), + align_of::() + ] + ); +} diff --git a/test/cmocka/set-locale-link-support.c b/test/cmocka/set-locale-link-support.c new file mode 100644 index 0000000000..ddd2759e0b --- /dev/null +++ b/test/cmocka/set-locale-link-support.c @@ -0,0 +1,2 @@ +/* Demand-link the real locale adapter; fixture-owned cores take precedence. */ +#include "libobs/obs-set-locale-fields.c.h" diff --git a/test/cmocka/tests.d/video_info_query_link_support.cmake b/test/cmocka/tests.d/video_info_query_link_support.cmake index 8193568b98..07a2ce283e 100644 --- a/test/cmocka/tests.d/video_info_query_link_support.cmake +++ b/test/cmocka/tests.d/video_info_query_link_support.cmake @@ -9,6 +9,7 @@ function(_video_info_query_link_support) "${CMAKE_CURRENT_SOURCE_DIR}/core-state-link-support.c" "${CMAKE_CURRENT_SOURCE_DIR}/encoder-get-name-link-support.c" "${CMAKE_CURRENT_SOURCE_DIR}/output-interleave-name-link-support.c" + "${CMAKE_CURRENT_SOURCE_DIR}/set-locale-link-support.c" "${CMAKE_CURRENT_SOURCE_DIR}/encoder-video-tex-active-fields-link-support.c" "${CMAKE_CURRENT_SOURCE_DIR}/encoder-video-tex-active-mix-link-support.c" "${CMAKE_CURRENT_SOURCE_DIR}/source-audio-capture-callback-link-support.c"