Repository navigation
move the taskkill and sysctl call-outs to in-process helpers - #19286
Conversation
Adds core::system::terminateProcessTree(pid): on Windows it opens the root and every descendant it finds (so no pid can be recycled under it), terminates the root first and then the descendants, treating an already exited process as success; on POSIX it signals the root and the descendants collected while the root was alive. Stopping a Quarto job on Windows now calls it instead of running taskkill /F /T through a shell, and gets a proper Error back. Exposes core::system::isAppleSilicon() to R as .rs.isAppleSilicon(), and uses it in .rs.rig.machine() instead of shelling out to sysctl. Addresses #19285
The Windows tree walk now takes its own snapshot and opens every listed child before checking it is the listed process: created after the snapshot means the pid was recycled, created before its parent means an orphan reporting a recycled parent pid. Either is dropped, so nothing is terminated by pid alone. The POSIX test reaps or kills both processes on every exit path, polls waitpid() instead of blocking, restores the subreaper setting, and gives the children an alarm as a safety net.
The Windows walk now also compares the opened process's image name with the snapshot's, the one identity check that does not depend on the clock, and the validation is detail::isListedProcess with unit tests for a recycled pid, another image, an orphan, and unqueryable times. processInfo(pid) split the whole /proc/<pid>/stat line on spaces, so a command name with a space shifted the parent pid field and hid the process from getChildProcesses(); it now parses what follows the name's closing parenthesis, as creationTime() does. The POSIX terminator also signals the root even when its descendants cannot be found. The tree test learns the grandchild's pid over a pipe, so cleanup can reach it even if discovery fails, and names it "worker thread" on Linux to cover the parse fix.
…s group The Windows walk enumerates with PROCESSENTRY32W and queries the image name with QueryFullProcessImageNameW, comparing with CompareStringOrdinal: in an ANSI code page such as CP932 a character's trailing byte can be a backslash, which split the name wrongly and rejected a real descendant. In the tree test the child puts itself and the grandchild in a process group, so cleanup can kill and reap the grandchild even before its pid was received; the grandchild reports its own pid after renaming itself, so receipt means the regression precondition holds; and the pipe read retries interrupted calls until a deadline.
openProcessTree() now reads a single Toolhelp snapshot into a parent to children map and walks it breadth-first from the root, visiting each pid once, so a tree that keeps spawning is terminated as listed rather than chased through fresh snapshots. The tree test's cleanup also reaps the child by pid, for the case where it never joined the process group. The Windows fixture launches with CreateProcessW, and a test runs a copy of ping.exe under a non-ASCII name through cmd.exe and checks the tree termination takes it.
…om the parent A descendant that denies PROCESS_TERMINATE is opened for querying alone, so it is still validated and its own descendants reached; terminating it fails and is logged. A test with a cmd.exe -> cmd.exe -> ping.exe tree denies termination on the middle one and checks ping.exe still goes. The tree test's parent also calls setpgid(child, child), so the group exists before the timed pipe read however far the child has got.
The Windows walk no longer compares creation times with a wall-clock snapshot time. The opened process must record the held parent as its parent (NtQueryInformationProcess, ProcessBasicInformation): that pid cannot be recycled while the parent's handle is open, so a process recording it was spawned by it, and one recycled by any other parent is rejected whatever the clock did. The image-name and orphan checks stay. A test checks the parent pid is queryable through a limited-access handle, the access the walk uses.
A listed process that is gone by the time it is opened no longer hides the descendants it left behind: the walk continues to its listed children, checked against the listed pid and the creation time of the nearest ancestor still held. The snapshot and the walk are now detail::listProcesses and detail::openProcessTree, so a test can list a cmd.exe -> cmd.exe -> ping.exe tree, terminate the middle process, and check the walk over the old listing still opens ping.exe.
A listed process that is gone by the time it is opened is skipped with its subtree after all: its descendants record only its pid, which can have gone to a new process by then, so nothing establishes that they belong to the tree, and terminating an unrelated process is the worse failure. The comment on openProcessTree says so and names a job object per launch as the deterministic alternative. The test lists the three level tree, terminates the middle process, closes every handle to it and waits for the root to exit so that it is no longer openable, and checks the orphan is left alone. tlhelp32.h in the tests now follows windows.h.
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
…ns (#19296) Two flakes from the PR #19286 e2e run (40398345386): - code_suggestions 'ghost text accept' (Posit AI, Linux): every agent answer took 10s+ and the session cancelled the re-request at its 10s cutoff. The suggestion waits now skip as a service failure when a request was cancelled and every answer that did arrive was slow. - shiny-app-r (Windows): the assistant built the tip choices with radioButtons(), which the button-only locator could not match. Match a button or radio by accessible name instead.
gtritchie
left a comment
There was a problem hiding this comment.
Nothing here is blocking. The request-changes state is procedural.
Main items: no guard for pid <= 0 in the new POSIX terminateProcessTree() (on macOS a pid of 0 reaches every process), and an inaccurate comment about why the Windows walk lists before terminating. The rest are a design question about #19287, test hygiene, and small cleanups.
| return terminateProcessTree(pid, SIGTERM); | ||
| } | ||
|
|
||
| Error terminateProcessTree(pid_t pid, int signal) |
There was a problem hiding this comment.
Nothing guards pid <= 0 here, and kill() treats those values specially: 0 is the caller's own process group, -1 is every process the user can signal. On macOS it is worse: proc_listchildpids(0, ...) returns launchd (pid 1) (checked on an Apple silicon Mac), so getChildProcesses(0) recurses through the whole system and every process found gets SIGTERM. No current caller passes 0 (QuartoJob checks pid_ > 0 and is Windows-only), but this is a new public API declared in System.hpp. Suggest returning EINVAL for pid <= 0, here and in the Windows version for symmetry.
There was a problem hiding this comment.
Done in c052696: EINVAL for pid <= 0 on POSIX. I left Windows as is: PidType is a DWORD there, and OpenProcess(0) already fails with ERROR_INVALID_PARAMETER.
|
|
||
| for (const ProcessInfo& process : descendants) | ||
| { | ||
| if (::kill(process.pid, signal) != 0 && errno != ESRCH) |
There was a problem hiding this comment.
Descendants are signalled by bare pid after the root has been signalled, and nothing pins those pids. If one exits after getChildProcesses() returns and its pid is reused, an unrelated process gets the signal. The window is short, and terminateChildProcesses() already has the same pattern, but the Windows half of this PR goes to some length to rule out exactly this. A pidfd on Linux (or re-checking the ppid just before kill()) would bring the two halves in line. Fine as a follow-up.
There was a problem hiding this comment.
Agreed, filed as #19302. The POSIX path has no production caller yet (the Quarto stop is Windows-only), so I'd rather do pidfd or a ppid re-check there than grow this PR.
| return LAST_SYSTEM_ERROR(); | ||
| CloseHandleOnExitScope closeRoot(&hRoot, ERROR_LOCATION); | ||
|
|
||
| // the descendants have to be found while the root is alive: once it has |
There was a problem hiding this comment.
I don't think the reason given here holds. hRoot is held for the whole function, so the root's pid can't be recycled even after it exits. Its children still record that pid and still postdate it, so isListedProcess() would accept them. Only an intermediate whose handle nobody holds becomes unreachable. Listing before terminating is still sensible (it bounds the walk), but the comment gives the wrong reason.
There was a problem hiding this comment.
You're right: holding hRoot keeps its children reachable. The real reason is that terminating the root can make an intermediate exit (on a broken pipe, say) before its handle is held, which takes its subtree out of reach. The comment says that now (618e164).
| // longer be established, and terminating an unrelated process would be the | ||
| // worse failure. A job object per launch would be the deterministic answer | ||
| // (#19287). | ||
| void openProcessTree(HANDLE hRoot, |
There was a problem hiding this comment.
Design question rather than a defect: this walk (snapshot, image name, ntdll parent pid, creation time) approximates tree membership and still has the exited-intermediate gap. A job object assigned when the quarto child is launched would give exact membership. ProcessOptions::terminateChildren (Process.hpp:120-126) already notes that Win32 needs CreateJobObject for this. I see #19287 tracks it. Is the interim heuristic, with its ntdll dependency and tests, worth carrying until then, or could #19287 be done first?
There was a problem hiding this comment.
I'd keep it. It replaces taskkill /T, which walks the same snapshot by bare pid with no protection against pid reuse, so this is strictly safer, and it is green on Windows CI. #19287 changes the shared Win32ChildProcess launch path (suspended start, a job nested in the session's initJobObject job, terminate routing), and I'd like that reviewed on its own. When it lands, QuartoJob moves to it, and the walk can go if nothing else needs a pid-only kill.
| EXPECT_EQ(WAIT_OBJECT_0, ::WaitForSingleObject(pi.hProcess, 5000)); | ||
| EXPECT_EQ(WAIT_OBJECT_0, ::WaitForSingleObject(hGrandchild, 5000)); | ||
|
|
||
| tempDir.remove(); |
There was a problem hiding this comment.
This cleanup is skipped whenever an earlier ASSERT_* fails (e.g. WaitForSubprocesses() returning empty), which leaves the copied ソ.exe in %TEMP%. Its result is also ignored, and it can fail while the image is still mapped. A scope-exit cleanup that logs failures would cover both.
There was a problem hiding this comment.
Done in 618e164: RemoveOnExitScope, declared before the grandchild's handle so it runs after that closes; a failure to remove is logged.
| TEST_F(Win32ProcessTest, TerminateProcessTreeTakesDescendants) | ||
| { | ||
| // cmd.exe -> ping.exe, a two-level tree | ||
| ASSERT_TRUE(StartProcess("cmd.exe /S /C \"ping -n 8 posit.co\" 1> nul")); |
There was a problem hiding this comment.
Nit: the new tests (here and at 621, 703, 762, 805, 814) ping posit.co, which needs DNS. Without DNS, ping exits immediately and the tree is gone before terminateProcessTree() runs. Some older tests in this file do the same, but the newer ones use ping -n 30 127.0.0.1, which avoids the network.
There was a problem hiding this comment.
Done in 618e164: the new tests use ping -n 30 127.0.0.1.
| if (error) | ||
| return error; | ||
|
|
||
| std::size_t nameEnd = statStr.rfind(')'); |
There was a problem hiding this comment.
This repeats the parse in ProcessInfo::creationTime() below (read stat, rfind(')'), trim_copy, split). Could both use one helper that returns the fields after the command name, so a future fix lands in both places?
There was a problem hiding this comment.
Done in c052696: both use readStatFieldsAfterName().
| int signal); | ||
|
|
||
| // signal version of the terminateProcessTree() declared in System.hpp | ||
| Error terminateProcessTree(pid_t pid, int signal); |
There was a problem hiding this comment.
The only production caller of terminateProcessTree() is QuartoJob::stop(), inside #ifdef _WIN32, so this overload, the POSIX implementation, and the POSIX tests currently have no caller. Keeping the cross-platform API complete is a fair reason to keep the one-argument form, but is the signal overload needed?
| std::vector<SubprocInfo> getSubprocesses(PidType pid, | ||
| const FILETIME* pParentCreationTime); | ||
|
|
||
| struct OpenedProcess |
There was a problem hiding this comment.
Minor: these redefine OpenedProcess and ProcessListing by hand. If either changes in Win32System.cpp only, the two translation units disagree on the layout. That is an ODR violation that still links, and openProcessTree() then fills a vector the test reads with the wrong layout. A small Win32 detail header shared by both files would prevent it.
There was a problem hiding this comment.
Done in 618e164: Win32SystemDetail.hpp holds the declarations both files use, detail::getSubprocesses included.
kill() reads 0 as the caller's process group and -1 as every process it can signal, and on macOS the children of pid 0 are the whole system, so terminateProcessTree() now returns EINVAL for pid <= 0. The signal overload had no caller and is gone. processInfo(pid) and ProcessInfo::creationTime() share one helper for the fields that follow the command name in /proc/<pid>/stat.
Win32SystemDetail.hpp declares what Win32SystemTests.cpp reaches into, so the two cannot disagree on the layout of OpenedProcess or ProcessListing. The comment on opening the tree before terminating it now gives the real reason: terminating the root can make an intermediate exit before its handle is held. The new tests ping the loopback address instead of needing DNS, and the copied non-ASCII executable is removed on scope exit, after the grandchild's handle closes, with failures logged.
…s-tree-and-apple-silicon # Conflicts: # src/cpp/core/include/core/system/System.hpp # src/cpp/core/system/Win32SystemTests.cpp # src/cpp/session/modules/SessionRUtil.R # src/cpp/session/modules/SessionRUtil.cpp
The call runs in a child that leads its own process group and blocks SIGTERM, so a pid that slipped through could reach nothing else and would leave SIGTERM pending instead of ending the child. 0 and -1 reach beyond any such group and are not exercised.
|
|
||
| // declared before the grandchild's handle so it runs after that closes, | ||
| // and on every early return; a failure to remove is logged | ||
| RemoveOnExitScope removeTempDir(tempDir, ERROR_LOCATION); |
There was a problem hiding this comment.
Optional nit: this runs on every early return, but it can't succeed on one that happens after StartProcess() and before terminateProcessTree(), for example when ASSERT_EQ(1u, children.size()) fails. The copied exe is still running at that point, because the fixture's job is only closed in ~Win32ProcessTest(), which runs after this scope's locals have been destroyed. The removal then fails and is only logged, and the temp dir leaks. Calling CleanupProcess() before the scope ends (or a scope guard declared after this one that calls it) would close that gap. Fine to leave as is.
Fixes #19285.
Follows the pattern from #19233 for the two remaining shell call-outs the survey in #19285 found worth moving in-process.
Stopping a Quarto job on Windows
QuartoJob::stop()rantaskkill /F /T /PID <pid>throughrunCommandand parsed stderr. It now calls a newcore::system::terminateProcessTree(pid), which returns a properError:Windows: takes one Toolhelp snapshot and walks it breadth-first from the root, opening each listed child before trusting it and keeping the handle until termination, so no pid can be recycled underneath the walk. A child is accepted only if the opened process's image name matches the listing (wide-character comparison, so CP932 names whose trailing byte is a backslash survive), the parent it records (via ntdll
NtQueryInformationProcess) is the pid of the parent whose handle is held (that pid cannot be recycled while the handle is open), and it does not predate that parent (the orphan heuristicgetSubprocesses()already uses). A child that refusesPROCESS_TERMINATEis opened for querying only so the walk still reaches its descendants; terminating it fails and is logged. The root is terminated first so it cannot spawn more, then the descendants. An already-exited process counts as success. Failures on descendants are logged; the result reflects the root only.Stated limitation: an intermediate that exits between the snapshot and being opened takes its subtree out of reach, because its descendants record only its pid, which may have gone to a new process by then, and terminating an unrelated process is the worse failure. A job object per launch in the child-process launcher would be the deterministic answer: terminate Windows child process trees through a per-launch job object #19287.
POSIX: collects the descendants with
getChildProcesses()while the root is alive (once it exits they are reparented and unreachable from its pid), signals the root withSIGTERM(even if discovery failed), then the descendants, ignoringESRCH. Apid <= 0is rejected withEINVAL:kill()reads those as process groups or every process, and on macOS the children of pid 0 are the whole system. Signalling descendants by pid without pinning them is a follow-up: signal POSIX process-tree descendants without pid-reuse races #19302.Also fixed on the way:
processInfo(pid)on Linux split the whole/proc/<pid>/statline on spaces, so a command name with a space shifted the parent-pid field and hid the process fromgetChildProcesses()(and so fromterminateChildProcesses()). It now parses what follows the name's closing parenthesis, asProcessInfo::creationTime()already did.Apple silicon check in
SessionRig.R.rs.rig.machine()shelled out to/usr/sbin/sysctl -n hw.optional.arm64to tell an x86_64 R under Rosetta from an Intel Mac.SessionRUtil.cppnow registersrs_isAppleSilicon(wrapping the existingcore::system::isAppleSilicon(),FALSEoff macOS), exposed as.rs.isAppleSilicon(), andrig.machine()uses it.Tests
Win32SystemTests.cpp(compile and run only on the Windows CI job):terminateProcessTreetakes acmd.exe -> ping.exetree, a process without descendants, an already-exited process, a descendant with a non-ASCII name (a copy of ping.exe named with U+30BD, launched throughCreateProcessW), and a three-level tree whose middle process has a DACL denyingPROCESS_TERMINATE;isListedProcesshas deterministic cases for same-image pid reuse from another parent, another image, an orphan, and unqueryable fields; the ntdll parent-pid query is checked through a limited-access handle; and the walk over a stale listing stops at an intermediate that has exited.PosixSystemTests.cpp: a forked child -> grandchild tree (the grandchild namedworker threadon Linux, covering the/procparse fix) with the grandchild's pid reported over a pipe and both processes in their own process group so cleanup is bounded on every path; both end withSIGTERM. On Linux the test makes itself a child subreaper so it can reap the grandchild itself. Also: a missing pid is an error.test-rig.R: on macOS,.rs.isAppleSilicon()and.rs.rig.machine("x86_64")are checked against thesysctloracle the shell call-out replaced; elsewhere.rs.isAppleSilicon()isFALSE.Verified locally on an Apple silicon Mac, after merging main: the full
PosixTestscore suite (42 pass, 1 pre-existing skip) and r-scoperig|linter(357 pass, 1 pre-existing skip). The Windows tests need the Windows CI job.No NEWS entry: there is no user-visible change.
QA Notes
On Windows, stop a running Quarto preview job from the Jobs pane and confirm the
quarto/denoprocesses are gone (Task Manager) and nothing is logged about the stop. On an Apple silicon Mac with an x86_64 build of R, open a project whose renv lockfile asks for an R version that is not installed and confirm the warning bar offers an arm64 install.