Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions browser-startup.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#pragma once

#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>

/* The Linux manager and unload share this state. A timed-out initializer may
* never be cancelled safely: it still owns CEF locks and calls into this
* library. Keep this object, CEF, and its events alive until process exit.
* Complete() also parks an initializer that returns after abandonment, before
* it can restore signal handlers, log, or publish a result into a torn-down OBS.
*/
class BrowserStartup {

std::mutex mutex;
std::condition_variable changed;
std::thread watchdog;
bool complete = false;
bool abandoned = false;
bool stopping = false;
bool warned = false;

public:
template<typename Warning> void Watch(std::chrono::milliseconds timeout, Warning warning)
{
watchdog = std::thread([this, timeout, warning] {
std::unique_lock lock(mutex);
if (!changed.wait_for(lock, timeout, [this] { return complete || stopping; })) {
warned = true;
warning();
}
});
}

template<typename Finish> bool Complete(Finish finish)
{
std::unique_lock lock(mutex);
// This cannot be a detach-and-return: OBS may already have destroyed
// its module metadata, log handler, and global core by now.
changed.wait(lock, [this] { return !abandoned; });
bool result = finish(warned);
complete = true;
changed.notify_all();
return result;
}

bool WaitForShutdown(std::chrono::milliseconds timeout)
{
std::unique_lock lock(mutex);
if (!changed.wait_for(lock, timeout, [this] { return complete; })) {
abandoned = true;
}
stopping = true;
changed.notify_all();
lock.unlock();
if (watchdog.joinable()) {
watchdog.join();
}
return !abandoned;
}

bool IsAbandoned()
{
std::lock_guard lock(mutex);
return abandoned;
}
};
114 changes: 103 additions & 11 deletions obs-browser-plugin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
#include <sstream>
#include <thread>
#include <mutex>
#if defined(__linux__) && !defined(ENABLE_BROWSER_QT_LOOP)
#include <cstdio>
#include <cstdlib>
#include "browser-startup.hpp"
#endif
#include <nlohmann/json.hpp>
#include <obs-websocket-api.h>

Expand Down Expand Up @@ -82,6 +87,36 @@ os_event_t *cef_started_event = nullptr;
static os_event_t *cef_initialized_event = nullptr;
static bool browser_initialized = false;

#if defined(__linux__) && !defined(ENABLE_BROWSER_QT_LOOP)
static BrowserStartup *browser_startup = nullptr;
static bool process_finalizer_prepared = false;
static std::string cef_startup_version;

static void WarnBrowserStartup(const char *reason)
{
blog(LOG_ERROR,
"[obs-browser]: CEF %s %s. Browser sources and docks are unavailable until CEF starts. "
"Check the installed CEF runtime and the browser debug.log.",
cef_startup_version.c_str(), reason);
}

// A host that prepares this hook calls finish only after all normal application
// cleanup, before returning from main. No atexit ordering can provide that
// guarantee while CefInitialize can still register destructors on another thread.
extern "C" EXPORT void obs_browser_prepare_shutdown(void)
{
process_finalizer_prepared = true;
}

extern "C" EXPORT void obs_browser_finish_shutdown(void)
{
if (browser_startup && browser_startup->IsAbandoned()) {
std::fflush(nullptr);
std::_Exit(EXIT_SUCCESS);
}
}
#endif

#if defined(_WIN32)
static int adapterCount = 0;
#endif
Expand Down Expand Up @@ -454,22 +489,39 @@ static bool BrowserInit(void)

#if !defined(_WIN32)
BackupSignalHandlers();
#endif
bool success = CefInitialize(args, settings, app, nullptr);
RestoreSignalHandlers();
#else
bool success = CefInitialize(args, settings, app, nullptr);
auto finish_initialize = [&](bool warned) {
(void)warned;
#if !defined(_WIN32)
RestoreSignalHandlers();
#endif

if (!success) {
if (!success) {
#if CHROME_VERSION_BUILD >= 6367
blog(LOG_ERROR, "[obs-browser]: CEF failed to initialize. Exit code: %d", CefGetExitCode());
blog(LOG_ERROR, "[obs-browser]: CEF failed to initialize. Exit code: %d", CefGetExitCode());
#else
blog(LOG_ERROR, "[obs-browser]: CEF failed to initialize.");
blog(LOG_ERROR, "[obs-browser]: CEF failed to initialize.");
#endif
#if defined(__linux__) && !defined(ENABLE_BROWSER_QT_LOOP)
if (!warned)
WarnBrowserStartup("failed to initialize");
#endif
app = nullptr;
}
#if defined(__linux__) && !defined(ENABLE_BROWSER_QT_LOOP)
browser_initialized = success;
os_event_signal(cef_initialized_event);
#endif
return success;
};
#if defined(__linux__) && !defined(ENABLE_BROWSER_QT_LOOP)
// Complete parks a late result before it can touch OBS or restore signal
// handlers after unload. The events and all CEF state stay alive at timeout.
return browser_startup->Complete(finish_initialize);
#else
return finish_initialize(false);
#endif
app = nullptr;
return false;
}
return true;
}

static void BrowserShutdown(void)
Expand All @@ -488,9 +540,14 @@ static void BrowserShutdown(void)
#ifndef ENABLE_BROWSER_QT_LOOP
static void BrowserManagerThread(void)
{
#if defined(__linux__)
const bool initialized = BrowserInit();
#else
browser_initialized = BrowserInit();
os_event_signal(cef_initialized_event);
if (browser_initialized) {
const bool initialized = browser_initialized;
#endif
if (initialized) {
CefRunMessageLoop();
BrowserShutdown();
}
Expand All @@ -511,6 +568,13 @@ extern "C" EXPORT void obs_browser_initialize(void)
browser_initialized = false;
}
#else
#if defined(__linux__)
cef_startup_version = std::to_string(cef_version_info(0)) + "." + std::to_string(cef_version_info(1)) +
"." + std::to_string(cef_version_info(2));
browser_startup = new BrowserStartup;
browser_startup->Watch(std::chrono::seconds(10),
[] { WarnBrowserStartup("initialization has not completed after 10 seconds"); });
#endif
manager_thread = thread(BrowserManagerThread);
#endif
}
Expand Down Expand Up @@ -925,6 +989,12 @@ static void MigrateToChromeRuntime()

bool obs_module_load(void)
{
#if defined(__linux__) && !defined(ENABLE_BROWSER_QT_LOOP)
if (browser_startup && browser_startup->IsAbandoned()) {
blog(LOG_ERROR, "[obs-browser]: Cannot reload abandoned CEF; OBS must exit first");
return false;
}
#endif
#if CHROME_VERSION_BUILD > 6533
MigrateToChromeRuntime();
#endif
Expand Down Expand Up @@ -1012,7 +1082,25 @@ void obs_module_unload(void)
// Initialization can finish before the context-ready callback runs.
// Wait for success or failure before using the CEF API; the quit task
// must also be accepted while the context is still starting.
#if defined(__linux__)
if (!browser_startup->WaitForShutdown(std::chrono::seconds(5))) {
blog(LOG_ERROR,
"[obs-browser]: CEF initialization timed out during shutdown (CEF %s, 5 seconds). "
"Retaining the blocked thread and its events; OBS will finish cleanup and exit "
"without running CEF destructors.",
cef_startup_version.c_str());
if (!process_finalizer_prepared) {
blog(LOG_ERROR,
"[obs-browser]: Host has no final process-shutdown hook; exiting immediately "
"to avoid a join hang or destroying state still used by CEF.");
std::fflush(nullptr);
std::_Exit(EXIT_SUCCESS);
}
return;
}
#else
os_event_wait(cef_initialized_event);
#endif
if (browser_initialized && !CefPostTask(TID_UI, new BrowserTask([]() { CefQuitMessageLoop(); }))) {
blog(LOG_DEBUG, "[obs-browser]: Failed to post CefQuit task to loop");
}
Expand All @@ -1027,4 +1115,8 @@ void obs_module_unload(void)
cef_initialized_event = nullptr;
browser_initialized = false;
manager_initialized = false;
#if defined(__linux__) && !defined(ENABLE_BROWSER_QT_LOOP)
delete browser_startup;
browser_startup = nullptr;
#endif
}
41 changes: 41 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,47 @@ covers real successful initialization concurrent with unload. It does not
inject a CEF initialization failure or prove absence of leaks, and it does not
replace full frontend/rendering tests.

## Stalled initialization and final process exit

`startup_state.py --output-dir <fresh-dir>` compiles the production handshake
without CEF or OBS. It repeats success, failure, warning followed by recovery,
and an initializer returning after abandonment 100 times. An abandoned result
must remain parked before touching OBS state.

`stalled_initialization.py` uses the same include/library/module/data arguments
as `startup_shutdown.py`. Run it under Xvfb with the staged CEF runtime. It
compiles a new lifecycle fixture and an LD_PRELOAD shim for `cef_initialize`.
Cases cover a released slow start, a start that never returns, a start blocked
after real CEF has spawned helpers, and recovery after the startup warning.
The test observes helper exits through pidfds and uses a static-destructor
sentinel to reject a normal exit while CEF is blocked. Each output directory
must be fresh; the case logs remain there on failure.

On Linux without the Qt CEF loop, startup logs one warning after 10 seconds,
including the runtime CEF version. This warning allows later recovery. Unload
allows another 5 seconds for initialization to finish; success or failure in
that interval retains the normal quit/join path. At timeout, no CEF quit task
is posted and no join occurs. The initializer, events and CEF objects remain
alive, and a late initializer is parked before restoring signal handlers or
accessing OBS. This is intentional retention until process termination.

The obs-studio frontend calls the private `obs_browser_prepare_shutdown` hook
after loading the module and `obs_browser_finish_shutdown` after normal OBS,
Qt and platform cleanup, with the application log flushed. Only an abandoned
initialization makes the final hook call `_Exit(0)`, terminating the blocked
thread without running static CEF destructors. Closing the parent process's
CEF IPC descriptors must also terminate its helpers; the real-runtime test
checks that rather than assuming it. Libobs intentionally keeps module
libraries loaded after unload, so the retained thread and final hook keep
their code mapped.

A host that does not install this finalization handshake cannot safely
continue normal unload after a timeout. The plugin logs that limitation and
calls `_Exit(0)` immediately in that exceptional case, skipping remaining
application cleanup. Normal startup/shutdown on such hosts is unchanged.
This does not cancel `CefInitialize`, make a stalled runtime functional, or
establish support for any particular CEF version.

## Real initialization failure

After compiling the lifecycle harness above, run the Linux CEF singleton case:
Expand Down
Loading
Loading