Repository navigation
obs-util: dstr FFI appends edit the C buffer in place (#1297) - #1393
Merged
Merged
Conversation
…Rust side (#1297) The C ABI shims copy the whole C string into an owned Dstr and back for every append, so an 8-byte dstr_ncat onto a 4096-byte string allocates. New deterministic allocation-counting tests (as in #1389) require zero Rust-side allocations for dstr_ncat/cat_dstr/cat_strref/ncat_dstr and dstr_safe_printf; they fail now (2, 13 and 3 allocations). Tier 3 parity gains the aliasing cases: cat_dstr(d, d), ncat_dstr(d, d), ncat from inside d's own buffer and copy from inside it, with capacity compared after every step.
dstr_copy, dstr_ncat, dstr_cat_dstr, dstr_cat_strref, dstr_ncat_dstr, dstr_replace and dstr_safe_printf no longer copy the whole string into an owned Dstr and back. They grow the C buffer with dstr_ensure_capacity's rule and the same brealloc call, then memmove the new bytes and write len and the terminator. A source inside the destination buffer (cat_dstr(d, d), a pointer into d->array) is re-derived after a moving brealloc. dstr_replace runs on the buffer in place: same-length and shrinking replaces compact in place, a growing one grows the buffer once and rebuilds front to back. find_from uses a SIMD memchr for the first byte, and the replace value is measured once instead of per step. Medians (Rust/C): dstr/cat/128 114.98/53.14 -> 52.65/52.59 ns, dstr/cat/4096 242.43/115.70 -> 141.53/136.85 ns, dstr/safe_printf/128 241.80/142.47 -> 159.07/148.64 ns, dstr/safe_printf/4096 1963.8/331.27 -> 339.68/335.79 ns.
zackees
enabled auto-merge
October 18, 2026 04:35
zackees
disabled auto-merge
October 18, 2026 04:36
…acle off C UB (#1297) A source that points into the destination buffer (dstr_ncat/cat_strref with a pointer into dst->array, dstr_cat_dstr(d, d), dstr_copy from inside dst->array) is UB in C (memcpy from the freed pointer after brealloc, or overlapping memcpy). Rust finds the source again after the grow and memmoves it. Listed in the parity header and in rust/README.md. The parity ops now give only Rust the aliasing pointer, and C a private copy of the same bytes, so the oracle is never fed the UB case. NcatFromOwn now also covers the growing (moving) case on the Rust side.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1297. #1296's
dstr/safe_printfis now within the 1.10 bound too, so #1296 can close.Cause
rust/obs-util/src/ffi/dstr.rsran every shim throughwith():read()copied the whole C string into an ownedDstr(slice::from_raw_parts(..).to_vec()), andwrite()copied it back into a newbmallocbuffer. So an 8-bytedstr_ncatcopied the existing 128 or 4096 bytes twice and made a Rust heap allocation.dstr_safe_printfwent through the same round trip once per step (copy plus up to four replaces).Design
ensure_capacityis a direct port ofdstr_ensure_capacityfromdstr.h: samegrow_capacityrule and the samebrealloccall, socapacityand the allocator traffic match C.write_at(d, at, src, n)grows the buffer toat + n + 1,memmoves the bytes and setslenand the NUL. It backsdstr_ncat,dstr_cat_dstr,dstr_cat_strref(throughdstr_ncat),dstr_ncat_dstranddstr_copy.dstr_replaceanddstr_safe_printfedit the buffer in place. New safe core helpers insrc/dstr.rs:replace_planfinds the first match and the grown length,replace_in_placehandles same-length and shrinking replaces, andreplace_growgrows once, moves the tail to the end and rebuilds front to back.Dstr::replaceuses the same helpers, so Tier 1 covers them.find_fromnow finds the first byte with SIMDmemchr(new direct dependencymemchr = "2", already inCargo.lock).cstruses it too. The replace value is measured once instead of at each step. I triedmemmem::Finderfirst, but building the searcher cost more than the search for these short needles.with().SAFETY reasoning
unsafeblock has a SAFETY comment. Pointers come only from the caller'sdstr/strrefcontract, and the buffer only ever comes from thebmallocfamily.write_atchecks whethersrcpoints intod's own buffer ([array, array + capacity)). If it does, it re-derivessrcfrom the possibly moved buffer at the same offset afterbrealloc.breallockeeps the old contents, and the copy is amemmove, sodstr_cat_dstr(d, d),dstr_ncat_dstr(d, d, n)anddstr_ncat(d, d->array + k, n)are all defined. In C the last one is a use-after-free when it reallocs.dstr_cat_dstranddstr_ncat_dstrreadsrc'sarrayandlenbefore touchingdst, becausesrcmay bedst.array/lenwith no other live reference. A grow re-readsarrayafterensure_capacity.#[cfg]/libc additions (platform boundary unchanged).Intentional difference from C (listed in the
dstr_parity.rsheader andrust/README.md)A source that points into the destination's own buffer is undefined behavior in C. This covers
dstr_ncatanddstr_cat_strrefwith a pointer intodst->array,dstr_cat_dstr(d, d), anddstr_copyfrom insidedst->array. Cbreallocs and thenmemcpys from the freed pointer, or copies overlapping ranges. Rust takes the offset before the grow, finds the source again in the new buffer andmemmoves it. The result is the source bytes as they were before the call. The parity test never sends this case to the C oracle: Rust gets the aliasing pointer, and C gets a private copy of the same bytes. Both sides are then compared on bytes, terminator,lenandcapacity.dstr_ncat_dstr(d, d, n)is defined in C, so both sides get the aliasing pointer there.New direct dependency:
memchr = "2"obs-utilnow depends onmemchrdirectly. It was already inCargo.lockas a transitive dependency (2.8.3), so no new crate enters the build. It provides the SIMD first-byte scan infind_fromandcstr. C uses libcstrstr/strlen, and the scalar Rust scan was the remainingsafe_printfgap: a byte loop over the 4 KiB value. I triedmemmem::Finderfirst, but building the searcher cost more than the search for these short needles.Parity coverage (Tier 3,
tests/strings/dstr_parity.rs)New ops are compared against the C oracle after every step. The comparison covers bytes, terminator,
lenandcapacity:CatSelf:dstr_cat_dstr(d, d). Only Rust gets the aliasing pointer.NcatDstrSelf:dstr_ncat_dstr(d, d, len)NcatFromOwn:dstr_ncat(d, d->array + start, len), including lengths that make the buffer move. Only Rust gets the aliasing pointer.CopyFromOwn:dstr_copy(d, d->array + start). Only Rust gets the aliasing pointer.Existing ops already cover a NULL dstr, a NULL or empty source, and embedded NULs. The suite also passed with
PROPTEST_CASES=20000.RED/GREEN evidence
RED (
e61ace233, tests only):tests/strings/dstr_alloc.rs::ffi_in_placeneeds zero Rust-side allocations. On master the tests fail:ncat_onto_4096_with_spare_capacity_does_not_allocate: left 2, right 0appends_that_grow_do_not_allocate_rust_side: left 13, right 0safe_printf_does_not_allocate_rust_side: left 3, right 0The C-side
bmalloc/breallocis not counted; it stays what C does.GREEN (
aa6647cd6):soldr cargo test -p obs-utilpasses and./lintgives rc=0.Benchmarks
soldr cargo bench -p obs-c-oracle --bench port_comparison -- 'dstr/(cat|safe_printf)/', criterion medians, same machine.On an earlier after-run,
dstr/replacewas 918 ns (Rust) vs 1188 ns (C) at 128 and 32.4 µs vs 86.4 µs at 4096, so Rust is still faster there. The machine was shared (load average around 10 to 17), and the C medians moved by up to ±15% between runs.