Skip to content

libobs: Snapshot contexts during enumeration - #730

Merged
zackees merged 2 commits into
obs-rust:masterfrom
chriscoveries:fix/obs-enum-outputs-removal
Oct 14, 2026
Merged

zackees merged 2 commits into
obs-rust:masterfrom
chriscoveries:fix/obs-enum-outputs-removal

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

obs_enum_outputs(), obs_enum_encoders() and obs_enum_services() read freed memory when the callback drops the last reference to the entry it was handed. That is the normal way to release an object you own, for example obs_output_release() on an output found while enumerating. The walk then reads next from the destroyed context: ASan reports a heap-use-after-free in obs_enum. Without sanitizers the result depends on what the freed memory holds; in our macOS runs the stale next reads as NULL, so releasing the first entry silently ends the walk after one visit. Separately, obs_enum_encoders() hands the callback an encoder that is already being destroyed (refcount 0, still listed). Any plugin or frontend code that enumerates these lists can trigger the first bug. The second needs an enumeration that runs while an encoder's destroy is in progress, on another thread or from a log handler.

Fixes: TBD

Root cause

On master (54435f0c2), obs_enum() (libobs/obs.c:1920-1940) holds the list mutex and does:

while (context) {
	if (!enum_proc(param, context))
		break;
	context = context->next;
}

Nothing holds a reference on context across enum_proc. If the callback drops the last reference, obs_*_destroy runs inside the callback. The list mutex is recursive, so the unlink succeeds and the context is freed. context->next (:1936) is then read from freed memory.

The walk also visits contexts that are being destroyed. obs_encoder_destroy() logs "encoder '%s' destroyed" (libobs/obs-encoder.c:475) and tears the encoder down while it is still on the encoder list at refcount 0. It is unlinked only at obs-encoder.c:491 (obs_context_data_free). An enumeration in that window is handed the dying encoder.

Fix

At GREEN 21c91c0a5b1c7baf1ee2213632230348ef1a612d, only libobs/obs.c changes:

  • obs_enum() (libobs/obs.c:1957-1998) now takes a referenced snapshot. Under the list mutex it calls get_ref on every listed entry and keeps the ones that succeed (:1974-1980). An entry whose get_ref fails is already at refcount 0 and being destroyed, so it is skipped (:1977).
  • It then drops the mutex. For each snapshot entry it takes the list mutex again, runs the callback, and drops the mutex (:1984-1993). The callback still runs under the list mutex, as before. Returning false still stops the walk (:1991-1992).
  • After the walk it releases every snapshot reference, outside the list mutex (:1995-1997). An entry released during the walk is destroyed there, after the last callback, not inside its own callback.
  • Typed get_ref/release wrappers for outputs, encoders and services (:1920-1951) are passed in by obs_enum_outputs/encoders/services (:2024-2040). obs_enum() is static, and these three are its only users.

This is not the same pattern as obs_enum_sources() (:1864) or obs_canvas_enum_scenes() (:1892). Those hold one reference per item and release it under the list mutex right after that item's callback. This change holds a reference on every entry for the whole walk, drops the list mutex between items, and runs any final destroy after the walk, outside the mutex.

Alternatives:

  • Option A (smallest, not chosen): one reference per item under the held mutex. Keep the list mutex for the whole walk. For each entry, call get_ref (skip it on NULL), run the callback, read next, then release the entry. About six changed lines and no allocation, and the walk stays atomic against inserts. Only the current entry's destroy is deferred, to just after its callback. The cost is that a final release runs obs_*_destroy under the list mutex. For outputs that destroy stops the output, waits for it to stop and joins its capture thread (libobs/obs-output.c:313-318), so every other user of the list mutex (create, obs_get_output_by_name, other enumerations) waits for it. master already does that whenever a callback drops the last reference.
  • Option B (this PR): referenced snapshot, release after the walk. No destroy runs under the list mutex. The costs are an allocation per walk, a walk that is no longer atomic against inserts, and destroys that can move to the enumerating thread (see Compatibility & risk). Chosen because it keeps the potentially blocking output destroy out of the list mutex. The maintainer may prefer A; both fix the use-after-free and both skip dying entries.
  • Snapshot weak references, upgrade each one just before its callback: rejected. It still needs a strong reference across each callback, so it still moves the final destroy, and it adds a weak-reference allocation per entry.

Evidence

Branch fix/obs-enum-outputs-removal on the fork, two commits on 54435f0c2:

  • RED, tests only: 45be6c4adbbfcb7ab5198f34b3666d0eed2f4e9e "libobs: test context release during enumeration (RED)"
  • GREEN, the fix: 21c91c0a5b1c7baf1ee2213632230348ef1a612d "libobs: snapshot contexts during enumeration (GREEN)"

The test is test/cmocka/test_obs_enum_outputs_removal.c, registered in test/cmocka/tests.d/test_obs_enum_outputs_removal.cmake (not on Windows, because each case runs in a fork()ed child with a 30 s alarm). It has 8 cases. The six release cases create 3 objects of one kind, and the callback releases the owner reference of the first or the last visited one. Through weak references taken at creation, each case checks that the released object is still alive inside its own callback, that exactly that one object is destroyed once the walk returns, and that all 3 are destroyed after the owners release the rest.

Case What it pins
test_output_release_first / _last release the first / last visited output inside the callback
test_encoder_release_first / _last the same for obs_enum_encoders
test_service_release_first / _last the same for obs_enum_services
test_output_early_stop returning false stops after 1 visit; the snapshot references are still dropped
test_encoder_skips_dying a log handler that sees "encoder '%s' destroyed" enumerates encoders, so the walk runs while the released encoder is listed at refcount 0. The callback must see the live encoder once, never the dying one, and never NULL. The handler it replaced is restored afterwards.

test_encoder_skips_dying relies on that log format string, which is a stable literal in obs_encoder_destroy(); a comment in the test says so. If the format changes, the case fails with "destroy log seen 0 times" rather than passing silently. It also relies on obs_encoder_destroy() logging that line before it unlinks the encoder from the list. If that order were ever swapped, the case would pass without exercising the dying-encoder state, and no public API can check the order without a test hook. The test needs no threads and no sleeps. With ENABLE_RUST_LIBOBS=ON, base_get_log_handler/base_set_log_handler are the Rust port, but blogva stays in C (libobs/util/base-variadic.c:101-108) and passes the format string to the handler unchanged, without holding a lock, so the case works the same way in both lanes.

Local runs: macOS arm64, CMake Xcode generator, RelWithDebInfo, ENABLE_RUST_LIBOBS=OFF, in two configurations. The sanitizer flags were added locally; CI builds with the repo's own flags.

  • ASan/UBSan (local -fsanitize=address,undefined -fno-omit-frame-pointer)
  • plain (no sanitizers)

RED on master, both builds: 7 of 8 cases fail. The six release cases fail on object destroyed inside the callback that released it. That check reads a weak reference before the walk touches freed memory, so the plain build fails without depending on what the freed memory holds. Under ASan the same six report heap-use-after-free in obs_enum. test_encoder_skips_dying fails on callback was handed the encoder being destroyed (1 times). test_output_early_stop passes on master by design: it releases nothing, and it exists to kill the early-stop mutants below.

Plain build, master (identical in 20 of 20 runs):

[ RUN      ] test_output_release_first
visited 1 objects, expected 3
object destroyed inside the callback that released it
outputs, release first visited failed
[  FAILED  ] test_output_release_first
[ RUN      ] test_output_release_last
object destroyed inside the callback that released it
outputs, release last visited failed
[  FAILED  ] test_output_release_last
[ RUN      ] test_output_early_stop
[       OK ] test_output_early_stop
...
[ RUN      ] test_encoder_skips_dying
callback was handed the encoder being destroyed (1 times)
encoders, enumerate during destroy failed
[  FAILED  ] test_encoder_skips_dying
[==========] tests: 8 test(s) run.
[  PASSED  ] 1 test(s).
[  FAILED  ] tests: 7 test(s), listed below:

The encoder and service release cases fail with the same messages as the output ones. ASan build, master: the same 7 cases fail, and the six release cases each print one report:

==68331==ERROR: AddressSanitizer: heap-use-after-free on address 0x62d000050500 at pc 0x00010305ab38 bp 0x00016d909680 sp 0x00016d909678
    #0 0x00010305ab34 in obs_enum obs.c
    #1 0x00010305ab34 in obs_enum_outputs obs.c:1968

(The freeing frame is obs_output_release obs-output.c:3132, called from the test's callback.)

GREEN, both builds: 8 of 8 pass.

[==========] tests: Running 8 test(s).
...
[       OK ] test_encoder_skips_dying
[==========] tests: 8 test(s) run.
[  PASSED  ] 8 test(s).

The plain GREEN build passed in 20 of 20 runs.

A third local build, plain with ENABLE_RUST_LIBOBS=ON (Rust log-handler port linked, C base.c not built), gives the same results: master fails the same 7 cases, including test_encoder_skips_dying with "callback was handed the encoder being destroyed (1 times)", and GREEN passes 8 of 8.

Mutation check: each mutant was applied to GREEN's obs.c, built with ASan/UBSan, and run against the committed test. The if (ref) mutant was also killed in the plain OFF build and in the ON build.

Mutant Result Failing cases
if (ref) guard removed (:1977), so a failed get_ref pushes NULL killed test_encoder_skips_dying ("callback was handed NULL")
early stop ignored (if (!keep_going) break; removed) killed test_output_early_stop
early stop returns before the release loop (break → return) killed test_output_early_stop
release loop removed (snapshot references leak) killed the six release cases and test_output_early_stop
obs_enum_outputs uses the old walk killed both output release cases (heap-use-after-free)
obs_enum_encoders uses the old walk killed both encoder release cases (heap-use-after-free) and test_encoder_skips_dying
obs_enum_services uses the old walk killed both service release cases (heap-use-after-free)

Real runs: the full app was not run for this change. An independent review ran a standalone stress probe against GREEN (one thread enumerating all three lists while another creates and releases outputs, encoders and services, 5 s): over 4.3 million rounds under ASan and 6.5 million in a plain build, no NULL callback and no ASan report. That is liveness only, not a proof; TSan was not run. master was not run on Linux.

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

Compatibility & risk

  • C API/ABI: no change. No new exports, and no Rust symbol or override exists for these functions or the reference helpers. obs.c is compiled in both Rust lanes, so ENABLE_RUST_LIBOBS OFF and ON run the same code.
  • Behaviour changes:
    • Objects released during a walk are destroyed after the walk returns, outside the list mutex, possibly on the enumerating thread. That includes a final release made by another thread during the walk. For outputs that destroy stops the output and joins its capture thread, so it can run on, for example, the obs-websocket request thread.
    • "Gone after obs_enum_* returns" still holds. "Gone right after the release, inside the same callback" no longer does: a callback that releases an object and then looks it up by name, or recreates it under a hardware-session limit, within one walk, now sees it still alive. The test pins this.
    • Entries created during the walk are not visited.
    • Entries already being destroyed (refcount 0) are skipped. master handed them to the callback.
    • An entry whose owner released it earlier in the walk is still visited, because the snapshot keeps it alive. master skipped it after unlinking. The memory is valid, but the object is one its owner has already released.
    • The callback still runs under the list mutex, as before.
  • Lock order: under the list mutex the walk only takes references and appends to the snapshot, as get_context_by_name() does. The release loop holds no list mutex, so there is no new lock-order edge inside libobs. An external caller that calls obs_enum_* while holding its own lock now runs any final obs_*_destroy under that lock. If a destroy-path callback (an output's stop/destroy, a signal handler) takes the same lock, that is a new deadlock. No in-tree caller holds a lock.
  • Shutdown: a walk running concurrently with obs_shutdown() was unsafe before for encoders and is still unsupported. Because the list mutex is now dropped between items, it is now also unsafe for outputs and services.
  • In-tree consumer: obs-websocket's GetOutputList (src/utils/Obs_ArrayHelper.cpp:385 in the plugins/obs-websocket submodule) is the one in-tree caller of these functions. Its callback only reads properties and never releases, so it is unaffected functionally. If the frontend drops its last reference to an output during the walk, that output's destroy now runs on the websocket request thread after the walk instead of on the frontend thread, so the request takes longer.
  • Platforms not tested locally: Windows (the test is not registered there) and Linux (not run locally; relies on upstream PR CI).

How this was tested

  • RED → GREEN: test_obs_enum_outputs_removal was built locally on macOS arm64 (CMake Xcode, RelWithDebInfo, Rust OFF), once with local -fsanitize=address,undefined and once without sanitizers, plus a plain ENABLE_RUST_LIBOBS=ON build. On master 7 of 8 cases fail in all three builds (20 of 20 identical runs in the plain OFF build); on this branch all 8 pass in all three. Seven mutants of the fix are each killed by the committed test.
  • 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: not applicable; the full app was not run. A standalone stress probe was run against the fix instead (see Evidence).

Status

Status: draft. Opened so upstream PR CI can run it. Branch pushed to the fork at 21c91c0a5b1c7baf1ee2213632230348ef1a612d.


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 marked this pull request as ready for review October 14, 2026 23:10
@zackees
zackees self-requested a review as a code owner October 14, 2026 23:10
@zackees
zackees merged commit c4efec3 into obs-rust:master Oct 14, 2026
22 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