From 9dccebc62fa8a4127e413a199968742e883f0bb7 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Fri, 6 Nov 2026 23:32:06 -0800 Subject: [PATCH 1/3] test: draft stalled CEF initialization interposition (#3833) --- tests/stalled_initialization.py | 153 ++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 tests/stalled_initialization.py diff --git a/tests/stalled_initialization.py b/tests/stalled_initialization.py new file mode 100644 index 0000000..f18f709 --- /dev/null +++ b/tests/stalled_initialization.py @@ -0,0 +1,153 @@ +#!/usr/bin/env -S uv run --script +"""Exercise real module shutdown with a stalled cef_initialize interposition. + +Build startup-shutdown with startup_shutdown.py first. The shim blocks before +CEF starts, or after real CEF has started helpers. A pipe releases slow starts; +stalled cases never release it. No production timeout environment overrides. +""" +import argparse +import os +from pathlib import Path +import selectors +import signal +import subprocess +import tempfile +import time + + +def descendants(pid): + found = set() + for task in Path(f"/proc/{pid}/task").glob("*"): + try: + children = (task / "children").read_text().split() + except FileNotFoundError: + continue + for child in children: + child = int(child) + if child not in found: + found.add(child) + found.update(descendants(child)) + return found + +SHIM = r''' +#define _GNU_SOURCE +#include +#include +#include +#include +typedef int (*initialize_fn)(const void *, const void *, void *, void *); +int cef_initialize(const void *args, const void *settings, void *app, void *sandbox) +{ + initialize_fn real = (initialize_fn)dlsym(RTLD_NEXT, "cef_initialize"); + int result = 0; + if (getenv("STALL_AFTER_INIT")) + result = real(args, settings, app, sandbox); + fprintf(stderr, "TEST: cef_initialize stalled (result=%d)\n", result); + fflush(stderr); + char release; + if (read(atoi(getenv("STALL_RELEASE_FD")), &release, 1) != 1) + _exit(90); + if (!getenv("STALL_AFTER_INIT")) + result = real(args, settings, app, sandbox); + return result; +} +''' + + +def run_case(args, shim, output, name, after_init=False, release=False): + config = output / name + config.mkdir() + read_fd, write_fd = os.pipe() + env = dict(os.environ, LD_PRELOAD=str(shim), STALL_RELEASE_FD=str(read_fd)) + if after_init: + env["STALL_AFTER_INIT"] = "1" + command = [str(args.executable.resolve()), str(args.module.resolve()), + str(args.data.resolve()), str(config), "hold", "--password-store=basic"] + evidence = [] + process = subprocess.Popen(command, env=env, pass_fds=(read_fd,), + start_new_session=True, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + os.close(read_fd) + selector = selectors.DefaultSelector() + helper_fds = [] + try: + selector.register(process.stdout, selectors.EVENT_READ) + deadline = time.monotonic() + 30 + stalled = False + warning = False + while time.monotonic() < deadline: + for key, _ in selector.select(max(0, deadline - time.monotonic())): + chunk = os.read(key.fd, 65536) + if not chunk: + raise AssertionError(f"{name}: exited before startup observation") + evidence.append(chunk) + text = b"".join(evidence) + stalled = b"TEST: cef_initialize stalled" in text + warning = b"Browser sources and docks" in text + if stalled and (release or warning): + break + assert stalled, f"{name}: interposition never reached" + if release: + os.write(write_fd, b"\n") + else: + assert warning, f"{name}: stalled CEF remained silent for 30 seconds" + if after_init: + assert b"result=1" in text, "real CEF initialization must succeed" + helpers = descendants(process.pid) + assert helpers, "real CEF must create helpers before the stall" + for pid in helpers: + try: + helper_fds.append(os.pidfd_open(pid)) + except ProcessLookupError: + pass + started = time.monotonic() + remaining, _ = process.communicate(b"\n", timeout=12) + evidence.append(remaining) + assert process.returncode == 0, f"{name}: exit {process.returncode}" + assert time.monotonic() - started < 12, f"{name}: shutdown exceeded bound" + text = b"".join(evidence) + assert b"browser startup and immediate shutdown completed" in text, text.decode(errors="replace") + if not release: + assert b"CEF initialization timed out during shutdown" in text, text.decode(errors="replace") + with selectors.DefaultSelector() as exited: + for fd in helper_fds: + exited.register(fd, selectors.EVENT_READ) + deadline = time.monotonic() + 5 + while exited.get_map() and time.monotonic() < deadline: + for key, _ in exited.select(max(0, deadline - time.monotonic())): + exited.unregister(key.fd) + assert not exited.get_map(), f"{name}: CEF helpers survived parent exit" + print(f"{name}: bounded shutdown completed") + finally: + selector.close() + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + for fd in helper_fds: + os.close(fd) + os.close(write_fd) + (output / (name + ".log")).write_bytes(b"".join(evidence)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ["executable", "module", "data", "output-dir"]: + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--compiler", default="cc") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="stalled-cef-", dir=args.output_dir) as scratch: + output = Path(scratch).resolve() + source = output / "stall.c" + source.write_text(SHIM) + shim = output / "stall.so" + subprocess.run([args.compiler, "-shared", "-fPIC", str(source), "-ldl", "-o", str(shim)], check=True) + # Keep logs outside the scratch directory even when a case fails. + for name, after, release in [("slow", False, True), ("stalled", False, False), + ("stalled-with-helpers", True, False)]: + run_case(args, shim, args.output_dir.resolve(), name, after, release) + + +if __name__ == "__main__": + main() From 2de6932cc511019e45117cfb8fde591c4375242c Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Fri, 6 Nov 2026 23:53:23 -0800 Subject: [PATCH 2/3] test: reproduce unbounded shutdown with stalled real CEF (RED) --- tests/stalled_initialization.py | 48 ++++++++++++++++++++++++--------- tests/startup-finalization.c | 44 ++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 12 deletions(-) create mode 100644 tests/startup-finalization.c diff --git a/tests/stalled_initialization.py b/tests/stalled_initialization.py index f18f709..de10a09 100644 --- a/tests/stalled_initialization.py +++ b/tests/stalled_initialization.py @@ -1,9 +1,9 @@ #!/usr/bin/env -S uv run --script """Exercise real module shutdown with a stalled cef_initialize interposition. -Build startup-shutdown with startup_shutdown.py first. The shim blocks before -CEF starts, or after real CEF has started helpers. A pipe releases slow starts; -stalled cases never release it. No production timeout environment overrides. +The shim blocks before CEF starts, or after real CEF has started helpers. A pipe +releases slow starts; stalled cases never release it. No production timeout +environment overrides. A static-destructor sentinel checks the fatal exit path. """ import argparse import os @@ -38,7 +38,13 @@ def descendants(pid): typedef int (*initialize_fn)(const void *, const void *, void *, void *); int cef_initialize(const void *args, const void *settings, void *app, void *sandbox) { - initialize_fn real = (initialize_fn)dlsym(RTLD_NEXT, "cef_initialize"); + /* OBS loads modules locally, so RTLD_NEXT cannot see their dependencies. */ + void *cef = dlopen("libcef.so", RTLD_LAZY | RTLD_NOLOAD); + initialize_fn real = cef ? (initialize_fn)dlsym(cef, "cef_initialize") : NULL; + if (!real) { + fprintf(stderr, "TEST: cannot resolve real cef_initialize: %s\n", dlerror()); + _exit(91); + } int result = 0; if (getenv("STALL_AFTER_INIT")) result = real(args, settings, app, sandbox); @@ -54,13 +60,15 @@ def descendants(pid): ''' -def run_case(args, shim, output, name, after_init=False, release=False): +def run_case(args, shim, output, name, after_init=False, release=False, wait_for_warning=False): config = output / name config.mkdir() read_fd, write_fd = os.pipe() env = dict(os.environ, LD_PRELOAD=str(shim), STALL_RELEASE_FD=str(read_fd)) if after_init: env["STALL_AFTER_INIT"] = "1" + if not release: + env["TEST_EXPECT_ABANDON"] = "1" command = [str(args.executable.resolve()), str(args.module.resolve()), str(args.data.resolve()), str(config), "hold", "--password-store=basic"] evidence = [] @@ -85,13 +93,11 @@ def run_case(args, shim, output, name, after_init=False, release=False): text = b"".join(evidence) stalled = b"TEST: cef_initialize stalled" in text warning = b"Browser sources and docks" in text - if stalled and (release or warning): + if stalled and ((release and not wait_for_warning) or warning): break assert stalled, f"{name}: interposition never reached" if release: os.write(write_fd, b"\n") - else: - assert warning, f"{name}: stalled CEF remained silent for 30 seconds" if after_init: assert b"result=1" in text, "real CEF initialization must succeed" helpers = descendants(process.pid) @@ -109,7 +115,12 @@ def run_case(args, shim, output, name, after_init=False, release=False): text = b"".join(evidence) assert b"browser startup and immediate shutdown completed" in text, text.decode(errors="replace") if not release: + assert warning, f"{name}: stalled CEF remained silent for 30 seconds" assert b"CEF initialization timed out during shutdown" in text, text.decode(errors="replace") + else: + assert b"CEF initialization timed out during shutdown" not in text, text.decode(errors="replace") + if warning: + assert text.count(b"Browser sources and docks") == 1, "warning must appear once" with selectors.DefaultSelector() as exited: for fd in helper_fds: exited.register(fd, selectors.EVENT_READ) @@ -132,11 +143,22 @@ def run_case(args, shim, output, name, after_init=False, release=False): def main(): parser = argparse.ArgumentParser(description=__doc__) - for name in ["executable", "module", "data", "output-dir"]: + for name in ["module", "data", "output-dir"]: parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--include-dir", type=Path, action="append", required=True) + parser.add_argument("--library-dir", type=Path, action="append", required=True) parser.add_argument("--compiler", default="cc") args = parser.parse_args() args.output_dir.mkdir(parents=True, exist_ok=True) + args.executable = args.output_dir.resolve() / "startup-finalization" + command = [args.compiler, "-DHAVE_OBSCONFIG_H"] + for directory in args.include_dir: + command.append("-I" + str(directory.resolve())) + command.append(str(Path(__file__).with_name("startup-finalization.c").resolve())) + for directory in args.library_dir: + command.extend(["-L" + str(directory.resolve()), "-Wl,-rpath," + str(directory.resolve())]) + command.extend(["-lobs", "-ldl", "-o", str(args.executable)]) + subprocess.run(command, check=True) with tempfile.TemporaryDirectory(prefix="stalled-cef-", dir=args.output_dir) as scratch: output = Path(scratch).resolve() source = output / "stall.c" @@ -144,9 +166,11 @@ def main(): shim = output / "stall.so" subprocess.run([args.compiler, "-shared", "-fPIC", str(source), "-ldl", "-o", str(shim)], check=True) # Keep logs outside the scratch directory even when a case fails. - for name, after, release in [("slow", False, True), ("stalled", False, False), - ("stalled-with-helpers", True, False)]: - run_case(args, shim, args.output_dir.resolve(), name, after, release) + for name, after, release, wait in [("slow", False, True, False), + ("stalled", False, False, False), + ("stalled-with-helpers", True, False, False), + ("slow-after-warning", False, True, True)]: + run_case(args, shim, args.output_dir.resolve(), name, after, release, wait) if __name__ == "__main__": diff --git a/tests/startup-finalization.c b/tests/startup-finalization.c new file mode 100644 index 0000000..0cb9378 --- /dev/null +++ b/tests/startup-finalization.c @@ -0,0 +1,44 @@ +/* Real module lifecycle with the frontend's final process-shutdown handshake. + * The optional hooks let the same test reproduce the original unbounded wait. */ +#include +#include +#include +#include + +static void unsafe_destructor(void) +{ + fputs("TEST: static destructors ran with stalled CEF\n", stderr); + abort(); +} + +int main(int argc, char **argv) +{ + if (argc < 5) + return 2; + obs_set_cmdline_args(argc, (const char *const *)argv); + if (!obs_startup("en-US", argv[3], NULL)) + return 3; + obs_module_t *module = NULL; + if (obs_open_module(&module, argv[1], argv[2]) != MODULE_SUCCESS || !obs_init_module(module)) + return 4; + void *library = obs_get_module_lib(module); + void (*prepare)(void) = dlsym(library, "obs_browser_prepare_shutdown"); + void (*finish)(void) = dlsym(library, "obs_browser_finish_shutdown"); + if (prepare && finish) + prepare(); + void (*initialize)(void) = dlsym(library, "obs_browser_initialize"); + if (!initialize) + return 6; + if (getenv("TEST_EXPECT_ABANDON")) + atexit(unsafe_destructor); + initialize(); + puts("holding browser startup until stdin is released"); + fflush(stdout); + getchar(); + obs_shutdown(); + puts("browser startup and immediate shutdown completed"); + fflush(stdout); + if (finish) + finish(); + return 0; +} From 4ba3c02cbc3f6c6cb93f34c6637f00692eac6809 Mon Sep 17 00:00:00 2001 From: Zach Vorhies Date: Sat, 7 Nov 2026 00:00:09 -0800 Subject: [PATCH 3/3] fix: bound CEF startup shutdown and preserve blocked state (GREEN) --- browser-startup.hpp | 68 ++++++++++++++++++++++++ obs-browser-plugin.cpp | 114 ++++++++++++++++++++++++++++++++++++---- tests/README.md | 41 +++++++++++++++ tests/startup-state.cpp | 54 +++++++++++++++++++ tests/startup_state.py | 17 ++++++ 5 files changed, 283 insertions(+), 11 deletions(-) create mode 100644 browser-startup.hpp create mode 100644 tests/startup-state.cpp create mode 100644 tests/startup_state.py diff --git a/browser-startup.hpp b/browser-startup.hpp new file mode 100644 index 0000000..a01214e --- /dev/null +++ b/browser-startup.hpp @@ -0,0 +1,68 @@ +#pragma once + +#include +#include +#include +#include + +/* 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 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 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; + } +}; diff --git a/obs-browser-plugin.cpp b/obs-browser-plugin.cpp index cee45b3..f4c02f3 100644 --- a/obs-browser-plugin.cpp +++ b/obs-browser-plugin.cpp @@ -27,6 +27,11 @@ #include #include #include +#if defined(__linux__) && !defined(ENABLE_BROWSER_QT_LOOP) +#include +#include +#include "browser-startup.hpp" +#endif #include #include @@ -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 @@ -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) @@ -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(); } @@ -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 } @@ -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 @@ -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"); } @@ -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 } diff --git a/tests/README.md b/tests/README.md index ab41619..4745194 100644 --- a/tests/README.md +++ b/tests/README.md @@ -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 ` 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: diff --git a/tests/startup-state.cpp b/tests/startup-state.cpp new file mode 100644 index 0000000..e497c3c --- /dev/null +++ b/tests/startup-state.cpp @@ -0,0 +1,54 @@ +#include "../browser-startup.hpp" + +#include +#include +#include + +using namespace std::chrono_literals; + +int main() +{ + for (bool success : {false, true}) { + BrowserStartup startup; + startup.Watch(1h, [] { std::abort(); }); + assert(startup.Complete([success](bool warned) { + assert(!warned); + return success; + }) == success); + assert(startup.WaitForShutdown(100ms)); + } + + // A startup warning does not abandon an initializer that is merely slow. + { + BrowserStartup startup; + std::promise warning; + startup.Watch(0ms, [&warning] { warning.set_value(); }); + warning.get_future().get(); + assert(startup.Complete([](bool warned) { + assert(warned); + return true; + })); + assert(startup.WaitForShutdown(100ms)); + } + + // A timed-out initializer and its state live until process exit. If init + // later returns, its completion callback must not touch destroyed OBS data. + auto *startup = new BrowserStartup; + startup->Watch(1h, [] { std::abort(); }); + assert(!startup->WaitForShutdown(1ms)); + assert(startup->IsAbandoned()); + std::promise entered; + std::promise escaped; + auto escaped_future = escaped.get_future(); + new std::thread([startup, &entered, &escaped] { + entered.set_value(); + startup->Complete([&escaped](bool) { + escaped.set_value(); + return true; + }); + }); + entered.get_future().get(); + assert(escaped_future.wait_for(50ms) == std::future_status::timeout); + // Avoid destructing promises while the intentionally parked thread lives. + std::_Exit(0); +} diff --git a/tests/startup_state.py b/tests/startup_state.py new file mode 100644 index 0000000..9140957 --- /dev/null +++ b/tests/startup_state.py @@ -0,0 +1,17 @@ +#!/usr/bin/env -S uv run --script +"""Test the actual startup handshake without CEF or OBS development libraries.""" +import argparse +from pathlib import Path +import subprocess + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--output-dir", type=Path, required=True) +parser.add_argument("--compiler", default="c++") +args = parser.parse_args() +args.output_dir.mkdir(parents=True, exist_ok=True) +executable = args.output_dir.resolve() / "startup-state" +subprocess.run([args.compiler, "-std=c++20", "-pthread", "-Wall", "-Wextra", "-Werror", + str(Path(__file__).with_name("startup-state.cpp")), "-o", str(executable)], check=True) +for _ in range(100): + subprocess.run([str(executable)], check=True, timeout=2) +print("startup handshake: 100 runs passed (failure, success, slow recovery, late return after timeout)")