Repository navigation
libobs: Snapshot contexts during enumeration - #730
Merged
zackees merged 2 commits intoOct 14, 2026
Merged
Conversation
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.
Problem
obs_enum_outputs(),obs_enum_encoders()andobs_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 exampleobs_output_release()on an output found while enumerating. The walk then readsnextfrom the destroyed context: ASan reports a heap-use-after-free inobs_enum. Without sanitizers the result depends on what the freed memory holds; in our macOS runs the stalenextreads 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:Nothing holds a reference on
contextacrossenum_proc. If the callback drops the last reference,obs_*_destroyruns 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 atobs-encoder.c:491(obs_context_data_free). An enumeration in that window is handed the dying encoder.Fix
At GREEN
21c91c0a5b1c7baf1ee2213632230348ef1a612d, onlylibobs/obs.cchanges:obs_enum()(libobs/obs.c:1957-1998) now takes a referenced snapshot. Under the list mutex it callsget_refon every listed entry and keeps the ones that succeed (:1974-1980). An entry whoseget_reffails is already at refcount 0 and being destroyed, so it is skipped (:1977).:1984-1993). The callback still runs under the list mutex, as before. Returningfalsestill stops the walk (:1991-1992).:1995-1997). An entry released during the walk is destroyed there, after the last callback, not inside its own callback.get_ref/releasewrappers for outputs, encoders and services (:1920-1951) are passed in byobs_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) orobs_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:
get_ref(skip it on NULL), run the callback, readnext, 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 runsobs_*_destroyunder 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.masteralready does that whenever a callback drops the last reference.Evidence
Branch
fix/obs-enum-outputs-removalon the fork, two commits on54435f0c2:45be6c4adbbfcb7ab5198f34b3666d0eed2f4e9e"libobs: test context release during enumeration (RED)"21c91c0a5b1c7baf1ee2213632230348ef1a612d"libobs: snapshot contexts during enumeration (GREEN)"The test is
test/cmocka/test_obs_enum_outputs_removal.c, registered intest/cmocka/tests.d/test_obs_enum_outputs_removal.cmake(not on Windows, because each case runs in afork()ed child with a 30 salarm). 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.test_output_release_first/_lasttest_encoder_release_first/_lastobs_enum_encoderstest_service_release_first/_lastobs_enum_servicestest_output_early_stopfalsestops after 1 visit; the snapshot references are still droppedtest_encoder_skips_dying"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_dyingrelies on that log format string, which is a stable literal inobs_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 onobs_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. WithENABLE_RUST_LIBOBS=ON,base_get_log_handler/base_set_log_handlerare the Rust port, butblogvastays 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.-fsanitize=address,undefined -fno-omit-frame-pointer)RED on
master, both builds: 7 of 8 cases fail. The six release cases fail onobject 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 reportheap-use-after-freeinobs_enum.test_encoder_skips_dyingfails oncallback was handed the encoder being destroyed (1 times).test_output_early_stoppasses onmasterby design: it releases nothing, and it exists to kill the early-stop mutants below.Plain build,
master(identical in 20 of 20 runs):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:(The freeing frame is
obs_output_release obs-output.c:3132, called from the test's callback.)GREEN, both builds: 8 of 8 pass.
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, Cbase.cnot built), gives the same results:masterfails the same 7 cases, includingtest_encoder_skips_dyingwith "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. Theif (ref)mutant was also killed in the plain OFF build and in the ON build.if (ref)guard removed (:1977), so a failedget_refpushes NULLtest_encoder_skips_dying("callback was handed NULL")if (!keep_going) break;removed)test_output_early_stopbreak→return)test_output_early_stoptest_output_early_stopobs_enum_outputsuses the old walkobs_enum_encodersuses the old walktest_encoder_skips_dyingobs_enum_servicesuses the old walkReal 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.
masterwas 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
obs.cis compiled in both Rust lanes, soENABLE_RUST_LIBOBSOFF and ON run the same code.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.masterhanded them to the callback.masterskipped it after unlinking. The memory is valid, but the object is one its owner has already released.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 callsobs_enum_*while holding its own lock now runs any finalobs_*_destroyunder that lock. If a destroy-path callback (an output'sstop/destroy, a signal handler) takes the same lock, that is a new deadlock. No in-tree caller holds a lock.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.GetOutputList(src/utils/Obs_ArrayHelper.cpp:385in theplugins/obs-websocketsubmodule) 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.How this was tested
test_obs_enum_outputs_removalwas built locally on macOS arm64 (CMake Xcode, RelWithDebInfo, Rust OFF), once with local-fsanitize=address,undefinedand once without sanitizers, plus a plainENABLE_RUST_LIBOBS=ONbuild. Onmaster7 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.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.