Skip to content

obs-util: Bound counted FFI string reads - #729

Merged
zackees merged 4 commits into
obs-rust:masterfrom
chriscoveries:fix/dstr-n-bounded-read
Oct 15, 2026
Merged

zackees merged 4 commits into
obs-rust:masterfrom
chriscoveries:fix/dstr-n-bounded-read

Conversation

@chriscoveries

Copy link
Copy Markdown
Contributor

Draft. Opened so upstream PR CI can run it. Our own CI is down, so this hasn't been through our usual CI runs: see our note on #699.

Problem

With ENABLE_RUST_LIBOBS=ON, astrcmp_n and astrcmpi_n scan past their n-byte limit before comparing, so a caller that provides exactly n readable bytes (no NUL) reads out of bounds. cf_literal_to_str has the same shape for a nonzero count: it measured a suffix after literal + count before parsing.

The real-world trigger: os_fread_utf8 (libobs/util/platform.c:192) passes its 3-byte stack buffer char bom[3] (platform.c:179) to astrcmp_n(bom, "\xEF\xBB\xBF", 3). We found that with ENABLE_RUST_LIBOBS=ON under ASan every libobs startup aborts there, since the buffer has no NUL. Tests that need libobs then skip silently and ctest still exits 0, so the abort is easy to miss. This PR fixes it.

Root cause

  • rust/obs-util/src/ffi/dstr.rs:149-151 (astrcmp_n) and :158-160 (astrcmpi_n) on upstream/master passed both arguments through opt_cstr (:112-118), which calls CStr::from_ptr and scans to NUL before the bounded comparison. The C implementation (libobs/util/dstr.c:57, :79) compares at most n bytes.
  • rust/obs-util/src/ffi/cf_tokenizer.rs:199 on upstream/master measured a suffix with CStr::from_ptr(literal.add(count)) for every count. The C implementation (libobs/util/cf-tokenizer.c:92) calls strlen(literal) only when count == 0; for a nonzero count that initial measurement does not exist.

Fix

The dstr FFI now feeds a lazy byte-pair reader to the shared comparator. It reads one pair at a time and stops at the first difference, NUL, or n; the core still compares through c_char, preserving the target C char ordering. For n == 0 it reads nothing, as in C.

cf_literal_to_str now forms a slice of exactly count bytes when the count is nonzero, and retains the NUL-terminated path for count == 0.

cf_literal_to_str details:

  • Fixed: the initial over-read. A nonzero count no longer triggers a scan past literal + count, so a buffer of exactly count bytes with no trailing NUL is accepted.

  • Output is byte-identical to C. An independent review compared the Rust FFI with the C oracle on 777,777 counted literals (quote + 0 to 5 bytes over " \ x 1 0 a space f ' 9 + quote, each with several non-NUL tails) and found 0 differences.

  • The one remaining difference is a read, not a result. C's loop tests *temp_src before temp_src < end (libobs/util/cf-tokenizer.c:110). Any escape that ends at the closing quote (not only \x and octal; the skip at :69 and :76 is one case) leaves temp_src at or past end, and C then reads one byte outside the counted span. The value is discarded because temp_src < end is already false. Rust does not read that byte: the safe core treats any index past the slice as NUL. strtoul (:68, :75) cannot leave the span, because it starts before the closing quote and the quote stops it.

  • Not changed: the C read itself. Making C test temp_src < end first and clamping the skips at :69 and :76 would change OFF-mode libobs and is a separate follow-up.

  • The safe-core doc comment on cf_literal_to_str in rust/obs-util/src/cf_tokenizer.rs says this.

  • Option A: fix only the two dstr comparators. Smaller, but leaves the independently reported counted-literal initial over-read.

  • Option B (implemented): fix both initial over-reads together and pin each with guard-page and cmocka regressions.

  • Alternative considered: copy counted inputs into temporary NUL-terminated buffers. Rejected because it adds allocation and still fails to honor the caller's exact span directly.

Evidence

Branch fix/dstr-n-bounded-read on the fork (two commits on upstream/master 35045319ee5c6a2afda129a0471850031233ad24):

  • RED, tests only: cc99e98e8f4f596a04cdcda02847be6393889235 "obs-util: test bounded counted-string reads (RED)".
  • GREEN, fix: 0f3bdf4024fd68035056a76a1cc8d4042d0f16e7 "obs-util: bound counted FFI string reads (GREEN)".

Tests, all in the RED commit:

  • Guard-page tests (unix): astrcmp_n_does_not_scan_past_n, astrcmpi_n_does_not_scan_past_n, cf_literal_to_str_respects_nonzero_count, cf_literal_to_str_escape_at_span_end_stays_in_bounds (the literal "a\" with count 4: the escape ends at the span end, so the core indexes at count). They fail on RED and pass on GREEN. A read past n or count crashes the test binary.
  • Fixed-value tests that pin both off-by-one directions through the C ABI, so detection never depends on a proptest seed or on a fault: astrcmp_n_compares_the_nth_byte and astrcmpi_n_compares_the_nth_byte ("abcd" vs "abce", n = 4, expect -1; catch a shim that compares only n - 1 bytes), and astrcmp_n_ignores_the_byte_after_n and astrcmpi_n_ignores_the_byte_after_n ("abcX" vs "abcY", n = 3, expect 0; catch a shim that compares n + 1 bytes). bounded_compare_with_zero_n_reads_nothing checks that n == 0 dereferences nothing.
  • Mutation check on the FFI shim, run locally on GREEN: with the bound changed to n - 1, astrcmp_n_compares_the_nth_byte and astrcmpi_n_compares_the_nth_byte fail (the guard-page tests alone still pass, which is why the fixed-value tests exist). With the bound changed to n + 1, astrcmp_n_ignores_the_byte_after_n and astrcmpi_n_ignores_the_byte_after_n fail, and the guard-page and zero-n tests crash. With the cf_literal_to_str slice changed to count + 1, cf_literal_to_str_escape_at_span_end_stays_in_bounds crashes with SIGBUS; cf_literal_to_str_respects_nonzero_count alone does not, because a plain literal never indexes at count, which is why the escape test exists. (Debug profile, which is the cargo test default; the optimizer elides the dead load in --release.)
  • C regressions: astrcmp_n_reads_only_n_bytes in test/cmocka/test_dstr_regressions.c and a counted-literal case in literal_to_str_test in test/cmocka/test_cf_lexer.c, both on exact, non-terminated allocations.

Local runs (macOS arm64, AppleClang, local flags). The Rust results are on RED cc99e98e8 and GREEN 0f3bdf402. The cmocka/ASan results are on the earlier RED 3106c6cb5 and GREEN bff884746; the later commits change only rust/obs-util/tests/cf_tokenizer_ffi_bounds.rs and a doc comment in rust/obs-util/src/cf_tokenizer.rs, not the C tests or any compiled code path:

  • Rust, cargo test -p obs-util --locked: RED fails (cf_tokenizer_ffi_bounds and dstr_ffi_bounds crash with SIGBUS/SIGSEGV on the over-read; all other obs-util targets pass); GREEN passes (dstr_ffi_bounds 7 passed, cf_tokenizer_ffi_bounds 2 passed, the rest unchanged; clippy -D warnings and cargo fmt --check clean).

  • cmocka test_dstr_regressions and test_cf_lexer, built with the repo's macos-ci preset plus a local -fsanitize=address -fno-omit-frame-pointer, Debug. ENABLE_RUST_LIBOBS=OFF: pass on RED. ENABLE_RUST_LIBOBS=ON on RED: both abort with an AddressSanitizer heap-buffer-overflow:

    ERROR: AddressSanitizer: heap-buffer-overflow ...
    #0 ... in strlen
    #1 ... in astrcmp_n
    #2 ... in astrcmp_n_reads_only_n_bytes test_dstr_regressions.c:69
    ... 0 bytes after 3-byte region ...
    
    ERROR: AddressSanitizer: heap-buffer-overflow ...
    #1 ... in cf_literal_to_str
    

    After GREEN, both tests pass with the Rust port OFF and ON. macOS ASan does not run LeakSanitizer, so leak detection was not exercised here.

  • Bounded-read audit: astrcmp_n and astrcmpi_n were the dstr comparison shims that pre-scanned; the other dstr ncopy/ncat shims use counted slices. cf_literal_to_str was the counted-literal pre-scan. The lexer validators already use c_bytes_limited, and UTF-8 shims use sized slices whenever their input size is nonzero. Other CStr conversions inspected in rust/obs-util/src/ffi accept NUL-terminated C-string inputs.

  • Fork CI: not run. Our self-hosted CI is down (see our note on #699), so this relies on upstream PR CI.

Compatibility & risk

No C API or ABI changes. Nonzero counts now bound the initial memory read as the C contract specifies; zero-count cf_literal_to_str continues to accept a NUL-terminated string. The Rust comparator retains the existing C char comparison semantics. cf_literal_to_str output is unchanged and identical to C; the only difference left is that C reads one discarded byte past the span for escapes that end at the closing quote and Rust does not (see Fix). Tested here on macOS arm64 only (local ASan and the guard-page tests); Linux was not run. Windows was not run, and the guard-page tests are cfg(unix).

Status

Status: draft. Opened so upstream PR CI can run it. Branch fix/dstr-n-bounded-read at 0f3bdf4024fd68035056a76a1cc8d4042d0f16e7.


How this was tested

  • RED → GREEN: guard-page and fixed-value Rust tests for astrcmp_n, astrcmpi_n and cf_literal_to_str in the test-only RED commit: the guard-page tests crash on RED and pass on GREEN. The C regression tests use exact 3-byte non-terminated allocations. Local macOS AppleClang builds use the macos-ci preset with an added local -fsanitize=address -fno-omit-frame-pointer (not a CI flag); with ENABLE_RUST_LIBOBS=OFF both C tests pass before and after the fix, and with it ON both fail on RED with the heap-buffer-overflow traces above and pass on GREEN. Mutation checks of the shim bound (n - 1 and n + 1) are described under Evidence.
  • Our own CI: not run. Our self-hosted CI is down (see our note on #699), so this relies on upstream PR CI.
  • Real runs: the full app was not run for this change. The libobs startup abort in os_fread_utf8 was observed in our own ASan runs with ENABLE_RUST_LIBOBS=ON; here it is covered by exact-span guard-page and ASan tests of the same astrcmp_n call shape.

Thank you to the obs-rust maintainers and contributors for building this project in the open. In the American spirit of free expression and individual independence, and with the principle of judging contributions on their merit alone, this PR is a small piece of what independent people can build when they come together.

@zackees

zackees commented Oct 14, 2026

Copy link
Copy Markdown
Member

The Rust Tests (ubuntu-26.04) failure is from the new test, not flakiness. Its rust-test lane fails to link obs-util's new dstr_ffi_bounds test for the Windows target (run 38590381446):

rust-lld: error: undefined symbol: base_default_log_handler   (obs_util::ffi::base::resolved_log)
rust-lld: error: undefined symbol: base_log_literal           (base_set_crash_handler)
rust-lld: error: undefined symbol: bcrash                     (bmalloc / brealloc)
rust-lld: error: undefined symbol: os_utf8_to_wcs_ptr         (platform::windows::sync::set_thread_name)
error: could not compile `obs-util` (test "dstr_ffi_bounds")

Other obs-util integration tests get these C symbols by linking obs-c-oracle (base-variadic.c, platform_conv_host.c). This test doesn't reference the oracle crate, so on that target nothing pulls those objects in. Adding use obs_c_oracle as _; (or whatever the sibling tests do) to tests/dstr_ffi_bounds.rs should fix it. Locally: uv run ci/local_gate.py --lane rust-test.

@zackees
zackees marked this pull request as ready for review October 14, 2026 23:11
@zackees
zackees self-requested a review as a code owner October 14, 2026 23:11
@zackees

zackees commented Oct 14, 2026

Copy link
Copy Markdown
Member

Updated from master and marked ready. The one failure is Rust Tests (ubuntu), in the rust-test lane's windows-gnu --no-run link of the new dstr_ffi_bounds test:

rust-lld: error: undefined symbol: blog / base_default_log_handler / base_log_literal / bcrash / os_utf8_to_wcs_ptr
error: could not compile `obs-util` (test "dstr_ffi_bounds")

The test pulls in obs-util's FFI shims, which call libobs C symbols that the test binary doesn't provide on x86_64-pc-windows-gnu. Have a look at how the other rust/obs-util/tests/*_ffi* / parity tests get those symbols: they either link obs-c-oracle (which supplies them), or they're gated to the hosts where they link. Doing the same here should fix it. Everything else is green, and I'll merge as soon as this passes.

The test didn't reference obs_c_oracle, so rust-lld couldn't resolve
blog, bcrash, base_default_log_handler, base_log_literal and
os_utf8_to_wcs_ptr in the rust-test lane.

Local-Gate: v1 tree=547ace1ff5ccf76d2bc5ca96385236eec6e56a0b secs=558 lanes=lint:run,rust-test:run,cross:run,tier2-linux:run
Ci-Attestation: {"at":1792022194,"gate":"rust/all/fmt","host":"linux-x86_64","key":"b9bdc4411bb2df21860fb54ea30f4951b43e6470210694e1c341f49fa1012e91","lane":"lint","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":115,"stamp":"a4013980dcb298139ed4916cf8b5db13","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"rust/x86_64-unknown-linux-gnu/clippy","host":"linux-x86_64","key":"b9bdc4411bb2df21860fb54ea30f4951b43e6470210694e1c341f49fa1012e91","lane":"lint","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":115,"stamp":"e4e85566205110ab44b20be2aed4269d","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"rust/x86_64-unknown-linux-gnu/test","host":"linux-x86_64","key":"60c24219512e61e2c3564d2c9ea696291abd8fabe9fe23e184e16e70391ec2e7","lane":"rust-test","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":129,"stamp":"a348a6851ce120cf4d7be3518cb91dd4","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"rust/x86_64-pc-windows-msvc/clippy","host":"linux-x86_64","key":"825a8cd298b0d16a8a5406195077a114a16a877a77107335caa3664c8bf33179","lane":"cross","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":126,"stamp":"61c3a9125f386f868775c5b87d1487d9","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"rust/x86_64-pc-windows-msvc/dylint","host":"linux-x86_64","key":"825a8cd298b0d16a8a5406195077a114a16a877a77107335caa3664c8bf33179","lane":"cross","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":126,"stamp":"dbf735f254f26852e5f81de35f37def7","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"rust/aarch64-apple-darwin/clippy","host":"linux-x86_64","key":"825a8cd298b0d16a8a5406195077a114a16a877a77107335caa3664c8bf33179","lane":"cross","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":126,"stamp":"40c2974587d4a0093bc2df3e06e89466","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"rust/aarch64-apple-darwin/dylint","host":"linux-x86_64","key":"825a8cd298b0d16a8a5406195077a114a16a877a77107335caa3664c8bf33179","lane":"cross","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":126,"stamp":"8abb6fc71ed98e7a894a9f052858a673","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"rust/x86_64-apple-darwin/clippy","host":"linux-x86_64","key":"825a8cd298b0d16a8a5406195077a114a16a877a77107335caa3664c8bf33179","lane":"cross","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":126,"stamp":"30297d94a9c0c41a259829d2deb957ad","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"rust/x86_64-apple-darwin/dylint","host":"linux-x86_64","key":"825a8cd298b0d16a8a5406195077a114a16a877a77107335caa3664c8bf33179","lane":"cross","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":126,"stamp":"a78caf104f4127056b930647e24c3baf","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
Ci-Attestation: {"at":1792022194,"gate":"cpp/linux-x64/tier2","host":"linux-x86_64","key":"81ba259fedf206a6bcf4a86db1ca4447603eb77e485d6a97fe55742f9ff2dcdb","lane":"tier2-linux","parents":["cf179b699fad20fdd176a603191110d5ea0eb6ea"],"secs":188,"stamp":"ce35d3b22379f3e4979a5fb82a40cf35","tree":"547ace1ff5ccf76d2bc5ca96385236eec6e56a0b","v":1,"via":"run"}
@zackees

zackees commented Oct 14, 2026

Copy link
Copy Markdown
Member

Pushed the link fix to your branch: use obs_c_oracle as _; in rust/obs-util/tests/dstr_ffi_bounds.rs, as cf_tokenizer_ffi_bounds.rs does. Red: uv run ci/local_gate.py --lane rust-test failed with could not compile obs-util (test "dstr_ffi_bounds"), undefined symbol: blog / bcrash. Green: the lane passes. Local gate stamped; queued for the merge queue.

@zackees
zackees enabled auto-merge October 14, 2026 23:56
@zackees
zackees added this pull request to the merge queue Oct 15, 2026
Merged via the queue into obs-rust:master with commit 18a20a3 Oct 15, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants