From 0a15d642e6f07611ecb5d7a4a5f1f16d2b4dcaac Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:22:15 +0100 Subject: [PATCH 1/7] Keep the watchdog profile path short and let a killed orphan exit [#416] The watchdog scenarios set TMPDIR to a directory under the work path, where Chromium creates its singleton Unix socket: on the CEF runners that path exceeded sockaddr_un's limit and the browser aborted (Socket path too long). They now use a private directory in the system temporary directory, as the shared-window scenario already does. CheckJasmineRunner sent the deadline's group SIGKILL and probed the orphan at once: on a loaded runner it had not exited yet. It now waits up to 5 s before reporting a process that survived the deadline. --- test/cmake/CheckJasmineRunner.cmake | 22 ++++++++---- test/tools/AutomationClient.py | 52 +++++++++++++++-------------- 2 files changed, 42 insertions(+), 32 deletions(-) diff --git a/test/cmake/CheckJasmineRunner.cmake b/test/cmake/CheckJasmineRunner.cmake index 7ee0b917..b9b97a23 100644 --- a/test/cmake/CheckJasmineRunner.cmake +++ b/test/cmake/CheckJasmineRunner.cmake @@ -34,14 +34,22 @@ file(READ "${work}/pids.txt" pids) string(STRIP "${pids}" pids) separate_arguments(pids) foreach(pid IN LISTS pids) - execute_process(COMMAND kill -0 ${pid} RESULT_VARIABLE alive OUTPUT_QUIET ERROR_QUIET) - # A killed orphan stays a zombie when the container's PID 1 does not reap it: it holds nothing and is dead. - if(alive STREQUAL "0" AND EXISTS "/proc/${pid}/stat") - file(READ "/proc/${pid}/stat" stat) - if(stat MATCHES "\\) Z ") - set(alive 1) + # The group's SIGKILL is sent before the runner returns, but an orphan may take a moment to exit on a loaded + # machine: only one still running after 5 s survived the deadline. + foreach(attempt RANGE 50) + execute_process(COMMAND kill -0 ${pid} RESULT_VARIABLE alive OUTPUT_QUIET ERROR_QUIET) + # A killed orphan stays a zombie when the container's PID 1 does not reap it: it holds nothing and is dead. + if(alive STREQUAL "0" AND EXISTS "/proc/${pid}/stat") + file(READ "/proc/${pid}/stat" stat) + if(stat MATCHES "\\) Z ") + set(alive 1) + endif() endif() - endif() + if(NOT alive STREQUAL "0") + break() + endif() + execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 0.1) + endforeach() if(alive STREQUAL "0") execute_process(COMMAND kill -KILL ${pid}) message(FATAL_ERROR "Process ${pid} survived the deadline") diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index f3c807b2..61c2ddec 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -255,32 +255,34 @@ def watchdog(args): "--integrity", "sha512-" + base64.b64encode(hashlib.sha512(environment.read_bytes()).digest()).decode(), "--registry-dir", args.registry, "--startup-timeout", "30", "--timeout", "2", "--allow", "build"] endpoint = root / "forced-window" - # A private temporary directory isolates the native profile, which the forced exit must still remove. - profiles = root / "profiles" - profiles.mkdir() - forced_environment = dict(os.environ, TMPDIR=str(profiles), TEMP=str(profiles), TMP=str(profiles)) - with (pathlib.Path(args.work) / "watchdog.log").open("w") as log: - if args.scenario == "mcp-watchdog": - client = Client([args.agent, *command, "--mcp", "--listen", str(endpoint)], log, env=forced_environment) - try: - client.initialize() - client.start("build") + # A private temporary directory isolates the native profile, which the forced exit must still remove. It is + # created in the system temporary directory, not under the work path: Chromium puts its singleton Unix socket + # there, and sockaddr_un limits that path to about 108 bytes whatever the checkout's depth. + with tempfile.TemporaryDirectory(prefix="wf-profile-") as profile_root: + profiles = pathlib.Path(profile_root).resolve() + forced_environment = dict(os.environ, TMPDIR=str(profiles), TEMP=str(profiles), TMP=str(profiles)) + with (pathlib.Path(args.work) / "watchdog.log").open("w") as log: + if args.scenario == "mcp-watchdog": + client = Client([args.agent, *command, "--mcp", "--listen", str(endpoint)], log, env=forced_environment) try: - status = client.child.wait(timeout=30) - except subprocess.TimeoutExpired: - raise AssertionError(f"The forced exit did not happen\n{pathlib.Path(log.name).read_text()}") from None - assert status == 71, f"exit {status}\n{pathlib.Path(log.name).read_text()}" - assert isinstance(client.messages.get(timeout=2), EOFError), "A renderer retained MCP stdout" - finally: - client.close() - else: - cli = subprocess.run([args.agent, *command, "--listen", str(endpoint), "--operation", "build"], - stdout=subprocess.PIPE, stderr=log, text=True, timeout=45, env=forced_environment) - assert cli.returncode == 71, f"exit {cli.returncode}\n{cli.stdout}\n{pathlib.Path(log.name).read_text()}" - assert (project / "renderer.started").is_file(), "The deadline expired before the renderer actually blocked" - assert not endpoint.exists(), "The forced exit left its attachment capability behind" - left = list(profiles.glob("webfront-agent-*")) - assert not left, f"The forced exit left its native profile behind: {left}\n{pathlib.Path(log.name).read_text()}" + client.initialize() + client.start("build") + try: + status = client.child.wait(timeout=30) + except subprocess.TimeoutExpired: + raise AssertionError(f"The forced exit did not happen\n{pathlib.Path(log.name).read_text()}") from None + assert status == 71, f"exit {status}\n{pathlib.Path(log.name).read_text()}" + assert isinstance(client.messages.get(timeout=2), EOFError), "A renderer retained MCP stdout" + finally: + client.close() + else: + cli = subprocess.run([args.agent, *command, "--listen", str(endpoint), "--operation", "build"], + stdout=subprocess.PIPE, stderr=log, text=True, timeout=45, env=forced_environment) + assert cli.returncode == 71, f"exit {cli.returncode}\n{cli.stdout}\n{pathlib.Path(log.name).read_text()}" + assert (project / "renderer.started").is_file(), "The deadline expired before the renderer actually blocked" + assert not endpoint.exists(), "The forced exit left its attachment capability behind" + left = list(profiles.glob("webfront-agent-*")) + assert not left, f"The forced exit left its native profile behind: {left}\n{pathlib.Path(log.name).read_text()}" if args.scenario == "cli-watchdog": # This same-path relaunch must reach its authenticated page before the intentional error. # It checks directory reuse and Unicode failure reporting in one process; normal builds From ba93ec9630aea4412b77affe50b6f83a6f094d13 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:16:17 +0100 Subject: [PATCH 2/7] End the agent's CEF helpers before removing its profile on Linux [#416] With the watchdog profile in a short path, the CEF runners reached the assertion #416 added: a forced exit left webfront-agent-* behind, with no removal error. The CEF helper processes (zygote, renderers, GPU and network services) descend from the agent, outlive _Exit and recreate the profile. On Linux, the cleanup now lists the agent's descendants from /proc, ends them and waits up to 2 s until they are gone, then removes the profile. The watchdog assertion lists what a leftover profile contains. --- docs/CHANGELOG.md | 4 +- js/developer/tools/WebFrontAgent.cpp | 73 ++++++++++++++++++++++++++++ test/tools/AutomationClient.py | 3 +- 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 714fb022..1bd3d878 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6,7 +6,9 @@ waits up to 5 s for the browser processes it launched to exit and ends those still running (at once after a forced exit, which also keeps the status of an exit that completes meanwhile), then retries files pending deletion for 2 s. The watchdog tests check that a forced exit removes the profile, the automation failure messages report the observed - run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. + run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. On Linux, the + automation agent ends the CEF helper processes descending from it before removing the profile, since they outlive + a forced exit and recreated it; the watchdog tests keep that profile in a short system temporary path. - Show the `wf` commands of the developer browser test in its window (#415): `DeveloperBrowserIntegration` shows, in place of its terminal, each command it runs with its outcome and duration, labelling the timeouts and cancellations diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index 987b66c7..f8ad9d93 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -25,6 +25,15 @@ #else #include #endif +#ifdef __linux__ +#include +#include +#include +#include +#include +#include +#include +#endif namespace { using namespace webfront; @@ -123,6 +132,68 @@ void releaseWebView(std::chrono::milliseconds grace) noexcept { // Without the process list, the removal below still retries the transient errors. } } +#elif defined(__linux__) +// The parent and state ('Z' for a zombie) of a process, from /proc//stat; nothing when it is gone. +std::optional> processStat(pid_t pid) { + std::ifstream input("/proc/" + std::to_string(pid) + "/stat"); + std::string stat; + if (!std::getline(input, stat)) + return std::nullopt; + // The command name may contain spaces and parentheses: the fields resume after its last ')'. + const auto end = stat.rfind(") "); + if (end == std::string::npos || end + 4 >= stat.size()) + return std::nullopt; + std::istringstream fields(stat.substr(end + 2)); + char state{}; + pid_t parent{}; + if (!(fields >> state >> parent)) + return std::nullopt; + return std::pair{parent, state}; +} + +bool running(pid_t pid) { + const auto stat = processStat(pid); + return stat && stat->second != 'Z' && stat->second != 'X'; +} + +// Every process descending from the agent, listed before any is ended: an orphan is reparented and leaves the tree. +std::vector descendants() { + std::map> children; + for (const auto& entry : std::filesystem::directory_iterator("/proc")) { + const auto name = entry.path().filename().string(); + if (name.empty() || !std::ranges::all_of(name, [](char c) { return c >= '0' && c <= '9'; })) + continue; + const auto pid = static_cast(std::stol(name)); + if (const auto stat = processStat(pid)) + children[stat->first].push_back(pid); + } + std::vector result{::getpid()}; + for (std::size_t next = 0; next != result.size(); ++next) + if (const auto found = children.find(result[next]); found != children.end()) + result.insert(result.end(), found->second.begin(), found->second.end()); + result.erase(result.begin()); + return result; +} + +// The CEF helper processes (zygote, renderers, GPU and network services) descend from the agent and outlive _Exit: one +// still writing into the profile after its removal recreates it. The profile is about to go, so nothing they could +// still save matters: end them and wait until they are gone. +void releaseBrowserProcesses() noexcept { + try { + const auto processes = descendants(); + const auto anyRunning = [&] { + return std::ranges::any_of(processes, running); + }; + for (const auto pid : processes) + if (running(pid)) + ::kill(pid, SIGKILL); + const auto terminated = std::chrono::steady_clock::now() + std::chrono::seconds{2}; + while (anyRunning() && std::chrono::steady_clock::now() < terminated) + std::this_thread::sleep_for(std::chrono::milliseconds{20}); + } catch (...) { + // Without the process list, the removal below still runs. + } +} #endif struct Profile { @@ -135,6 +206,8 @@ struct Profile { #ifdef _WIN32 releaseWebView(grace); const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; +#elif defined(__linux__) + releaseBrowserProcesses(); // the browser's helpers would otherwise recreate the profile #endif for (;;) { std::error_code error; diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 61c2ddec..cc48b05c 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -282,7 +282,8 @@ def watchdog(args): assert (project / "renderer.started").is_file(), "The deadline expired before the renderer actually blocked" assert not endpoint.exists(), "The forced exit left its attachment capability behind" left = list(profiles.glob("webfront-agent-*")) - assert not left, f"The forced exit left its native profile behind: {left}\n{pathlib.Path(log.name).read_text()}" + contents = [str(path.relative_to(profiles)) for profile in left for path in profile.rglob("*")][:40] + assert not left, f"The forced exit left its native profile behind: {left} {contents}\n{pathlib.Path(log.name).read_text()}" if args.scenario == "cli-watchdog": # This same-path relaunch must reach its authenticated page before the intentional error. # It checks directory reuse and Unicode failure reporting in one process; normal builds From 9d42f5482b0dba3381510838b045897703d93dea Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:27:49 +0100 Subject: [PATCH 3/7] Remove the agent's profile once it has exited on Linux [#416] Ending the CEF helpers was not enough: the CEF browser runs inside the agent, relaunches its helpers and keeps writing into the profile until the agent exits (cef_debug.log, Dictionaries, GPUPersistentCache), so the removal failed with "Directory not empty". After ending the helpers and a first removal, the agent now spawns a shell, with /dev/null as stdio and none of its other descriptors, that waits until the agent has exited (even unreaped) and removes the profile. The automation tests wait up to 10 s for that removal. --- docs/CHANGELOG.md | 5 ++-- js/developer/tools/WebFrontAgent.cpp | 35 ++++++++++++++++++++++++++++ test/tools/AutomationClient.py | 22 +++++++++++++---- 3 files changed, 55 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1bd3d878..9fa9fe6b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,8 +7,9 @@ exit, which also keeps the status of an exit that completes meanwhile), then retries files pending deletion for 2 s. The watchdog tests check that a forced exit removes the profile, the automation failure messages report the observed run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. On Linux, the - automation agent ends the CEF helper processes descending from it before removing the profile, since they outlive - a forced exit and recreated it; the watchdog tests keep that profile in a short system temporary path. + automation agent ends the CEF helper processes descending from it, removes the profile, and leaves a last removal + to a shell that waits for its exit, since the CEF browser inside the agent writes into the profile until then; the + tests wait up to 10 s for that removal and keep the watchdog profile in a short system temporary path. - Show the `wf` commands of the developer browser test in its window (#415): `DeveloperBrowserIntegration` shows, in place of its terminal, each command it runs with its outcome and duration, labelling the timeouts and cancellations diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index f8ad9d93..6621c8e9 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -194,6 +195,35 @@ void releaseBrowserProcesses() noexcept { // Without the process list, the removal below still runs. } } + +// The CEF browser runs inside the agent: until the agent exits, its threads may write into the profile again, and +// relaunch the helpers ended above. A shell outside the agent's descriptors removes the profile once the agent is gone +// (exited, even if not reaped yet); false when it cannot be started. +bool removeAfterExit(const std::filesystem::path& path) noexcept { + try { + posix_spawn_file_actions_t actions; + if (::posix_spawn_file_actions_init(&actions) != 0) + return false; + // Neither the CLI/MCP pipes, whose EOF the clients wait for, nor the agent's sockets go to the shell. + bool prepared = ::posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0) == 0 + && ::posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0) == 0 + && ::posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0) == 0 + && ::posix_spawn_file_actions_addclosefrom_np(&actions, 3) == 0; + const auto agent = std::to_string(::getpid()); + const auto profile = path.string(); + // Waits while the agent runs ('Z' once exited), then removes the profile. + const char* script = "while [ -r \"/proc/$0/stat\" ] && [ \"$(sed 's/.*) //' \"/proc/$0/stat\" | cut -c1)\" != Z ]; do " + "sleep 0.05; done; rm -rf -- \"$1\""; + char* const arguments[] = {const_cast("sh"), const_cast("-c"), const_cast(script), + const_cast(agent.c_str()), const_cast(profile.c_str()), nullptr}; + pid_t cleaner{}; + prepared = prepared && ::posix_spawn(&cleaner, "/bin/sh", &actions, nullptr, arguments, environ) == 0; + ::posix_spawn_file_actions_destroy(&actions); + return prepared; + } catch (...) { + return false; + } +} #endif struct Profile { @@ -208,6 +238,11 @@ struct Profile { const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; #elif defined(__linux__) releaseBrowserProcesses(); // the browser's helpers would otherwise recreate the profile + std::error_code ignored; + std::filesystem::remove_all(path, ignored); // what the browser still writes goes after the agent's exit + if (!removeAfterExit(path)) + std::cerr << "Automation: cannot schedule the removal of the temporary profile\n"; + return; #endif for (;;) { std::error_code error; diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index cc48b05c..1c318744 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -112,6 +112,19 @@ def close(self): self.reader.join(timeout=2) +def remaining_profiles(profiles, timeout=10): + """The agent profiles left in `profiles`, once removed or after `timeout` seconds, with what they contain. + + On Linux, the CEF browser runs inside the agent and may write until it exits: the agent then leaves the + last removal to a process that waits for its exit.""" + deadline = time.monotonic() + timeout + while True: + left = list(profiles.glob("webfront-agent-*")) + if not left or time.monotonic() >= deadline: + return left, [str(path.relative_to(profiles)) for profile in left for path in profile.rglob("*")][:40] + time.sleep(0.05) + + def check_startup_backoff(agent, root, ready_delay=0): """The attach-only path needs no renderer and must not create 50 connections per second.""" endpoint = root / f"owner-{ready_delay}" @@ -281,8 +294,7 @@ def watchdog(args): assert cli.returncode == 71, f"exit {cli.returncode}\n{cli.stdout}\n{pathlib.Path(log.name).read_text()}" assert (project / "renderer.started").is_file(), "The deadline expired before the renderer actually blocked" assert not endpoint.exists(), "The forced exit left its attachment capability behind" - left = list(profiles.glob("webfront-agent-*")) - contents = [str(path.relative_to(profiles)) for profile in left for path in profile.rglob("*")][:40] + left, contents = remaining_profiles(profiles) assert not left, f"The forced exit left its native profile behind: {left} {contents}\n{pathlib.Path(log.name).read_text()}" if args.scenario == "cli-watchdog": # This same-path relaunch must reach its authenticated page before the intentional error. @@ -458,9 +470,9 @@ def main(): assert shutdown.returncode == 0, shutdown.stderr # Before it exits, the owner waits up to 5 s for the WebView2 browser, ends it, then removes the profile. assert owner.wait(timeout=30) == 0, pathlib.Path(log.name).read_text() - # Only the owner removes the profile: once it has exited, the directory no longer changes. - left = list(profiles.glob("webfront-agent-*")) - assert not left, f"The owner left its native profile behind: {left}\n{pathlib.Path(log.name).read_text()}" + # Only the owner removes the profile, at the latest just after it has exited. + left, contents = remaining_profiles(profiles) + assert not left, f"The owner left its native profile behind: {left} {contents}\n{pathlib.Path(log.name).read_text()}" assert not endpoint.exists(), "The owner left its attachment capability behind" unavailable = subprocess.run([args.agent, "--attach", str(endpoint), "--operation", "build"], capture_output=True, text=True, timeout=5) From 21340c5d0a38a14c4e7fca7351af4591b6fd5e48 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:17:19 +0100 Subject: [PATCH 4/7] Harden the deferred profile removal and the orphan check [#416] - CheckJasmineRunner: read the orphan's state with a recoverable command; a process reaped between the checks counts as gone instead of failing CMake. Probe 50 times (5 s). - WebFrontAgent (Linux): clean up once, so a forced exit racing a normal one no longer ends the first removal shell; give the Linux cleanup its own branch; fall back to /proc/self/fd where posix_spawn has no closefrom action (musl, glibc < 2.34); let the shell tell a reused PID apart by the agent's start time and repeat the removal for 2 s against a helper relaunched just before the exit. - AutomationClient: a leftover profile reports its assertion, not a cleanup error of the temporary directory. --- docs/CHANGELOG.md | 6 ++-- js/developer/tools/WebFrontAgent.cpp | 50 ++++++++++++++++++++++------ test/cmake/CheckJasmineRunner.cmake | 9 ++--- test/tools/AutomationClient.py | 4 +-- 4 files changed, 50 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 9fa9fe6b..f8e3fbd5 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,8 +8,10 @@ The watchdog tests check that a forced exit removes the profile, the automation failure messages report the observed run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. On Linux, the automation agent ends the CEF helper processes descending from it, removes the profile, and leaves a last removal - to a shell that waits for its exit, since the CEF browser inside the agent writes into the profile until then; the - tests wait up to 10 s for that removal and keep the watchdog profile in a short system temporary path. + to a shell that waits for its exit, since the CEF browser inside the agent writes into the profile until then, and + repeats it for 2 s against a helper relaunched meanwhile; the tests wait up to 10 s for that removal and keep the + watchdog profile in a short system temporary path. The deadline check of the Jasmine runner waits up to 5 s for a + killed orphan to exit and treats one reaped while it reads its state as gone. - Show the `wf` commands of the developer browser test in its window (#415): `DeveloperBrowserIntegration` shows, in place of its terminal, each command it runs with its outcome and duration, labelling the timeouts and cancellations diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index 6621c8e9..0fcefa8b 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -196,6 +196,21 @@ void releaseBrowserProcesses() noexcept { } } +// Closes every descriptor from 3 in the spawned process. glibc 2.34 has a dedicated action; elsewhere the open +// descriptors are listed from /proc/self/fd, after the listing has closed its own. +bool closeInheritedDescriptors(posix_spawn_file_actions_t& actions) { +#if defined(__GLIBC__) && __GLIBC_PREREQ(2, 34) + return ::posix_spawn_file_actions_addclosefrom_np(&actions, 3) == 0; +#else + std::vector open; + for (const auto& entry : std::filesystem::directory_iterator("/proc/self/fd")) + open.push_back(std::stoi(entry.path().filename().string())); + return std::ranges::all_of(open, [&](int descriptor) { + return descriptor < 3 || ::fcntl(descriptor, F_GETFD) < 0 || ::posix_spawn_file_actions_addclose(&actions, descriptor) == 0; + }); +#endif +} + // The CEF browser runs inside the agent: until the agent exits, its threads may write into the profile again, and // relaunch the helpers ended above. A shell outside the agent's descriptors removes the profile once the agent is gone // (exited, even if not reaped yet); false when it cannot be started. @@ -208,12 +223,18 @@ bool removeAfterExit(const std::filesystem::path& path) noexcept { bool prepared = ::posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0) == 0 && ::posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0) == 0 && ::posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0) == 0 - && ::posix_spawn_file_actions_addclosefrom_np(&actions, 3) == 0; + && closeInheritedDescriptors(actions); const auto agent = std::to_string(::getpid()); const auto profile = path.string(); - // Waits while the agent runs ('Z' once exited), then removes the profile. - const char* script = "while [ -r \"/proc/$0/stat\" ] && [ \"$(sed 's/.*) //' \"/proc/$0/stat\" | cut -c1)\" != Z ]; do " - "sleep 0.05; done; rm -rf -- \"$1\""; + // Waits while the agent runs: its stat fields after the command name start with the state ('Z' once exited) and + // have its start time 20th, which tells a reused PID apart. A helper relaunched just before the agent's exit + // ends once the browser is gone, but may recreate the profile meanwhile: the removal is repeated for 2 s. + const char* script = "fields() { sed 's/.*) //' \"/proc/$0/stat\" 2>/dev/null; }; " + "started=$(fields | cut -d' ' -f20); " + "while current=$(fields) && [ \"${current%% *}\" != Z ] " + "&& [ \"$(echo \"$current\" | cut -d' ' -f20)\" = \"$started\" ]; do sleep 0.05; done; " + "rm -rf -- \"$1\"; i=0; while [ $i -lt 20 ]; do sleep 0.1; " + "if [ -e \"$1\" ]; then rm -rf -- \"$1\"; fi; i=$((i + 1)); done"; char* const arguments[] = {const_cast("sh"), const_cast("-c"), const_cast(script), const_cast(agent.c_str()), const_cast(profile.c_str()), nullptr}; pid_t cleaner{}; @@ -229,20 +250,26 @@ bool removeAfterExit(const std::filesystem::path& path) noexcept { struct Profile { channel::PrivateDirectory directory{std::filesystem::temp_directory_path() / ("webfront-agent-" + channel::nonce())}; const std::filesystem::path path{directory.path}; +#ifdef __linux__ + mutable std::atomic released{false}; +#endif /// @param grace how long the WebView2 browser may take to exit on its own before it is ended (Windows only) void cleanup([[maybe_unused]] std::chrono::milliseconds grace) const noexcept { - // POSIX can unlink open files. On Windows, the files of a process that has just exited can stay pending - // deletion for a moment, which reports a sharing violation, a refused access or a non-empty directory. -#ifdef _WIN32 - releaseWebView(grace); - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; -#elif defined(__linux__) +#ifdef __linux__ + // A forced exit that loses the race with a normal one cleans up twice: the second would end the first's shell. + if (released.exchange(true)) + return; releaseBrowserProcesses(); // the browser's helpers would otherwise recreate the profile std::error_code ignored; std::filesystem::remove_all(path, ignored); // what the browser still writes goes after the agent's exit if (!removeAfterExit(path)) std::cerr << "Automation: cannot schedule the removal of the temporary profile\n"; - return; +#else + // POSIX can unlink open files. On Windows, the files of a process that has just exited can stay pending + // deletion for a moment, which reports a sharing violation, a refused access or a non-empty directory. +#ifdef _WIN32 + releaseWebView(grace); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; #endif for (;;) { std::error_code error; @@ -259,6 +286,7 @@ struct Profile { std::cerr << "Automation: cannot remove temporary profile: " << error.message() << '\n'; return; } +#endif } ~Profile() { cleanup(std::chrono::seconds{5}); diff --git a/test/cmake/CheckJasmineRunner.cmake b/test/cmake/CheckJasmineRunner.cmake index b9b97a23..e7e57ab9 100644 --- a/test/cmake/CheckJasmineRunner.cmake +++ b/test/cmake/CheckJasmineRunner.cmake @@ -36,12 +36,13 @@ separate_arguments(pids) foreach(pid IN LISTS pids) # The group's SIGKILL is sent before the runner returns, but an orphan may take a moment to exit on a loaded # machine: only one still running after 5 s survived the deadline. - foreach(attempt RANGE 50) + foreach(attempt RANGE 1 50) execute_process(COMMAND kill -0 ${pid} RESULT_VARIABLE alive OUTPUT_QUIET ERROR_QUIET) # A killed orphan stays a zombie when the container's PID 1 does not reap it: it holds nothing and is dead. - if(alive STREQUAL "0" AND EXISTS "/proc/${pid}/stat") - file(READ "/proc/${pid}/stat" stat) - if(stat MATCHES "\\) Z ") + # The process may also be reaped between the two checks: a stat that cannot be read means it is gone. + if(alive STREQUAL "0") + execute_process(COMMAND cat "/proc/${pid}/stat" OUTPUT_VARIABLE stat RESULT_VARIABLE unreadable ERROR_QUIET) + if(NOT unreadable STREQUAL "0" OR stat MATCHES "\\) Z ") set(alive 1) endif() endif() diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 1c318744..97b1f623 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -271,7 +271,7 @@ def watchdog(args): # A private temporary directory isolates the native profile, which the forced exit must still remove. It is # created in the system temporary directory, not under the work path: Chromium puts its singleton Unix socket # there, and sockaddr_un limits that path to about 108 bytes whatever the checkout's depth. - with tempfile.TemporaryDirectory(prefix="wf-profile-") as profile_root: + with tempfile.TemporaryDirectory(prefix="wf-profile-", ignore_cleanup_errors=True) as profile_root: profiles = pathlib.Path(profile_root).resolve() forced_environment = dict(os.environ, TMPDIR=str(profiles), TEMP=str(profiles), TMP=str(profiles)) with (pathlib.Path(args.work) / "watchdog.log").open("w") as log: @@ -410,7 +410,7 @@ def main(): endpoint = pathlib.Path(temporary) / "shared-window" # Keep Chromium's temporary Unix socket paths below sockaddr_un's limit, independently # of the checkout/work path length. The agent still creates its own private child profile. - with tempfile.TemporaryDirectory(prefix="wf-profile-") as profile_root, (pathlib.Path(temporary) / "shared.log").open("w") as log: + with tempfile.TemporaryDirectory(prefix="wf-profile-", ignore_cleanup_errors=True) as profile_root, (pathlib.Path(temporary) / "shared.log").open("w") as log: profiles = pathlib.Path(profile_root).resolve() owner_environment = dict(os.environ, TMPDIR=str(profiles), TEMP=str(profiles), TMP=str(profiles)) owner = subprocess.Popen([args.agent, *command, "--serve", "--listen", str(endpoint), From cc999df6cd9c6997cece2c541239ec2ffd95c2ad Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:41:03 +0100 Subject: [PATCH 5/7] Spare unrelated processes and harden the Linux profile removal [#416] - WebFrontAgent (Linux): end only the descendants running the agent's own executable, the CEF helpers, so a WebKitGTK web process or a command of the developer application survives; give them the cleanup grace (5 s on a normal exit) before killing them; hold them through pidfds, confirmed by a second scan, so a reused PID is never signalled. They are listed once: the browser aborts after a few GPU relaunches. - Start the removal shell in its own session, so a kill of the agent's process group does not prevent the removal; release the spawn actions and attributes on every path; test the glibc version without __GLIBC_PREREQ, which another libc lacks. - CheckJasmineRunner: read the orphan's state with ps where there is no /proc (macOS) instead of taking it for gone; do not wait after the last probe. - AutomationClient: list a leftover profile with os.walk, which tolerates the removal still under way, and stop after 40 entries. --- docs/CHANGELOG.md | 8 +- js/developer/tools/WebFrontAgent.cpp | 138 ++++++++++++++++++++------- test/cmake/CheckJasmineRunner.cmake | 15 ++- test/tools/AutomationClient.py | 7 +- 4 files changed, 127 insertions(+), 41 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index f8e3fbd5..73abd001 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,11 +7,13 @@ exit, which also keeps the status of an exit that completes meanwhile), then retries files pending deletion for 2 s. The watchdog tests check that a forced exit removes the profile, the automation failure messages report the observed run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. On Linux, the - automation agent ends the CEF helper processes descending from it, removes the profile, and leaves a last removal - to a shell that waits for its exit, since the CEF browser inside the agent writes into the profile until then, and + automation agent gives the CEF helpers descending from it (the processes running its own executable) the same + grace, then kills them through pidfds, removes the profile, and leaves a last removal to a shell in its own session + that waits for its exit, since the CEF browser inside the agent writes into the profile until then, and repeats it for 2 s against a helper relaunched meanwhile; the tests wait up to 10 s for that removal and keep the watchdog profile in a short system temporary path. The deadline check of the Jasmine runner waits up to 5 s for a - killed orphan to exit and treats one reaped while it reads its state as gone. + killed orphan to exit and treats one reaped while it reads its state as gone, reading that state with `ps` where + there is no `/proc` (macOS). - Show the `wf` commands of the developer browser test in its window (#415): `DeveloperBrowserIntegration` shows, in place of its terminal, each command it runs with its outcome and duration, labelling the timeouts and cancellations diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index 0fcefa8b..e5ae91f2 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -28,10 +28,13 @@ #ifdef __linux__ #include #include +#include +#include #include #include #include #include +#include #include #include #endif @@ -152,13 +155,10 @@ std::optional> processStat(pid_t pid) { return std::pair{parent, state}; } -bool running(pid_t pid) { - const auto stat = processStat(pid); - return stat && stat->second != 'Z' && stat->second != 'X'; -} - -// Every process descending from the agent, listed before any is ended: an orphan is reparented and leaves the tree. -std::vector descendants() { +// The CEF helpers (zygote, renderers, GPU and network services) are the descendants running the agent's own +// executable, listed before any is ended (an orphan is reparented and leaves the tree): a WebKitGTK web process or a +// command the developer application started is not one of them. +std::vector browserHelpers() { std::map> children; for (const auto& entry : std::filesystem::directory_iterator("/proc")) { const auto name = entry.path().filename().string(); @@ -168,38 +168,95 @@ std::vector descendants() { if (const auto stat = processStat(pid)) children[stat->first].push_back(pid); } - std::vector result{::getpid()}; - for (std::size_t next = 0; next != result.size(); ++next) - if (const auto found = children.find(result[next]); found != children.end()) - result.insert(result.end(), found->second.begin(), found->second.end()); - result.erase(result.begin()); + std::vector tree{::getpid()}; + for (std::size_t next = 0; next != tree.size(); ++next) + if (const auto found = children.find(tree[next]); found != children.end()) + tree.insert(tree.end(), found->second.begin(), found->second.end()); + std::vector result; + for (const auto pid : tree | std::views::drop(1)) { + std::error_code error; + if (std::filesystem::equivalent("/proc/" + std::to_string(pid) + "/exe", "/proc/self/exe", error)) + result.push_back(pid); + } return result; } -// The CEF helper processes (zygote, renderers, GPU and network services) descend from the agent and outlive _Exit: one -// still writing into the profile after its removal recreates it. The profile is about to go, so nothing they could -// still save matters: end them and wait until they are gone. -void releaseBrowserProcesses() noexcept { +// A pidfd keeps designating the process it was opened on, even once its identifier is reused; -1 without pidfds. +int openProcess(pid_t pid) noexcept { +#ifdef SYS_pidfd_open + return static_cast(::syscall(SYS_pidfd_open, pid, 0)); +#else + return -1; +#endif +} + +struct Helper { + pid_t pid; + int descriptor; + bool killed = false; + bool exited() const { + if (descriptor < 0) { + const auto stat = processStat(pid); + return !stat || stat->second == 'Z' || stat->second == 'X'; + } + pollfd readable{.fd = descriptor, .events = POLLIN, .revents = 0}; + return ::poll(&readable, 1, 0) > 0; + } + void kill() { + if (std::exchange(killed, true)) + return; +#ifdef SYS_pidfd_send_signal + if (descriptor >= 0) { + ::syscall(SYS_pidfd_send_signal, descriptor, SIGKILL, nullptr, 0); + return; + } +#endif + ::kill(pid, SIGKILL); + } +}; + +// The CEF helpers outlive _Exit: one still writing into the profile after its removal recreates it. Let them exit +// during the grace, then end them and wait until they are gone, for 2 s more at most. They are listed once: the +// browser relaunches an ended GPU process, and aborts after a few, so a helper started later is left to the removal +// after the agent's exit. +void releaseBrowserProcesses(std::chrono::milliseconds grace) noexcept { + std::vector helpers; try { - const auto processes = descendants(); - const auto anyRunning = [&] { - return std::ranges::any_of(processes, running); - }; - for (const auto pid : processes) - if (running(pid)) - ::kill(pid, SIGKILL); - const auto terminated = std::chrono::steady_clock::now() + std::chrono::seconds{2}; - while (anyRunning() && std::chrono::steady_clock::now() < terminated) + for (const auto pid : browserHelpers()) + helpers.push_back({pid, openProcess(pid)}); + // Opened after the scan: a pidfd designates one of our helpers only if its identifier still is one. + const auto confirmed = browserHelpers(); + std::erase_if(helpers, [&](const Helper& helper) { + if (helper.descriptor < 0 || std::ranges::find(confirmed, helper.pid) != confirmed.end()) + return false; + ::close(helper.descriptor); + return true; + }); + const auto ended = std::chrono::steady_clock::now() + grace; + const auto terminated = ended + std::chrono::seconds{2}; + for (;;) { + const auto now = std::chrono::steady_clock::now(); + if (std::ranges::all_of(helpers, &Helper::exited) || now >= terminated) + break; + if (now >= ended) + for (auto& helper : helpers) + if (!helper.exited()) + helper.kill(); std::this_thread::sleep_for(std::chrono::milliseconds{20}); + } } catch (...) { // Without the process list, the removal below still runs. } + for (const auto& helper : helpers) + if (helper.descriptor >= 0) + ::close(helper.descriptor); } // Closes every descriptor from 3 in the spawned process. glibc 2.34 has a dedicated action; elsewhere the open // descriptors are listed from /proc/self/fd, after the listing has closed its own. bool closeInheritedDescriptors(posix_spawn_file_actions_t& actions) { -#if defined(__GLIBC__) && __GLIBC_PREREQ(2, 34) +// Another libc has no __GLIBC_PREREQ, which the preprocessor would still have to parse. +#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 34)) return ::posix_spawn_file_actions_addclosefrom_np(&actions, 3) == 0; #else std::vector open; @@ -212,13 +269,29 @@ bool closeInheritedDescriptors(posix_spawn_file_actions_t& actions) { } // The CEF browser runs inside the agent: until the agent exits, its threads may write into the profile again, and -// relaunch the helpers ended above. A shell outside the agent's descriptors removes the profile once the agent is gone -// (exited, even if not reaped yet); false when it cannot be started. +// relaunch the helpers ended above. A shell outside the agent's descriptors and process group removes the profile once +// the agent is gone (exited, even if not reaped yet); false when it cannot be started. bool removeAfterExit(const std::filesystem::path& path) noexcept { try { posix_spawn_file_actions_t actions; if (::posix_spawn_file_actions_init(&actions) != 0) return false; + const auto destroyActions = [](posix_spawn_file_actions_t* initialized) { + ::posix_spawn_file_actions_destroy(initialized); + }; + const std::unique_ptr actionsGuard{&actions, destroyActions}; + posix_spawnattr_t attributes; + if (::posix_spawnattr_init(&attributes) != 0) + return false; + const auto destroyAttributes = [](posix_spawnattr_t* initialized) { + ::posix_spawnattr_destroy(initialized); + }; + const std::unique_ptr attributesGuard{&attributes, destroyAttributes}; +#ifdef POSIX_SPAWN_SETSID + // A kill of the agent's process group, by a harness or a CTest timeout, must not prevent the removal. + if (::posix_spawnattr_setflags(&attributes, static_cast(POSIX_SPAWN_SETSID)) != 0) + return false; +#endif // Neither the CLI/MCP pipes, whose EOF the clients wait for, nor the agent's sockets go to the shell. bool prepared = ::posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0) == 0 && ::posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0) == 0 @@ -238,9 +311,7 @@ bool removeAfterExit(const std::filesystem::path& path) noexcept { char* const arguments[] = {const_cast("sh"), const_cast("-c"), const_cast(script), const_cast(agent.c_str()), const_cast(profile.c_str()), nullptr}; pid_t cleaner{}; - prepared = prepared && ::posix_spawn(&cleaner, "/bin/sh", &actions, nullptr, arguments, environ) == 0; - ::posix_spawn_file_actions_destroy(&actions); - return prepared; + return prepared && ::posix_spawn(&cleaner, "/bin/sh", &actions, &attributes, arguments, environ) == 0; } catch (...) { return false; } @@ -253,13 +324,14 @@ struct Profile { #ifdef __linux__ mutable std::atomic released{false}; #endif - /// @param grace how long the WebView2 browser may take to exit on its own before it is ended (Windows only) + /// @param grace how long the browser processes may take to exit on their own before they are ended (Windows and + /// Linux) void cleanup([[maybe_unused]] std::chrono::milliseconds grace) const noexcept { #ifdef __linux__ // A forced exit that loses the race with a normal one cleans up twice: the second would end the first's shell. if (released.exchange(true)) return; - releaseBrowserProcesses(); // the browser's helpers would otherwise recreate the profile + releaseBrowserProcesses(grace); // the browser's helpers would otherwise recreate the profile std::error_code ignored; std::filesystem::remove_all(path, ignored); // what the browser still writes goes after the agent's exit if (!removeAfterExit(path)) diff --git a/test/cmake/CheckJasmineRunner.cmake b/test/cmake/CheckJasmineRunner.cmake index e7e57ab9..b3e1d490 100644 --- a/test/cmake/CheckJasmineRunner.cmake +++ b/test/cmake/CheckJasmineRunner.cmake @@ -39,14 +39,21 @@ foreach(pid IN LISTS pids) foreach(attempt RANGE 1 50) execute_process(COMMAND kill -0 ${pid} RESULT_VARIABLE alive OUTPUT_QUIET ERROR_QUIET) # A killed orphan stays a zombie when the container's PID 1 does not reap it: it holds nothing and is dead. - # The process may also be reaped between the two checks: a stat that cannot be read means it is gone. + # The process may also be reaped between the two checks: a state that cannot be read means it is gone. Linux + # reads it from /proc, which a minimal container image has without ps; macOS has no /proc and asks ps. if(alive STREQUAL "0") - execute_process(COMMAND cat "/proc/${pid}/stat" OUTPUT_VARIABLE stat RESULT_VARIABLE unreadable ERROR_QUIET) - if(NOT unreadable STREQUAL "0" OR stat MATCHES "\\) Z ") + if(EXISTS "/proc/self/stat") + execute_process(COMMAND cat "/proc/${pid}/stat" OUTPUT_VARIABLE stat RESULT_VARIABLE unreadable ERROR_QUIET) + set(zombie "\\) Z ") + else() + execute_process(COMMAND ps -o stat= -p ${pid} OUTPUT_VARIABLE stat RESULT_VARIABLE unreadable ERROR_QUIET) + set(zombie "^[ \t]*Z") + endif() + if(NOT unreadable STREQUAL "0" OR stat MATCHES "${zombie}") set(alive 1) endif() endif() - if(NOT alive STREQUAL "0") + if(NOT alive STREQUAL "0" OR attempt EQUAL 50) break() endif() execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 0.1) diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 97b1f623..2b466200 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -11,6 +11,7 @@ import base64 import hashlib import io +import itertools import tarfile import tempfile import threading @@ -121,7 +122,11 @@ def remaining_profiles(profiles, timeout=10): while True: left = list(profiles.glob("webfront-agent-*")) if not left or time.monotonic() >= deadline: - return left, [str(path.relative_to(profiles)) for profile in left for path in profile.rglob("*")][:40] + # os.walk skips a directory removed while it is listed: the removal may still be under way. Only the + # first 40 entries are walked. + contents = (str(pathlib.Path(directory, name).relative_to(profiles)) + for profile in left for directory, folders, files in os.walk(profile) for name in folders + files) + return left, list(itertools.islice(contents, 40)) time.sleep(0.05) From e1e578c5d37e986b08f5a9032595d84342d26f72 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:17:55 +0100 Subject: [PATCH 6/7] Recognize sandboxed helpers and bound the deferred profile removal [#416] - WebFrontAgent (Linux): drop a helper whose pidfd cannot be opened because it is gone, so its reused identifier is never signalled; only a kernel without pidfds falls back to the identifier. Recognize a non-dumpable CEF helper, whose executable link is hidden, by its command name. - The removal shell reads the agent's state with builtins and waits for about a minute at most. A normal exit, after CefShutdown, starts it only when the profile could not be removed. - Document that the /proc/self/fd fallback lists a snapshot of descriptors. - AutomationClient: create the profile directory without ignore_cleanup_errors, which needs Python 3.10. --- docs/CHANGELOG.md | 9 ++-- js/developer/tools/WebFrontAgent.cpp | 76 +++++++++++++++++++++------- test/tools/AutomationClient.py | 17 ++++++- 3 files changed, 77 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 73abd001..d734c588 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,10 +7,11 @@ exit, which also keeps the status of an exit that completes meanwhile), then retries files pending deletion for 2 s. The watchdog tests check that a forced exit removes the profile, the automation failure messages report the observed run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. On Linux, the - automation agent gives the CEF helpers descending from it (the processes running its own executable) the same - grace, then kills them through pidfds, removes the profile, and leaves a last removal to a shell in its own session - that waits for its exit, since the CEF browser inside the agent writes into the profile until then, and - repeats it for 2 s against a helper relaunched meanwhile; the tests wait up to 10 s for that removal and keep the + automation agent gives the CEF helpers descending from it (the processes running its own executable, recognized by + their command name when the sandbox hides it) the same grace, then kills them through pidfds, removes the profile, + and after a forced exit leaves a last removal to a shell in its own session that waits for its exit (a minute at + most), since the CEF browser inside the agent writes into the profile until then, and repeats it for 2 s against a + helper relaunched meanwhile; the tests wait up to 10 s for that removal and keep the watchdog profile in a short system temporary path. The deadline check of the Jasmine runner waits up to 5 s for a killed orphan to exit and treats one reaped while it reads its state as gone, reading that state with `ps` where there is no `/proc` (macOS). diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index e5ae91f2..0b590468 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -26,6 +26,7 @@ #include #endif #ifdef __linux__ +#include #include #include #include @@ -155,6 +156,25 @@ std::optional> processStat(pid_t pid) { return std::pair{parent, state}; } +// The command name of a process, from /proc//comm, which stays readable when its executable link is not. +std::string commandName(const std::string& process) { + std::ifstream input("/proc/" + process + "/comm"); + std::string name; + std::getline(input, name); + return name; +} + +// Whether a process runs the agent's executable. Chromium makes its sandboxed helpers non-dumpable, which hides their +// executable link from a process without CAP_SYS_PTRACE: such a helper is recognized by its command name, which +// Chromium does not rename for a process's main thread. +bool runsAgent(pid_t pid, const std::string& agentName) { + const auto process = std::to_string(pid); + std::error_code error; + if (std::filesystem::equivalent("/proc/" + process + "/exe", "/proc/self/exe", error)) + return true; + return error == std::errc::permission_denied && !agentName.empty() && commandName(process) == agentName; +} + // The CEF helpers (zygote, renderers, GPU and network services) are the descendants running the agent's own // executable, listed before any is ended (an orphan is reparented and leaves the tree): a WebKitGTK web process or a // command the developer application started is not one of them. @@ -172,20 +192,21 @@ std::vector browserHelpers() { for (std::size_t next = 0; next != tree.size(); ++next) if (const auto found = children.find(tree[next]); found != children.end()) tree.insert(tree.end(), found->second.begin(), found->second.end()); + const auto agentName = commandName("self"); std::vector result; - for (const auto pid : tree | std::views::drop(1)) { - std::error_code error; - if (std::filesystem::equivalent("/proc/" + std::to_string(pid) + "/exe", "/proc/self/exe", error)) + for (const auto pid : tree | std::views::drop(1)) + if (runsAgent(pid, agentName)) result.push_back(pid); - } return result; } -// A pidfd keeps designating the process it was opened on, even once its identifier is reused; -1 without pidfds. +// A pidfd keeps designating the process it was opened on, even once its identifier is reused; -1 with errno ESRCH for +// a process that is gone, ENOSYS without pidfds. int openProcess(pid_t pid) noexcept { #ifdef SYS_pidfd_open return static_cast(::syscall(SYS_pidfd_open, pid, 0)); #else + errno = ENOSYS; return -1; #endif } @@ -222,8 +243,15 @@ struct Helper { void releaseBrowserProcesses(std::chrono::milliseconds grace) noexcept { std::vector helpers; try { - for (const auto pid : browserHelpers()) - helpers.push_back({pid, openProcess(pid)}); + const auto listed = browserHelpers(); + helpers.reserve(listed.size()); + for (const auto pid : listed) { + // A helper gone since the scan needs nothing more, and its identifier may already designate another + // process: only a kernel without pidfds (before Linux 5.3) leaves the identifier to signal. + const int descriptor = openProcess(pid); + if (descriptor >= 0 || errno == ENOSYS) + helpers.push_back({pid, descriptor}); + } // Opened after the scan: a pidfd designates one of our helpers only if its identifier still is one. const auto confirmed = browserHelpers(); std::erase_if(helpers, [&](const Helper& helper) { @@ -253,7 +281,9 @@ void releaseBrowserProcesses(std::chrono::milliseconds grace) noexcept { } // Closes every descriptor from 3 in the spawned process. glibc 2.34 has a dedicated action; elsewhere the open -// descriptors are listed from /proc/self/fd, after the listing has closed its own. +// descriptors are listed from /proc/self/fd, after the listing has closed its own. That list is a snapshot: a +// descriptor another thread opens without O_CLOEXEC before the spawn still reaches the shell. Chromium opens its +// descriptors with O_CLOEXEC, and the shell holds them for its bounded wait at most. bool closeInheritedDescriptors(posix_spawn_file_actions_t& actions) { // Another libc has no __GLIBC_PREREQ, which the preprocessor would still have to parse. #if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 34)) @@ -299,13 +329,15 @@ bool removeAfterExit(const std::filesystem::path& path) noexcept { && closeInheritedDescriptors(actions); const auto agent = std::to_string(::getpid()); const auto profile = path.string(); - // Waits while the agent runs: its stat fields after the command name start with the state ('Z' once exited) and - // have its start time 20th, which tells a reused PID apart. A helper relaunched just before the agent's exit - // ends once the browser is gone, but may recreate the profile meanwhile: the removal is repeated for 2 s. - const char* script = "fields() { sed 's/.*) //' \"/proc/$0/stat\" 2>/dev/null; }; " - "started=$(fields | cut -d' ' -f20); " - "while current=$(fields) && [ \"${current%% *}\" != Z ] " - "&& [ \"$(echo \"$current\" | cut -d' ' -f20)\" = \"$started\" ]; do sleep 0.05; done; " + // Waits while the agent runs, for about a minute at most: its stat fields after the command name start with the + // state ('Z' once exited) and have its start time 20th, which tells a reused PID apart. They are read with + // builtins, so a poll only starts sleep. A helper relaunched just before the agent's exit ends once the browser + // is gone, but may recreate the profile meanwhile: the removal is repeated for 2 s. + const char* script = "probe() { read -r line 2>/dev/null < \"/proc/$0/stat\" || return 1; " + "set -- ${line##*\") \"}; state=$1; start=${20}; }; " + "probe && started=$start; i=0; " + "while [ $i -lt 1200 ] && probe && [ \"$state\" != Z ] && [ \"$start\" = \"$started\" ]; " + "do sleep 0.05; i=$((i + 1)); done; " "rm -rf -- \"$1\"; i=0; while [ $i -lt 20 ]; do sleep 0.1; " "if [ -e \"$1\" ]; then rm -rf -- \"$1\"; fi; i=$((i + 1)); done"; char* const arguments[] = {const_cast("sh"), const_cast("-c"), const_cast(script), @@ -326,14 +358,20 @@ struct Profile { #endif /// @param grace how long the browser processes may take to exit on their own before they are ended (Windows and /// Linux) - void cleanup([[maybe_unused]] std::chrono::milliseconds grace) const noexcept { + /// @param browserRunning whether the browser may still write into the profile until the agent exits (a forced exit; + /// Linux only) + void cleanup([[maybe_unused]] std::chrono::milliseconds grace, [[maybe_unused]] bool browserRunning = false) const noexcept { #ifdef __linux__ // A forced exit that loses the race with a normal one cleans up twice: the second would end the first's shell. if (released.exchange(true)) return; releaseBrowserProcesses(grace); // the browser's helpers would otherwise recreate the profile - std::error_code ignored; - std::filesystem::remove_all(path, ignored); // what the browser still writes goes after the agent's exit + std::error_code error; + std::filesystem::remove_all(path, error); + // After a normal exit, CefShutdown has returned: a removed profile stays removed. Otherwise, what the browser + // still writes goes after the agent's exit. + if (!browserRunning && !error && !std::filesystem::exists(path, error) && !error) + return; if (!removeAfterExit(path)) std::cerr << "Automation: cannot schedule the removal of the temporary profile\n"; #else @@ -674,7 +712,7 @@ int main(int argc, char** argv) { if (channel) channel->stop(); // _Exit skips the destructors. The browser already had the close grace above: end it now. - profile.cleanup(std::chrono::milliseconds{0}); + profile.cleanup(std::chrono::milliseconds{0}, true); // Ending the browser can release a blocked main thread: an exit completed meanwhile keeps its // own status and destructors. if (!done.load()) diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 2b466200..6e547a30 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -9,6 +9,7 @@ import socket import os import base64 +import contextlib import hashlib import io import itertools @@ -113,6 +114,18 @@ def close(self): self.reader.join(timeout=2) +@contextlib.contextmanager +def profile_directory(): + """A private directory in the system temporary directory, whose removal tolerates what the agent still removes. + + tempfile.TemporaryDirectory takes ignore_cleanup_errors only from Python 3.10.""" + path = tempfile.mkdtemp(prefix="wf-profile-") + try: + yield path + finally: + shutil.rmtree(path, ignore_errors=True) + + def remaining_profiles(profiles, timeout=10): """The agent profiles left in `profiles`, once removed or after `timeout` seconds, with what they contain. @@ -276,7 +289,7 @@ def watchdog(args): # A private temporary directory isolates the native profile, which the forced exit must still remove. It is # created in the system temporary directory, not under the work path: Chromium puts its singleton Unix socket # there, and sockaddr_un limits that path to about 108 bytes whatever the checkout's depth. - with tempfile.TemporaryDirectory(prefix="wf-profile-", ignore_cleanup_errors=True) as profile_root: + with profile_directory() as profile_root: profiles = pathlib.Path(profile_root).resolve() forced_environment = dict(os.environ, TMPDIR=str(profiles), TEMP=str(profiles), TMP=str(profiles)) with (pathlib.Path(args.work) / "watchdog.log").open("w") as log: @@ -415,7 +428,7 @@ def main(): endpoint = pathlib.Path(temporary) / "shared-window" # Keep Chromium's temporary Unix socket paths below sockaddr_un's limit, independently # of the checkout/work path length. The agent still creates its own private child profile. - with tempfile.TemporaryDirectory(prefix="wf-profile-", ignore_cleanup_errors=True) as profile_root, (pathlib.Path(temporary) / "shared.log").open("w") as log: + with profile_directory() as profile_root, (pathlib.Path(temporary) / "shared.log").open("w") as log: profiles = pathlib.Path(profile_root).resolve() owner_environment = dict(os.environ, TMPDIR=str(profiles), TEMP=str(profiles), TMP=str(profiles)) owner = subprocess.Popen([args.agent, *command, "--serve", "--listen", str(endpoint), From 2efc082d0f92e270e1c97c8b80947f4ca09fb40a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:37:03 +0100 Subject: [PATCH 7/7] Verify a helper's identifier before signalling it and settle the profile check [#416] - WebFrontAgent (Linux): follow a helper whose pidfd cannot be opened for a reason other than its exit (seccomp, no descriptor left) by its identifier, signalled only if a scan just before still finds it among the helpers. Mark the parameter of openProcess unused where there is no pidfd_open. - AutomationClient: create the profile directory in /tmp on Linux rather than in an inherited, possibly long TMPDIR, and count a profile as removed once absent for 2.5 s, longer than the agent's repeated removal. --- js/developer/tools/WebFrontAgent.cpp | 24 +++++++++++++++++++----- test/tools/AutomationClient.py | 26 +++++++++++++++++++------- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index 0b590468..f78c2d54 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -202,7 +202,7 @@ std::vector browserHelpers() { // A pidfd keeps designating the process it was opened on, even once its identifier is reused; -1 with errno ESRCH for // a process that is gone, ENOSYS without pidfds. -int openProcess(pid_t pid) noexcept { +int openProcess([[maybe_unused]] pid_t pid) noexcept { #ifdef SYS_pidfd_open return static_cast(::syscall(SYS_pidfd_open, pid, 0)); #else @@ -215,7 +215,10 @@ struct Helper { pid_t pid; int descriptor; bool killed = false; + bool gone = false; // without a pidfd, its identifier no longer designates one of the helpers bool exited() const { + if (gone) + return true; if (descriptor < 0) { const auto stat = processStat(pid); return !stat || stat->second == 'Z' || stat->second == 'X'; @@ -247,9 +250,10 @@ void releaseBrowserProcesses(std::chrono::milliseconds grace) noexcept { helpers.reserve(listed.size()); for (const auto pid : listed) { // A helper gone since the scan needs nothing more, and its identifier may already designate another - // process: only a kernel without pidfds (before Linux 5.3) leaves the identifier to signal. + // process. Without a pidfd (a kernel before Linux 5.3, a seccomp filter, no descriptor left), the helper is + // still followed by its identifier, which is checked before it is signalled. const int descriptor = openProcess(pid); - if (descriptor >= 0 || errno == ENOSYS) + if (descriptor >= 0 || errno != ESRCH) helpers.push_back({pid, descriptor}); } // Opened after the scan: a pidfd designates one of our helpers only if its identifier still is one. @@ -266,10 +270,20 @@ void releaseBrowserProcesses(std::chrono::milliseconds grace) noexcept { const auto now = std::chrono::steady_clock::now(); if (std::ranges::all_of(helpers, &Helper::exited) || now >= terminated) break; - if (now >= ended) - for (auto& helper : helpers) + if (now >= ended) { + // An identifier without a pidfd is signalled only if a scan just before, while none is ended yet, + // still finds it among the helpers: otherwise it may designate another process. + const auto unverified = [](const Helper& helper) { + return helper.descriptor < 0 && !helper.killed && !helper.exited(); + }; + const auto current = std::ranges::any_of(helpers, unverified) ? browserHelpers() : std::vector{}; + for (auto& helper : helpers) { + if (unverified(helper) && std::ranges::find(current, helper.pid) == current.end()) + helper.gone = true; if (!helper.exited()) helper.kill(); + } + } std::this_thread::sleep_for(std::chrono::milliseconds{20}); } } catch (...) { diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 6e547a30..36cdca3f 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -7,6 +7,7 @@ import shutil import subprocess import socket +import sys import os import base64 import contextlib @@ -118,23 +119,34 @@ def close(self): def profile_directory(): """A private directory in the system temporary directory, whose removal tolerates what the agent still removes. - tempfile.TemporaryDirectory takes ignore_cleanup_errors only from Python 3.10.""" - path = tempfile.mkdtemp(prefix="wf-profile-") + tempfile.TemporaryDirectory takes ignore_cleanup_errors only from Python 3.10. On Linux, the directory is in /tmp + rather than an inherited TMPDIR, which may be long: Chromium's singleton socket path must stay below sockaddr_un's + limit.""" + root = "/tmp" if sys.platform.startswith("linux") and os.access("/tmp", os.W_OK | os.X_OK) else None + path = tempfile.mkdtemp(prefix="wf-profile-", dir=root) try: yield path finally: shutil.rmtree(path, ignore_errors=True) -def remaining_profiles(profiles, timeout=10): - """The agent profiles left in `profiles`, once removed or after `timeout` seconds, with what they contain. +def remaining_profiles(profiles, timeout=10, settle=2.5): + """The agent profiles left in `profiles`, once absent for `settle` seconds or after `timeout` more, with what + they contain. On Linux, the CEF browser runs inside the agent and may write until it exits: the agent then leaves the - last removal to a process that waits for its exit.""" - deadline = time.monotonic() + timeout + last removal to a process that waits for its exit and repeats it for 2 s against a helper relaunched meanwhile. + A profile is gone only once absent for longer than that.""" + deadline = time.monotonic() + timeout + settle + absent_since = None while True: left = list(profiles.glob("webfront-agent-*")) - if not left or time.monotonic() >= deadline: + now = time.monotonic() + if left: + absent_since = None + elif absent_since is None: + absent_since = now + if (absent_since is not None and now - absent_since >= settle) or now >= deadline: # os.walk skips a directory removed while it is listed: the removal may still be under way. Only the # first 40 entries are walked. contents = (str(pathlib.Path(directory, name).relative_to(profiles))