Skip to content

bug: graphics math: 17 functions give a wrong result when dst overlaps an input #370

Closed

Description

@chriscoveries

Summary

libobs/graphics asks callers never to pass a dst that overlaps an input,
but nothing enforces it and the failure is silent: when a caller does overlap
them, the function returns a value that depends on the overlap rather than on
the inputs. An audit proved the
failing arrangements by direct measurement, re-verified under -O2 -fno-strict-aliasing, and found 17 functions with unsequenced read-write
hazards - 16 public or header-inline and 1 private helper
: 2 fail for
ordinary same-type whole-object aliases (quat_mul, calc_torque), 9 for
typed member overlap, 5 for same-address different-type storage, and the
private helper for a partially overlapping scratch buffer. 11 of them need no
cross-type cast to fail. Four further restrict inlines document the contract
rather than enforce it and are excluded from that count.

No caller in libobs, the frontend, the data layer or the plugins uses any
failing arrangement (whole-tree source search), so this is latent, not a live
defect. The reason to fix it anyway is that the requirement is undocumented in
every affected header and is silently violated the moment a new caller passes a
destination it also reads from. Two of the arrangements are reachable only
through libobs's own cast in quat_from_matrix3, and the private helper
(get_3x3_submatrix) has no aliased caller at all.

Affected functions

Function Location Failure
quat_mul libobs/graphics/quat.c:30 reads q1->w/q2->w after vec3_add cleared dst->w
quat_from_matrix3 libobs/graphics/quat.c:62 same, via the matrix3-to-matrix4 cast it forwards to
quat_from_matrix4 libobs/graphics/quat.c:67 reads matrix elements overwritten by earlier quaternion lanes
vec3_rotate libobs/graphics/vec3.c:37 reads m->y/m->z after storing dst->x
vec3_transform3x4 libobs/graphics/vec3.c:56 same
matrix3_scale libobs/graphics/matrix3.c:95 re-reads v for later rows after storing dst->x
matrix3_mirrorv libobs/graphics/matrix3.c:132 same
matrix3_mirror libobs/graphics/matrix3.c:124 reads p->dir/p->dist after storing the rows
plane_from_tri libobs/graphics/plane.c:22 reads v1 after writing and normalizing dst->dir
bounds_move libobs/graphics/bounds.c:24 re-reads v after storing dst->min
bounds_scale libobs/graphics/bounds.c:30 same
bounds_merge_point libobs/graphics/bounds.c:42 same
bounds_get_center libobs/graphics/bounds.c:83 re-reads b->min after storing dst
calc_torque libobs/graphics/math-extra.c:96 re-reads v1 after storing dst
polar_to_norm libobs/graphics/math-extra.c:58 re-reads polar->x after storing dst->x at the same address
gs_u8x4_to_float4 libobs/graphics/srgb.h:42 reads later input bytes after earlier float stores (same base)
get_3x3_submatrix libobs/graphics/matrix4.c:115 private; unreachable aliased today, fixed defensively

Three further functions are safe but only because they internally snapshot
their inputs, and the runtime cost of those copies is invisible at the call
sites (matrix4_transpose, quat_vec3, vec4_mul); four restrict inlines
(documenting a contract rather than enforcing it) were classified as
"safe taking restrict as contract" and are left alone.

Measured examples of the wrong results (from the audit's probes, -O2 -fno-strict-aliasing, real headers):

quat_mul:
nonaliased = {-0.25, 0.150000006, -0.230000019, 1.27999997}
dst==q1   = {-0.25, 0.150000006, -0.230000019, 0.560000002}

calc_torque:
nonalias=(7.5,0,0)
alias=(-5,0,0)

quat_from_matrix4, valid 90-degree rotation:
nonaliased   = {0, 0, 0.707106769, 0.707106769}
same-address = {0, 0, 0.353553385, 0.707106769}

How it is reached

Each row above reads at least one input lane that an earlier store has already
overwritten when dst shares storage with an input. The audit measured the
wrong result directly for each function; for example, quat_mul(&q, &q, &b)
produces a quaternion whose scalar part omits q.w * b.w, and
vec3_rotate(&m->y, &v, &m) uses a rotation matrix whose second row has
already been replaced. A function failing for one operand's alias may still be
safe for another - bounds.c calls vec3_transform3x4(&p, &p, m) safely - so
an aliased call alone is not automatically a bug; the failing arrangement per
function is what the table records.

Proposed fix

Three options, in the order I would take them.

Option A (proposed): make the functions alias-safe. Move each late read
ahead of the writes it races with, snapshotting into a local where the ordering
cannot be expressed otherwise. This is what the audit recommends and what the
Rust port already does: every shim in rust/obs-graphics reads its inputs in
full before writing dst, so the C currently disagrees with the Rust for
aliased calls. Each edit only reorders a read, so non-overlapping results are
bit-for-bit unchanged.

Risk: low. No in-tree caller overlaps, so no behavior change today; the edits
are local and mechanical. quat_from_matrix3's existing matrix3-to-
matrix4 cast must keep reading only the 3x3 block, which the fix preserves.

Test plan: a new test/cmocka/test_graphics_math_alias.c runs each function
twice (separate storage, then the overlapping arrangement) and asserts exact
equality. On unfixed master all 19 cases fail
([ PASSED ] 0 test(s). / 19 FAILED TEST(S)); with the fix all 19 pass
([ PASSED ] 19 test(s).). The two updated characterization tests fail
individually on the unfixed tree and pass with it. Rust parity tests add the
same arrangements, which also fail against the unfixed C.

Option B: document the constraint and add a debug assertion. Add the
"dst must not overlap an input" requirement to the affected headers and
assert it in debug builds. Cheaper, but it does not fix the wrong results for
callers that overlap, and it does not remove the C/Rust disagreement above;
used alone it leaves the Rust port as the only definition of correct.

Option C: nothing. The failures are latent and unreachable today.
Rejected: any future caller that overlaps gets a silent wrong answer, and the
Rust port and C disagree for those inputs, which defeats the parity checks that
protect the port.

Rejected alternative: adding restrict to the parameters instead. That
documents the constraint and lets compilers assume it, but it is undefined
behavior for an overlapping caller instead of a wrong value, and it would not
match the Rust.

Scope

One PR per the branch naming rules: fix/graphics-alias-safe. C fixes first
(RED commit, then GREEN), then the Rust shim and parity tests in lockstep, per
docs/rust-port/testing-policy.md. The public header srgb.h changes one
inline function's body only; no signature, layout or export changes anywhere,
so EXPORTED_FUNCTIONS.txt is unaffected (checked by Tier 2).

Note: upstream #338 and #352 ported plane.c and math-extra.c to
obs-graphics after the audit, so those two files now also have Rust shims.
Those ports deliberately reproduced the C aliasing bugs (plane_from_tri
detected v1 == &dst->dir and set dist = dir·dir; calc_torque stored the
scaled step and re-read v1), and their characterization tests pinned the
results as "Characterized, not endorsed". Option A therefore also removes the
two emulations and updates those two characterization tests, each of which now
asserts the aliased result equals the non-aliased one instead of a pinned
constant.

Test plan

  1. cmocka: new test_graphics_math_alias - 19 cases, all fail on master,
    all pass after the fix. Existing test_quat, test_vec2, test_vec3,
    test_vec4, test_matrix3, test_matrix4, test_video_matrices,
    test_math_extra, test_plane and test_bounds must keep passing (they
    do, with the two characterization values updated as described above).
  2. Rust: soldr cargo test -p obs-graphics in debug and release, including
    the new parity tests, which fail against the unfixed C oracle and pass
    after. mul_dst_aliases_q1, which pins the aliased C result, is replaced by
    mul_dst_aliases_input, which checks the aliased call against the
    non-aliased one.
  3. Fork CI on chriscoveries/obsrust-fork, all three jobs (tier2, gate, mac)
    green on the head: Tier 2 with ENABLE_RUST_LIBOBS OFF and ON, the full
    ctest suite and the exported-symbol parity diff.
  4. ./lint: clang-format 22.1.3, gersemi, rustfmt and clippy clean on the
    changed files.

Evidence

The measured wrong results are above. The PR carries the RED test commit first,
so the failing run is reproducible from the branch itself.

Activity

  1. chriscoveries commented on Oct 13, 2026

    @chriscoveries
    ContributorAuthor

    Claiming: part 1, the five ordinary same-type alias cases (bounds_move, bounds_scale, bounds_merge_point, bounds_get_center, plane_from_tri). PR follows.

  2. nathan-v commented on Oct 14, 2026

    @nathan-v
    Contributor

    Claiming: the remaining twelve alias cases (quat_mul, quat_from_matrix3, quat_from_matrix4, vec3_rotate, vec3_transform3x4, matrix3_scale, matrix3_mirrorv, matrix3_mirror, calc_torque, polar_to_norm, gs_u8x4_to_float4, get_3x3_submatrix). Part 1 stays with #423.

    1. RED: a cmocka test that runs each function on separate storage and on the overlapping arrangement and expects the two results to match. It fails on current master.
    2. GREEN: read every input before writing dst, in the C functions and in any Rust shim that still copies the overlap bug. Update characterization cases that pinned the old overlap result.
    3. ./lint, ./unittest (Linux Docker Tier 2 included), then the local-gate stamp. One PR to master today.

    Please add the claimed label; I cannot if triage is restricted.

  3. nathan-v commented on Oct 14, 2026

    @nathan-v
    Contributor

    The remaining twelve, plus get_3x3_submatrix, are in #680.

    calc_torque with dst == v1 now returns the separate-storage result. For v1 (10, 0, 0), v2 at the origin, torque 0.5, that is (5, 0, 0). The old characterized value was (-10, 0, 0). test_calc_torque_dst_aliases_v1 expects (5, 0, 0).

    get_3x3_submatrix stays static. It has no cmocka entry.

  4. chriscoveries commented on Oct 14, 2026

    @chriscoveries
    ContributorAuthor

    @nathan-v thanks for #680, that's the rest of this one done.

    Heads-up for you and everyone else: we're drowning in CI on our side and have stalled on nine issues we'd taken on, #482 through #490. I've released them all, and each one now has a comment linking our RED test and fix branch in case they save anyone time. They're yours, or anyone's, if you want them.

    @zackees, could you remove me as assignee on #484–#490? I don't have the rights to do it myself.

  5. zackees commented on Oct 14, 2026

    @zackees
    Member

    @chriscoveries thanks for releasing these and for leaving the RED test and fix branches. They'll save a lot of time.

    One likely cause of the CI pain: our builds go through a compile cache called Soldr, and it can't be mixed with bare cargo. Running plain cargo ... bypasses the cache (and can fight with the toolchain Soldr pins), so builds get slow and results can disagree with CI. Every build/test command should be soldr cargo ... (see AGENTS.md, "Use soldr cargo ..., never bare cargo").

    We're going to look at shipping a pre-tool hook that forces agents onto Soldr automatically, so this doesn't depend on the agent remembering the rule.

  6. zackees commented on Oct 14, 2026

    @zackees
    Member

    @chriscoveries follow-up: I looked at the Self-hosted CI runs on your fork (283 runs since 10-11, 109 failed). Most failures come from the runner environment, not your code:

    1. Soldr on the runner. Earlier runs fail with soldr: command not found. Recent ones fail with soldr: IO error: Permission denied (os error 13) in both the Rust tiers and Tier 2 (e.g. run 38490910321), right after Soldr detaches shared files in target/. Check ownership of ~/.soldr and the workspace target/ for the runner user. Soldr also warns the build volume is down to 8.4 GiB (< 10 GiB).
    2. Native Tier 2 has the wrong FFmpeg. tier2-native.sh builds against the host's libraries, and Debian's FFmpeg 7.1 fails libobs's configure: Found unsuitable version "7.1", but required is at least "8.0". Our ./unittest runs Tier 2 in Docker, where that's already handled.
    3. Merging upstream fails. Master has moved about 340 commits since your branches' base, so many runs stop at "ref does not merge cleanly with current upstream master".

    You don't need the fork CI at all. Run ./unittest, or the local gate from AGENTS.md (uvx --from git+https://github.com/zackees/ci.yml@1a970f01574447d681571ff3d0b8de56cb983dcc ci-lint local-gate run). Its stamp lets upstream CI skip the Linux unit-test jobs. Then open the PR and let our CI do the rest. If you keep the runner, fixing the permissions and disk space and running Tier 2 in Docker should clear most of the red.

    For the branches you released, #686 tracks rebasing them and landing them with your authorship kept. Your fixes looked solid from reading them.

  7. chriscoveries commented on Oct 14, 2026

    @chriscoveries
    ContributorAuthor

    Thanks, @zackees. Our lanes mostly use soldr cargo, but not always, so a pre-tool hook would help us too.

    Disk is our real limit, though. Soldr's embedded cache defaults to 5% of the filesystem, clamped to 40–200 GiB, and separate cache roots each get their own budget. The cheap Hetzner boxes we can afford have about 150 GB of disk, so that 40 GiB floor alone is over a quarter of the disk before any build or test output, and we don't know who has 500 GB of disk to spare for CI. Most of what we cleaned up wasn't build cache anyway: it was leaked test temp folders, stale git worktrees and runner work directories. There's more on #699.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions