Skip to content

frontend: Guard against a freed core on shutdown in 3 sites - #13906

Closed
zackees wants to merge 1 commit into
obsproject:masterfrom
zackees:fix/null-guard-obs-enter-graphics-shutdown
Closed

zackees wants to merge 1 commit into
obsproject:masterfrom
zackees:fix/null-guard-obs-enter-graphics-shutdown

Conversation

@zackees

@zackees zackees commented Sep 17, 2026 •

Copy link
Copy Markdown

Reproduced an OBS crash in NixOS, this PR fixes it.

Description

OBSBasicPreview's destructor releases its GL/Vulkan resources by calling
obs_enter_graphics() unconditionally. If that destructor runs after
obs_shutdown() has already freed the global obs_core and set obs to
NULL, obs_enter_graphics() dereferences the freed pointer and crashes.

This lands as a single commit (squashed per review) with three parts:

  1. libobs: obs_enter_graphics()/obs_leave_graphics() only checked
    obs->video.graphics, never obs itself. Add the missing null check.
  2. frontend: OBSBasicPreview::~OBSBasicPreview() skips its whole
    graphics-resource cleanup via the existing obs_initialized() when
    libobs has already torn down the graphics subsystem those resources
    belong to (there's nothing meaningful left to release at that point).
  3. frontend: the same guard, applied to two sibling destructors found
    by auditing every obs_enter_graphics() call site in frontend/ for
    the same exposure (see "Related call sites audited" below):
    Multiview::~Multiview() and ScreenshotObj::~ScreenshotObj().
    ScreenshotObj also calls obs_remove_tick_callback(), which
    dereferences obs directly with no null check of its own, so it is
    called after the guard. After shutdown the tick callback list has
    already been freed, so skipping it loses nothing.

Motivation and Context

Fixes a shutdown-order race between OBSBasic's deferred deletion and the
aboutToQuit-triggered call into obs_shutdown()/applicationShutdown().
This is the same root cause reported in #13248 ("OBS Studio 32.1.0 crashes
after shutdown") and in @notr1ch's comment there describing an identical
OBSBasicPreview/obs_enter_graphics crash on 32.1.2. #13347 closed the
specific aboutToQuit path that was racing on that report by removing the
connection, and that is a real fix for the instance it targets. This PR
instead hardens the lower-level entry points at fault, so any caller that
manages to run graphics teardown code after obs_shutdown() (now, or in
a future regression) fails safe instead of dereferencing freed memory.

Reproduction

Built master's parent commit of this branch (i.e. without this fix)
locally via Nix (nixpkgs's obs-studio derivation, src overridden to
a local checkout -- a full source build, not a substituted binary), then,
with a fresh XDG_CONFIG_HOME (so the first-run/auto-config path is
active) ran:

obs --minimize-to-tray &
sleep 3
kill $!          # SIGTERM, the same signal systemd/session managers send

This reproduced the crash in 6 of 8 attempts. coredumpctl/gdb
against the resulting core, with full local debug info, gives:

Program terminated with signal SIGSEGV, Segmentation fault.
#0  obs_enter_graphics () at libobs/obs.c:1807
#1  OBSBasicPreview::~OBSBasicPreview (this=<optimized out>) at frontend/widgets/OBSBasicPreview.cpp:22
#2  OBSBasicPreview::~OBSBasicPreview (this=<optimized out>) at frontend/widgets/OBSBasicPreview.cpp:34
#3  QObjectPrivate::deleteChildren() ()
... (QWidget teardown chain) ...
#14 OBSBasic::~OBSBasic (this=<optimized out>) at frontend/widgets/OBSBasic.cpp:1393
#15 QObject::event(QEvent*) ()
... (QApplication/QCoreApplication event dispatch) ...
#19 QCoreApplication::exec() ()
#20 run_program (...) at frontend/obs-main.cpp:691
#21 main (...) at frontend/obs-main.cpp:1055

The fault address is 0x148 in every capture (reproduced independently
twice). That is exactly offsetof(struct obs_core, video.graphics):

(gdb) print &((struct obs_core*)0)->video.graphics
$1 = (graphics_t **) 0x148

i.e. obs is NULL (set by obs_shutdown(), libobs/obs.c) and
obs_enter_graphics() reads obs->video.graphics anyway.

Related call sites audited

obs_enter_graphics() has 152 call sites project-wide; almost all of them
run only during normal (obs-alive) operation. I went through every one
under frontend/ specifically, since that's where shutdown-adjacent code
lives:

Site Exposed to this race?
OBSBasicPreview::~OBSBasicPreview() Yes -- fixed (this is the crash reproduced above)
Multiview::~Multiview() Yes -- fixed. Owned by OBSProjector, a Qt-parented top-level window that can outlive applicationShutdown()'s explicit cleanup list the same way OBSBasicPreview does
ScreenshotObj::~ScreenshotObj() Yes -- fixed. Its completion path (muxFile() on a background std::thread, finishing via a Qt::QueuedConnection into onFinished() -> deleteLater()) can plausibly land after obs_shutdown() if a screenshot is still in flight at quit
OBSBasic::applicationShutdown() (OBSBasic.cpp:1477) No. This runs before obs_shutdown() is called, in the same synchronous function (see the /* XXX: any obs data must be released before calling obs_shutdown */ comment a few lines above it) -- obs is guaranteed non-null here by construction, not part of the race
OBSProjector::UpdateMultiviewProjectors(), InitSafeAreas(), OBSBasicSourceSelect::AddExisting(), system-info-posix.cpp GPU query No. All are normal-operation paths (settings changes, adding a source, gathering GPU info for the "Go Live" flow), not reachable from shutdown

I did not extend this to the Multiview::~Multiview() loop that calls
obs_source_dec_showing() on weak-referenced sources above the graphics
cleanup -- that already goes through OBSGetStrongRef(), which returns
null once the underlying source is gone, so it's safe by a different,
pre-existing mechanism and out of scope for this fix.

Why the fix fixes it

With all three parts in place, the same repro (fresh config, SIGTERM
at 3s) was run 39 times total across three test rounds against builds
containing progressively more of this branch: zero crashes, and the
process exits cleanly within a few seconds every time (even racing a
from-scratch first-run wizard, which is the worst case observed). The
obs_initialized() checks mean the crashing lines are never reached once
libobs is down; the obs && check in obs_enter_graphics()/
obs_leave_graphics() is a second, independent line of defense at the
layer that actually dereferences the pointer, protecting any other caller
that hits the same shutdown ordering, not just these three call sites.

How Has This Been Tested?

  • Built the unpatched source and two incremental versions of the patched
    source with Nix (nixpkgs's obs-studio derivation, src overridden
    to a local checkout of each state), so all are genuine local source
    builds, not substituted binaries.
  • Unpatched: 6/8 launch+SIGTERM cycles (fresh config each time)
    produced the SIGSEGV above.
  • Patched (parts 1-2): 27/27 launch+SIGTERM cycles produced no crash.
  • Patched (parts 1-3): a further 12/12 launch+SIGTERM cycles,
    each with a completely fresh config directory (forcing the auto-config
    wizard every time), produced no crash and a clean exit every time.
  • No change in behavior observed in normal use (start/stop recording via
    obs-websocket, normal window close, multiview/projector windows,
    screenshots) -- all three guards are no-ops on the happy path where
    obs is still alive.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)

Checklist:

  • I have read the contributing document.
  • My code has been run through clang-format.
  • My code follows the project's style guidelines
  • My code is not on the master branch.
  • My code has been tested.
  • All commit messages are properly formatted and commits squashed where appropriate.
  • I have included updates to all appropriate documentation.

@PatTheMav PatTheMav changed the title CRASH FIX - libobs/frontend: Guard against a freed core on shutdown in 3 sites frontend: Guard against a freed core on shutdown in 3 sites Sep 24, 2026

@PatTheMav PatTheMav left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see a need for the frontend changes to be split into 2 separate commits, particularly as the language in the commit messages and the code comments makes references to the "same" hazard.

Indeed the third commit also uses two different ways to solve the issue:

  • In Multiview.cpp a guard statement is used to check if libobs is still initialised and bails out early.
  • In ScreenshotObj the functionality is wrapped in a conditional block doing the opposite check.

It would be more consistent if we'd use the same code pattern as in Multiview.cpp and OBSBasicPreview.

@Warchamp7 wouldn't it be more correct if the tick callback in ScreenshotObj is removed unconditionally, e.g. before a if(!obs_initialized) check?


There's IMO also no need to add (duplicate) multiline comments explaining the change in the source code itself - as long as the commit messages contain the motivation we should be fine.

@PatTheMav

Copy link
Copy Markdown
Member

If I'm not mistaken there is nothing that would in theory prevent libobs from being uninitialised between the obs_initialised and obs_enter_graphics call, as it's only the latter that attempts to lock the graphics mutex which obs_free_graphics will attempt to lock as well - a typical TOCTOU issue.

So with the changes of the first commit (which is indeed correct - one needs to ensure that the object on which to check a pointer can be dereferenced itself) obs_enter_graphics will only succeed if libobs is not fully shut down and if it succeeds it will actually prevent the shutdown of the graphics part.

Once shutdown has completed obs_enter_graphics will fail, but unfortunately that failure state is not communicated. Instead the thread-local graphics pointer will remain NULL and hopefully all graphics API calls implemented gs_valid which will log the error message <function>: called while not in a graphics context.

So in the case of Multiview::~Multiview, obs_initialised might succeed, obs_enter_graphics might still fail (but not crash with this PR), and then we'll end up with 6 error messages in the log for each gs_vertexbuffer_destroy call.


@RytoEX I'll leave it to you if that added check is "nice enough" as it currently avoids the log messages if only because both the destructors as well as obs_shutdown are currently executed on the same thread.

A better change (that'd also pay back some of the tech debt) would be for obs_enter_graphics to actually return a success state, so one could do this instead:

if (obs_enter_graphics()) {
    gs_vertexbuffer_destroy(actionSafeMargin);
    gs_vertexbuffer_destroy(graphicsSafeMargin);
    gs_vertexbuffer_destroy(fourByThreeSafeMargin);
    gs_vertexbuffer_destroy(leftLine);
    gs_vertexbuffer_destroy(topLine);
    gs_vertexbuffer_destroy(rightLine);
    obs_leave_graphics();
}

The obs_enter_graphics call produces a locked context that ensures that both the graphics object will continue to exist until obs_leave_graphics is called and also avoids calling any graphics functions when that cannot be ensured.

That might be an ABI break though and would thus probably require a new method like obs_lock_graphics which we'd then need to manually migrate everything to. 😬

@zackees

zackees commented Sep 24, 2026

Copy link
Copy Markdown
Author

First commit in this PR fixes crash.

The second commit was defensive.

I can squash the commits. Or split them into seperate PRs.

what's the best way to get these fixes in? I'm currently building my own obs to get around it.

@Fenrirthviti

Copy link
Copy Markdown
Member

Large portions of this PR/discussion appear to be AI generated.

Can you please confirm that the PR content, comments, and code were all human written per our policy?

@zackees

zackees commented Sep 25, 2026

Copy link
Copy Markdown
Author

Applied the requested changes

Comment on lines +56 to 59
if (!obs_initialized()) {
return;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This leads to obs_remove_tick_callback never being called, is that intentional?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is provably overly defensive

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is provably overly defensive

I don't think it is, I had time to look into this and that function unconditionally dereferences obs->data when attempting to lock a mutex.

So if obs is a nullptr already (as indicated by obs_initialized returning false), it would lead to a crash.

If the problem is limited to the order in which destructors are called on the main thread (and obs_shutdown is only ever(!) called from the main thread) then this solutions's TOCTOU issue still exists, but is without effect as nothing can uninitialise libobs between the check and the consecutive access.


Have you checked all call sites of obs_shutdown?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You were right, it isn't overly defensive. obs_remove_tick_callback dereferences obs->data, so calling it before the check could crash after shutdown. I moved it after the obs_initialized() guard, so it matches Multiview and OBSBasicPreview.

I checked all the call sites of obs_shutdown:

  • libobs/obs.c: in obs_startup(), when obs_init fails. The frontend objects don't exist yet at that point.
  • frontend/OBSApp.cpp: in OBSApp::~OBSApp, behind libobs_initialized, on the main thread.
  • test/win/test.cpp: a standalone test, not the frontend.

So the frontend only shuts down on the main thread, which means the TOCTOU window can't be hit from these destructors. I agree the proper fix is an obs_enter_graphics variant that reports success. I'd be happy to do that as a follow-up.

obs_shutdown() frees the global obs_core and sets `obs` to NULL, but
obs_enter_graphics()/obs_leave_graphics() only checked
obs->video.graphics, not obs itself. A caller that runs after shutdown
dereferences the freed pointer.

OBSBasicPreview, Multiview and ScreenshotObj release graphics resources
in their destructors via obs_enter_graphics(). These destructors can
run after obs_shutdown() (via a Qt DeferredDelete processed late in
shutdown), at which point the graphics subsystem is already gone and
entering graphics crashes. Return early when libobs is no longer
initialized.

ScreenshotObj removes its tick callback after that check, since
obs_remove_tick_callback() also dereferences obs. After shutdown the
tick callback list has already been freed, so nothing is left to remove.
@zackees

zackees commented Sep 29, 2026

Copy link
Copy Markdown
Author

Comments addressed

@Fenrirthviti

Copy link
Copy Markdown
Member

Can you please reply to my previous comment as well?

@Fenrirthviti

Copy link
Copy Markdown
Member

Closing as no response, and there are some pretty clear markers this is AI-generated.

@zackees

zackees commented Oct 8, 2026 •

Copy link
Copy Markdown
Author

image

Adobe was hostile to their users and now their entire suite got auto converted to rust.

Would it be possible that in this one case, you make an exception. For the good of the users.

Then I can close my fork.

@Fenrirthviti

Copy link
Copy Markdown
Member
image

Yeah, I think we'll be fine if this is what you're using to defend AI.

Best of luck with your projects.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants