Skip to content

libobs: Check pthread init and thread start results with != 0 - #2163

Merged
zackees merged 2 commits into
obs-rust:masterfrom
rdoupe:fix/pthread-init-checks
Oct 24, 2026
Merged

zackees merged 2 commits into
obs-rust:masterfrom
rdoupe:fix/pthread-init-checks

Conversation

@rdoupe

@rdoupe rdoupe commented Oct 24, 2026

Copy link
Copy Markdown
Collaborator

Fixes #2152

What and why

pthread functions return 0 or a positive error number, never a negative one. libobs checked some of them, and one os_event_init() result that carries their error, with < 0, so these failures were never caught:

  • os_event_init() (util/threading-posix.c.h): a failed pthread_mutex_init() or pthread_cond_init() was ignored, and it returned 0 with an event whose lock was not initialized.
  • obs_context_data_init_wrap() (obs.c.h): a failed init of the rename cache mutex was ignored, so the source, output, encoder, service or canvas was created around it.

The same-pattern survey of libobs, plugins, frontend, shared and deps found three more in libobs, fixed here too:

  • obs_output_create() (obs-output.c.h) checks os_event_init() for its reconnect stop event with < 0. Once os_event_init() reports the failure, this check would let the output be created without that event. The test shows it: with only the two fixes above, obs_output_create() returned an output whose reconnect_stop_event is NULL.
  • output_reconnect() (obs-output.c.h) checks pthread_create() with < 0. When the reconnect thread did not start, the output stayed "reconnecting" with no thread.
  • os_inhibit_sleep_set_active() (util/platform-nix-inhibit.c.h, the fallback without a portal or session D-Bus inhibitor) checks pthread_create() with < 0. It reported success with no thread, and deactivating it later would join a thread that never started.

All five now check != 0. The error paths that follow are unchanged.

Second bug, found by the test: with the rename cache check fixed, obs_source_create() crashed instead of returning NULL. obs_context_data_init() frees and zeroes the context on failure, and obs_source_create_internal() then calls obs_source_destroy() on a context that was never added anywhere:

  • obs_context_data_remove_name() ran HASH_DELETE with the context's zeroed hash handle. With no public sources it dereferenced NULL. With some, it would have freed the public source table.
  • The deferred destroy called obs_context_wait(), which locked the context's list mutex pointer. That pointer is NULL because the context was never inserted.

Both now return early for a context that was never added (hh.tbl / mutex still NULL). This path was already reachable before this PR, when a source's signal handler failed to initialize.

Platforms: the rename cache, output and context fixes apply everywhere (w32-pthreads also returns positive error numbers). os_event_init() and the inhibitor are POSIX and Linux code. On glibc these inits practically never fail, so this is a robustness fix for resource exhaustion. Upstream has the same code.

Hybrid libobs: its os_event_init() (rust/obs-util/src/ffi/threading.rs, platform/unix/event.rs) is built on std::sync::{Mutex, Condvar} and calls no pthread init, so it cannot fail this way. The RED expectations for the event cases cannot fail on the hybrid. There the test checks that the event still works and that nothing leaks, and it passes. The hybrid's Rust inhibitor already reported a failed std::thread start (that goes through pthread_create()), so that case passes on the hybrid in RED as well. The context, output reconnect event and reconnect thread code is C on all three builds.

Test: test_pthread_init_failures (new, Linux only). It interposes pthread_mutex_init(), pthread_cond_init(), pthread_mutex_destroy() and pthread_create(), which the executable exports through link_options: -Wl,--export-dynamic-symbol=... as test_canvas_flags does. Each interposer fails the Nth call on the test's own thread and records the object it was given, so each case fails exactly the init it targets:

  • os_event_init() (auto and manual) with the mutex init failing, then with the cond init failing: non-zero return, out-pointer unchanged, bnum_allocs() unchanged. On the cond failure, the mutex that was initialized is the one destroyed.
  • obs_source_create() and obs_source_create_private() of a registered test input type, with only the first mutex init failing. A successful create first checks that this init is &source->context.rename_cache_mutex. The create must return NULL and allocate nothing.
  • obs_output_create() with only its last pthread_cond_init() failing. A successful create first checks that this init belongs to output->reconnect_stop_event. The create must return NULL and allocate nothing.
  • obs_output_signal_stop(OBS_OUTPUT_DISCONNECTED) with pthread_create() failing: the output must not stay reconnecting.
  • os_inhibit_sleep_set_active(true) with pthread_create() failing must return false. This case runs first, with DBUS_SESSION_BUS_ADDRESS pointed at nothing while the inhibitor is created, so the inhibitor takes the thread fallback. A failed bus connection is not cached.

It is a new test rather than part of test_threading. test_threading is cross-platform and runs without obs_startup(), while these interposers are Linux-only, replace the symbols for the whole executable, and need obs_startup() (a display) for the context cases. libobs and libobs-c-reference call the interposed functions through the PLT. The interposers reached them on all three builds: each case checks its call count.

RED → GREEN

  • RED commit: 28a5b3b (test only; its RED runs were on the same commit before the rebase, f5fa571ec on af31b65).
    • libobs (C): 6/6 cases fail, through 5 assertions. The event cases see a 0 return (0 == 0) for both the mutex and the cond failure. The source and output creates return an object (created is not false). The output stays reconnecting (reconnecting is not false). The inhibitor reports success without its thread.
    • libobs-c-reference: the same 6/6.
    • Hybrid libobs: 2/6 fail (source rename cache, reconnect thread). 4 pass: the two event cases and the output event case report that the Rust event makes no pthread call, and the Rust inhibitor already returns false.
    • Between RED and GREEN, the C lane was also run with only the != 0 changes: the output event case failed until obs-output.c.h:240 changed. With that change, the source case segfaulted in obs_context_data_remove_name() and then in obs_context_wait(), which led to the second fix.
  • GREEN: 73d16b9 (rebased onto 187d815 over obs-output: Port the encoder size and info choices #2148 and libobs: Windows-only bmem, config-file and audio-io choices in self-guarded headers (#876) #2155, after which the new test, test_threading, test_task, test_canvas_flags, test_output_failed_start_encoders, test_output_start_twice and test_encoder_size_steps passed again on C and hybrid; before that 5b2619cd5 on fe75932; first run as 52f4270a7 on af31b65).
    • test_pthread_init_failures passes 6/6 on libobs, the hybrid libobs and libobs-c-reference.
    • LSan (LD_PRELOAD=liblsan.so, fast_unwind_on_malloc=0) on test_pthread_init_failures: RED on C and c-ref reports 598 bytes in 3 allocations. These are the inhibitor that the RED case deliberately leaves alive, because deactivating it would join a thread that never existed. The hybrid reports none. GREEN, on 52f4270a7 and again on 73d16b9: no leaks on any of the three.
    • Focused, on 52f4270a7: the new test plus every cmocka test that uses os_event_* (49 built per lane), on all three builds. 39 pass and 10 PipeWire tests exit 77 (skip, no PipeWire daemon) on each. Nothing fails. On 73d16b9: test_pthread_init_failures, test_threading, test_task, test_canvas_flags, test_audio_io, test_video_io, test_output_failed_start_encoders and test_output_start_twice all pass on all three.
    • Full ctest on 52f4270a7: libobs (C) 448/448, hybrid 462/462, 0 skipped. Each ran under a private Xvfb with -noreset and dbus-run-session, a fresh HOME, ulimit -c 0 and TMPDIR unset. The known flakes (test_deinterlace_2x_field_order is timing-sensitive (yadif 2x 60i into 60): startup underrun and load-induced hold #456, Flaky: real-time audio cmocka tests lose audio under machine load (test_vlc_playlist_gap, test_group_hide_transition_audio) #838) passed.
    • Exported symbols: 1766 on libobs, the hybrid libobs and libobs-c-reference, with identical sets (on both heads).
  • Real app (UI, protocol output or logging changes): N/A. The only new log lines are the existing "Failed to create reconnect thread" and "Failed to create screensaver inhibitor thread" warnings, now reached on a failure.

Checklist

  • Base is master (or the description starts with a Stacked: note)
  • I claimed the issue, or no one else has an open PR for it
  • Characterization test (if the unit had none), then RED, then GREEN commits (N/A for docs-only; a focused CI fix may push RED and GREEN together)
  • User-visible change: its line in docs/features.md is added or updated (not applicable: no user-visible change)
  • (Optional) Local gate passed and the pushed head is stamped; otherwise PR CI runs the full suite
  • Warning or flag changes (-W..., ratchets): built with scripting ON (PR CI builds no OBS app: run gh workflow run ci.yml --ref <branch> for the full builds) and cross-checked with clang and MSVC
  • Intentional differences from C listed in the parity test header and rust/README.md (ports)

Local gate on 52f4270a7: --test-diff origin/master (3362 passed, 4 skipped by the nextest profile), --lane lint and --lane cross passed. On 73d16b9, after the rebase: --test-diff origin/master passed again (3362 passed, 4 skipped), and so did clang-format.

Not fixed here (reported): several callers ignore the result of os_event_init() and then use the event:

  • obs_queue_task() with wait and obs_wait_for_destroy_queue() (obs.c.h);
  • buffered-file-serializer.c.h, which also ignores pthread_mutex_init() and pthread_create();
  • in plugins: mac-capture (several), obs-browser, ffmpeg-mux and rtmp-services' ingest refresh wait.

Before this PR, a failed init there gave a zeroed lock, which happens to work on glibc. Now the event pointer stays NULL, and the first wait would crash. These inits do not fail on glibc with default attributes. Checking those callers is a separate change. os_sem_wait(...) < 0 in shared/media-playback is correct: os_sem_wait() returns -1 on failure.

pthread functions return 0 or a positive error number. libobs checked
some of them with "< 0", so these failures were never caught:

- os_event_init() went on after a failed pthread_mutex_init() or
  pthread_cond_init() and returned 0 with an event whose lock was not
  initialized;
- obs_context_data_init() went on after a failed init of the rename
  cache mutex, so the object was created around it;
- obs_output_create() checks os_event_init() for its reconnect event
  with "< 0", so once that reports the failure, the output would be
  created without the event;
- output_reconnect() and os_inhibit_sleep_set_active() checked
  pthread_create() with "< 0": the output stayed "reconnecting" with no
  thread, and the inhibitor reported success and would later join a
  thread that never started.

test_pthread_init_failures interposes pthread_mutex_init(),
pthread_cond_init(), pthread_mutex_destroy() and pthread_create() for
its own thread, fails exactly the call it targets, and checks the
return, the out-pointer and bnum_allocs(). Linux only.

The hybrid libobs's Rust os_event_init() uses no pthread init, so its
event cases check that the event still works; its Rust inhibitor
already reports a failed thread start.

Refs obs-rust#2152
pthread functions return 0 or a positive error number, so the "< 0"
checks never caught a failure. os_event_init(), obs_context_data_init()
(rename cache mutex), obs_output_create() (reconnect event, now that
os_event_init() reports the failure), output_reconnect() and
os_inhibit_sleep_set_active() (pthread_create) now check "!= 0". The
error paths that follow are unchanged.

A source whose context fails to initialize then reaches
obs_source_destroy() with a context that was never added anywhere: its
zeroed hash handle made obs_context_data_remove_name() dereference or
corrupt the public source table, and the deferred destroy locked its
NULL list mutex in obs_context_wait(). Both now skip a context that was
never added. This path was already reachable when the source's signal
handler failed to initialize.

Fixes obs-rust#2152
@rdoupe
rdoupe requested a review from zackees as a code owner October 24, 2026 14:14
@zackees
zackees added this pull request to the merge queue Oct 24, 2026
Merged via the queue into obs-rust:master with commit 6b1e25b Oct 24, 2026
35 checks passed
zackees added a commit to obs-rust/obs-browser that referenced this pull request Oct 25, 2026
Since obs-rust/obs-studio#2163 a failed os_event_init() leaves the event
NULL. obs_module_load() now fails cleanly if either startup event cannot
be created, and ExecuteOnBrowser() returns without queueing a task that
would signal a missing event.

Fixes #4
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.

libobs: pthread init failures are checked with < 0 and never caught

2 participants