The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
fix(run,debug): Stop ends the whole launched process tree (#2416)
Vadim Lazukcc53be62d0d8
diff --git a/crates/ide-core/Cargo.toml b/crates/ide-core/Cargo.tomlindex 759abf8e6..f8c23a0cb 100644--- a/crates/ide-core/Cargo.toml+++ b/crates/ide-core/Cargo.toml@@ -23,4 +23,4 @@ tempfile.workspace = truelibc = "0.2"[target.'cfg(windows)'.dependencies]-windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }+windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }diff --git a/crates/ide-core/src/process.rs b/crates/ide-core/src/process.rsindex 0f0b47e1d..daed2ca49 100644--- a/crates/ide-core/src/process.rs+++ b/crates/ide-core/src/process.rs@@ -104,6 +104,8 @@ fn signal_group(child: &Child, signal: libc::c_int) {#[cfg(windows)]const TREE_EXIT_WAIT: Duration = Duration::from_secs(5);+#[cfg(windows)]+pub use windows_job::Job;#[cfg(windows)]pub use windows_tree::ProcessTree;@@ -251,6 +253,167 @@ mod windows_tree {}}+/// A kernel job object over one launched process tree. Everything a launch starts joins+/// the job by inheritance, so [`Job::terminate`] ends the whole tree — also processes+/// started after the launch's snapshot was taken, orphans of a launcher that already+/// exited (where a `taskkill /T /F` from the tracked pid no longer finds them), and+/// processes born in the window a process-enumeration kill would miss. Spawns assign+/// their root right after it starts; when the assignment fails (an enclosing job that+/// disallows nesting, an already-exited pid), callers fall back to `taskkill /T /F`.+#[cfg(windows)]+mod windows_job {+ use std::mem::size_of;+ use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};+ use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, INVALID_HANDLE_VALUE};+ use windows_sys::Win32::System::JobObjects::{+ AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+ JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,+ JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation, QueryInformationJobObject,+ SetInformationJobObject, TerminateJobObject,+ };+ use windows_sys::Win32::System::Threading::{IO_COUNTERS, OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};++ /// A job object holding one launch's processes. The handle is kept open for the+ /// launch's lifetime: `KILL_ON_JOB_CLOSE` ends anything still in the job when the+ /// launch record (a run entry, a debug session) is finally dropped.+ pub struct Job(OwnedHandle);++ impl Job {+ /// Takes the just-started `child` into a new job, so everything it starts is in+ /// there too. `None` when the job could not be made or the process rejected the+ /// assignment (callers fall back to `taskkill /T /F` from the child's pid).+ pub fn for_child(child: &std::process::Child) -> Option<Job> {+ // SAFETY: the child's own handle is a live process handle.+ Self::from_handle(child.as_raw_handle())+ }++ /// [`Job::for_child`] for a process known by its id (a PTY child, a follow-up run,+ /// a `tokio` child). `None` when the id no longer names an openable process — a+ /// caller that holds the child cannot have had it reaped, so this is a dead or+ /// already-gone launch.+ pub fn for_pid(pid: u32) -> Option<Job> {+ // SAFETY: plain call; a non-null result is a process handle owned by the caller.+ // Assignment needs `SET_QUOTA | TERMINATE` on the process.+ let handle = unsafe { OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, 0, pid) };+ if handle.is_null() {+ return None;+ }+ // SAFETY: the handle was just opened and is owned here.+ let handle = unsafe { OwnedHandle::from_raw_handle(handle) };+ Self::from_handle(handle.as_raw_handle())+ }++ fn from_handle(handle: RawHandle) -> Option<Job> {+ // SAFETY: plain calls; a non-null result is a job handle owned by the caller.+ let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };+ if job.is_null() || job == INVALID_HANDLE_VALUE {+ return None;+ }+ // SAFETY: the job handle is owned here and `limits` is sized as the API requires.+ let job = unsafe { OwnedHandle::from_raw_handle(job) };+ let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {+ BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {+ PerProcessUserTimeLimit: 0,+ PerJobUserTimeLimit: 0,+ LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+ MinimumWorkingSetSize: 0,+ MaximumWorkingSetSize: 0,+ ActiveProcessLimit: 0,+ Affinity: 0,+ PriorityClass: 0,+ SchedulingClass: 0,+ },+ IoInfo: IO_COUNTERS {+ ReadOperationCount: 0,+ WriteOperationCount: 0,+ OtherOperationCount: 0,+ ReadTransferCount: 0,+ WriteTransferCount: 0,+ OtherTransferCount: 0,+ },+ ProcessMemoryLimit: 0,+ JobMemoryLimit: 0,+ PeakProcessMemoryUsed: 0,+ PeakJobMemoryUsed: 0,+ };+ // SAFETY: the job handle is owned here and `limits` is sized as the API requires.+ let ok = unsafe {+ SetInformationJobObject(+ job.as_raw_handle(),+ JobObjectExtendedLimitInformation,+ &mut limits as *mut _ as *const _,+ size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,+ )+ };+ if ok == 0 {+ return None;+ }+ // SAFETY: the process handle belongs to the just-spawned child and outlives+ // this call; the job handle is owned here.+ let ok = unsafe { AssignProcessToJobObject(job.as_raw_handle(), handle) };+ if ok == 0 {+ return None;+ }+ Some(Job(job))+ }++ /// Adds another just-started root of the same launch to the job (a Go build's+ /// follow-up run, a JVM a debug session starts itself). `false` when it did not+ /// take; the process then relies on its own kill.+ pub fn assign_pid(&self, pid: u32) -> bool {+ // SAFETY: plain call; the handle is opened only to assign it, and the job+ // handle is owned and valid.+ let handle = unsafe { OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, 0, pid) };+ if handle.is_null() {+ return false;+ }+ // SAFETY: both handles are valid for the duration of the call.+ let ok = unsafe { AssignProcessToJobObject(self.0.as_raw_handle(), handle) };+ // SAFETY: the process handle was opened above and is owned here.+ unsafe { drop(OwnedHandle::from_raw_handle(handle)) };+ ok != 0+ }++ /// Terminates every process in the job. `false` when the call failed (the job+ /// handle is invalid): callers then fall back to `taskkill /T /F`. Termination is+ /// asynchronous; poll [`Job::is_running`] (bounded by [`TREE_EXIT_WAIT`]) until+ /// the tree is gone.+ pub fn terminate(&self) -> bool {+ // SAFETY: a job handle owned here.+ unsafe { TerminateJobObject(self.0.as_raw_handle(), 1) != 0 }+ }++ /// Whether any process of the launch is still in the job. When the job's state+ /// cannot be read, reports gone: waits on this must not wedge, and a kill via+ /// [`Job::terminate`] does not depend on the answer.+ pub fn is_running(&self) -> bool {+ // A list of one is the common case; `ERROR_MORE_DATA` says the real list is+ // longer, which means there are processes.+ let mut list = JOBOBJECT_BASIC_PROCESS_ID_LIST {+ NumberOfAssignedProcesses: 0,+ NumberOfProcessIdsInList: 0,+ ProcessIdList: [0],+ };+ let mut returned = 0u32;+ // SAFETY: the job handle is owned here and `list` is sized as the API requires.+ let ok = unsafe {+ QueryInformationJobObject(+ self.0.as_raw_handle(),+ JobObjectBasicProcessIdList,+ &mut list as *mut _ as *mut _,+ size_of::<JOBOBJECT_BASIC_PROCESS_ID_LIST>() as u32,+ &mut returned,+ )+ };+ if ok != 0 {+ list.NumberOfProcessIdsInList > 0+ } else {+ std::io::Error::last_os_error().raw_os_error() == Some(ERROR_MORE_DATA as i32)+ }+ }+ }+}+/// Gives `cmd` the host's environment back when the IDE runs from an AppImage. `AppRun` and/// its hooks point `LD_LIBRARY_PATH`, `PATH`, `XDG_DATA_DIRS`, `GIO_MODULE_DIR`, `GTK_PATH`,/// `GST_PLUGIN_*`, ... into the mounted image for the IDE itself; a host program that@@ -956,3 +1119,66 @@ mod kill_tests {assert!(started.elapsed() < Duration::from_secs(5));}}++#[cfg(all(test, windows))]+mod job_tests {+ use super::*;+ use std::os::windows::process::CommandExt;+ use std::process::Stdio;+ use std::time::Instant;++ /// `cmd` that keeps a `ping` grandchild for a minute, like a launcher that started an+ /// application: the job must reach both.+ fn launch_tree() -> (std::process::Child, Job, ProcessTree) {+ let mut cmd = Command::new("cmd");+ cmd.args(["/D", "/S", "/C", "ping -n 60 127.0.0.1 >NUL"]).stdin(Stdio::null()).creation_flags(CREATE_NO_WINDOW);+ let child = cmd.spawn().unwrap();+ let job = Job::for_child(&child).expect("the job takes the launch");+ let tree = ProcessTree::capture(child.id());+ assert!(tree.is_running(), "cmd started a grandchild the job inherits");+ (child, job, tree)+ }++ /// Termination is asynchronous: the job reports its processes gone while their+ /// handles still wait, so wait on the handles (the reused-pid-proof oracle).+ fn assert_gone(tree: &ProcessTree) {+ let until = Instant::now() + Duration::from_secs(10);+ while tree.is_running() {+ assert!(Instant::now() < until, "the tree survived the job");+ std::thread::sleep(Duration::from_millis(20));+ }+ }++ #[test]+ fn job_terminates_the_tree_the_root_started() {+ let (mut child, job, tree) = launch_tree();+ assert!(job.is_running());+ assert!(job.terminate(), "TerminateJobObject succeeds");+ // The captured tree's handles survive the root's death, so the wait below is the+ // grandchild's, not a reused pid's.+ assert_gone(&tree);+ assert!(!job.is_running());+ let _ = child.wait();+ }++ #[test]+ fn a_later_spawned_root_joins_the_job() {+ let (mut first, job, _) = launch_tree();+ let mut cmd = Command::new("cmd");+ cmd.args(["/D", "/S", "/C", "ping -n 60 127.0.0.1 >NUL"]).stdin(Stdio::null()).creation_flags(CREATE_NO_WINDOW);+ let mut second = cmd.spawn().unwrap();+ let second_tree = ProcessTree::capture(second.id());+ assert!(job.assign_pid(second.id()), "the follow-up run joins the job");+ assert!(job.terminate());+ assert_gone(&second_tree);+ let _ = first.wait();+ let _ = second.wait();+ }++ #[test]+ fn a_dead_pid_makes_no_job() {+ // An id of a process this test cannot open (or that does not exist) gives no job,+ // which is the callers' cue for the `taskkill /T /F` fallback.+ assert!(Job::for_pid(u32::MAX).is_none());+ }+}diff --git a/crates/ide-dap/src/adapter.rs b/crates/ide-dap/src/adapter.rsindex 9c8913634..cc59f3a38 100644--- a/crates/ide-dap/src/adapter.rs+++ b/crates/ide-dap/src/adapter.rs@@ -525,9 +525,10 @@ async fn spawn_adapter(cmd.env("PATH", path);}ide_core::process::prepare(cmd.as_std_mut());- if spec.adapter == "rdbg" {- ide_core::process::own_group(cmd.as_std_mut());- }+ // Every adapter leads its own process group: the program an adapter launches itself+ // (java-debug's JVM) joins the group, so a forced stop reaches the whole tree with+ // one `kill(-pgid)`. On Windows the same coverage comes from the session's job object.+ ide_core::process::own_group(cmd.as_std_mut());cmd.args(args).envs(spec.env.iter().map(|(k, v)| (k, v))).current_dir(&spec.cwd)diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rsindex 687742642..23c8abcc0 100644--- a/crates/ide-dap/src/lib.rs+++ b/crates/ide-dap/src/lib.rs@@ -1160,7 +1160,7 @@ impl DebugManager {if own_terminate && !graceful {// Signal before anything else: waiting on a request the adapter may not answer// would delay the shutdown the console is supposed to show.- crate::session::signal_debuggee(s, false);+ crate::session::signal_debuggee(s, false).await;}if graceful {// java-debug sends `terminated` only after it has drained the program's consolediff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rsindex d3863a300..e8f2980d9 100644--- a/crates/ide-dap/src/session.rs+++ b/crates/ide-dap/src/session.rs@@ -45,6 +45,13 @@ pub(crate) struct Session {pub debuggees: Mutex<Vec<Child>>,/// The terminal a `runInTerminal` program runs in: typed input goes to it.pub program: Mutex<Option<ProgramTerminal>>,+ /// The job object over the adapter and everything it started: the program an adapter+ /// like java-debug launches is its child, so a forced stop (and the session's+ /// cleanup) ends the whole tree even when the adapter exited first and the reported+ /// pid no longer names it. `None` when the assignment failed; the kill then falls+ /// back to the captured process tree.+ #[cfg(windows)]+ pub job: Mutex<Option<ide_core::process::Job>>,/// Set once `configurationDone` was sent; breakpoint updates go out live after that.pub configured: AtomicBool,pub initialized: watch::Sender<bool>,@@ -91,6 +98,10 @@ impl Session {port: Option<u16>,child: Option<Child>,) -> Self {+ // Before `child` moves into the session: the adapter is the root of the job, so+ // everything it starts (java-debug's JVM) is in there by inheritance.+ #[cfg(windows)]+ let job = child.as_ref().and_then(tokio::process::Child::id).and_then(ide_core::process::Job::for_pid);Self {id,owner,@@ -105,6 +116,8 @@ impl Session {adapter_process: Mutex::new(child),debuggees: Mutex::new(Vec::new()),program: Mutex::new(None),+ #[cfg(windows)]+ job: Mutex::new(job),configured: AtomicBool::new(false),initialized: watch::channel(false).0,startup_cancel: ide_core::CancellationToken::new(),@@ -282,6 +295,24 @@ impl Session {/// Kills the adapter and every debuggee we started.pub fn kill_processes(&self) {self.kotlin_relay.lock().take();+ #[cfg(unix)]+ if self.request == "launch" {+ for group in launch_groups(self) {+ ide_core::process::kill_tree_of(group as u32);+ }+ }+ // The job first: it ends the adapter and everything it started (the program+ // java-debug launched is its child), members included that the stop's captured+ // tree never saw. An empty job is unaffected, and whatever survives this session+ // dies when the handle closes (`KILL_ON_JOB_CLOSE`).+ #[cfg(windows)]+ if let Some(job) = self.job.lock().as_ref() {+ job.terminate();+ }+ #[cfg(windows)]+ if let Some(tree) = self.stop_tree.lock().as_ref() {+ tree.terminate();+ }if let Some(mut c) = self.adapter_process.lock().take() {if self.adapter == "rdbg"&& let Some(pid) = c.id()@@ -295,6 +326,9 @@ impl Session {}if let Some(mut program) = self.program.lock().take() {let _ = program.child.kill();+ let _ = std::thread::Builder::new().name("openidea-debug-reap".into()).spawn(move || {+ let _ = program.child.wait();+ });}}}@@ -346,18 +380,36 @@ fn process_tree(pid: i32) -> Vec<i32> {/// Asks the program itself to exit (`force` = SIGKILL) without ending the adapter session:/// its output keeps flowing over DAP while it shuts down. The first call remembers the pid/// tree, because the reported pid may die before its program does.-pub(crate) fn signal_debuggee(s: &Arc<Session>, force: bool) {- let pid = s.debuggee_pid.load(Ordering::Acquire);- if pid <= 0 {+pub(crate) async fn signal_debuggee(s: &Arc<Session>, force: bool) {+ if s.request != "launch" {return;}+ #[cfg(not(windows))]+ let pid = s.debuggee_pid.load(Ordering::Acquire);#[cfg(unix)]{- let mut known = s.stop_pids.lock();- if known.is_empty() {- *known = process_tree(pid as i32);+ let needs_tree = pid > 0 && s.stop_pids.lock().is_empty();+ if needs_tree {+ let tree = tokio::task::spawn_blocking(move || process_tree(pid as i32)).await.unwrap_or_default();+ *s.stop_pids.lock() = tree;}+ let known = s.stop_pids.lock();let signal = if force { libc::SIGKILL } else { libc::SIGTERM };+ if force {+ // A forced stop kills the launch: every root the session spawned leads its own+ // process group (`own_group` at spawn), so one signal reaches the program and+ // everything it started, even processes born after the snapshot below was+ // taken — the adapter's program is in the adapter's group. The session's own+ // JVM roots (Kotlin) and `runInTerminal` programs lead groups of their own.+ // The roots are unreaped until the session drops them, so their ids (and the+ // groups named by them) cannot have been reused yet.+ for group in launch_groups(s) {+ // SAFETY: plain syscalls on the processes this session started.+ if unsafe { libc::kill(-group, libc::SIGKILL) } != 0 {+ unsafe { libc::kill(group, libc::SIGKILL) };+ }+ }+ }// Children first: the shell that started the program would otherwise reparent it.for p in known.iter().rev() {// SAFETY: plain syscall on the processes this session started.@@ -368,15 +420,53 @@ pub(crate) fn signal_debuggee(s: &Arc<Session>, force: bool) {}#[cfg(windows)]{- // Console programs have no external graceful signal; the adapter gets its chance first.- if force && let Some(tree) = s.stop_tree.lock().as_ref() {- tree.terminate();+ // Console programs have no external graceful signal; the adapter gets its chance+ // first. The job ends the program and everything it started, members included+ // that the captured tree never saw.+ if force {+ if let Some(job) = s.job.lock().as_ref() {+ job.terminate();+ }+ // A separately spawned program may have rejected assignment to the adapter's job.+ if let Some(tree) = s.stop_tree.lock().as_ref() {+ tree.terminate();+ }}}#[cfg(not(any(unix, windows)))]let _ = (pid, force);}+/// The process groups the session spawned roots for: the adapter's (the program it+/// launched is in it), the JVMs the session started itself, the `runInTerminal` program.+#[cfg(unix)]+fn launch_groups(s: &Session) -> Vec<libc::pid_t> {+ let mut groups = Vec::new();+ let mut push = |id: Option<u32>| {+ if let Ok(pid) = libc::pid_t::try_from(id.unwrap_or(0)) {+ groups.push(pid);+ }+ };+ push(s.adapter_process.lock().as_ref().and_then(tokio::process::Child::id));+ for child in s.debuggees.lock().iter() {+ push(child.id());+ }+ push(s.program.lock().as_ref().and_then(|p| p.child.process_id()));+ groups.retain(|g| *g > 0);+ groups+}++/// Whether the launch is still running: the stop's captured tree when there is one,+/// otherwise the session's job (the adapter and everything it started).+#[cfg(windows)]+fn launch_running(s: &Arc<Session>) -> bool {+ if let Some(tree) = s.stop_tree.lock().as_ref() {+ tree.is_running()+ } else {+ s.job.lock().as_ref().is_some_and(|job| job.is_running())+ }+}+/// Waits until the program a `launch` session started is gone; a second Stop kills it.pub(crate) async fn wait_for_debuggee(s: &Arc<Session>, terminate: bool) {if !terminate || s.request != "launch" {@@ -390,19 +480,19 @@ pub(crate) async fn wait_for_debuggee(s: &Arc<Session>, terminate: bool) {#[cfg(unix)]{use std::time::Instant;- let targets = {- let known = s.stop_pids.lock();- if known.is_empty() { process_tree(pid as i32) } else { known.clone() }- };+ let mut targets = s.stop_pids.lock().clone();+ if targets.is_empty() {+ targets = tokio::task::spawn_blocking(move || process_tree(pid as i32)).await.unwrap_or_default();+ }let alive = || targets.iter().any(|p| unsafe { libc::kill(*p, 0) } == 0);let deadline = Instant::now() + DEBUGGEE_EXIT_WAIT;while alive() {if s.stop_force.swap(false, Ordering::AcqRel) {- signal_debuggee(s, true);+ signal_debuggee(s, true).await;}if Instant::now() >= deadline {// The program ignored the terminate: do not leave it running.- signal_debuggee(s, true);+ signal_debuggee(s, true).await;break;}tokio::time::sleep(Duration::from_millis(50)).await;@@ -412,9 +502,12 @@ pub(crate) async fn wait_for_debuggee(s: &Arc<Session>, terminate: bool) {{remember_debuggee(s).await;let deadline = std::time::Instant::now() + DEBUGGEE_EXIT_WAIT;- while s.stop_tree.lock().as_ref().is_some_and(|tree| tree.is_running()) {+ // The captured tree is the oracle when it was captured; otherwise the job (every+ // process the launch started) is, so a failed capture can no longer end the wait+ // while the program still holds its port.+ while launch_running(s) {if s.stop_force.swap(false, Ordering::AcqRel) || std::time::Instant::now() >= deadline {- signal_debuggee(s, true);+ signal_debuggee(s, true).await;}tokio::time::sleep(Duration::from_millis(50)).await;}@@ -697,6 +790,14 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S}}let mut child = pair.slave.spawn_command(cmd).map_err(|e| format!("failed to start {program}: {e}"))?;+ // The program joins the session's job, so Stop reaches what it starts (its children),+ // though only the program itself is the session's child.+ #[cfg(windows)]+ if let Some(pid) = child.process_id()+ && let Some(job) = s.job.lock().as_ref()+ {+ job.assign_pid(pid);+ }drop(pair.slave);let reader = pair.master.try_clone_reader().map_err(|e| format!("terminal of {program}: {e}"))?;let writer = pair.master.take_writer().map_err(|e| format!("terminal of {program}: {e}"))?;@@ -864,7 +965,16 @@ pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) ->}}}+ // A root the session spawns itself: its own process group on Unix (`kill(-pgid)` in a+ // forced stop), the session's job on Windows, so a stop reaches what it forks.+ ide_core::process::own_group(cmd.as_std_mut());let mut child = cmd.spawn()?;+ #[cfg(windows)]+ if let Some(pid) = child.id()+ && let Some(job) = s.job.lock().as_ref()+ {+ job.assign_pid(pid);+ }if let Some(err) = child.stderr.take() {forward_output(s, err, "stderr");}diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rsindex 5463db03c..908f997b6 100644--- a/crates/ide-dap/src/tests.rs+++ b/crates/ide-dap/src/tests.rs@@ -1963,3 +1963,55 @@ async fn rdbg_drains_test_output_after_dap_closes_before_killing_the_process() {IdeEvent::Debug { event: DebugEvent::Output { output, .. }, .. } if output == "test summary\n")));}++#[cfg(unix)]+#[tokio::test]+async fn cleanup_ends_the_adapter_tree_without_a_process_event() {+ use tokio::io::AsyncBufReadExt;++ let h = harness(Script::default());+ let id = h.start(config()).await.unwrap();+ let session = h.manager.session(id).unwrap();+ let mut command = tokio::process::Command::new("python3");+ ide_core::process::own_group(command.as_std_mut());+ command+ .args([+ "-u",+ "-c",+ "import subprocess,sys,time; subprocess.Popen([sys.executable, '-u', '-c', \+ \"import socket,time; s=socket.socket(); s.bind(('127.0.0.1',0)); s.listen(); \+ print(s.getsockname()[1],flush=True); time.sleep(60)\"]); time.sleep(60)",+ ])+ .stdout(std::process::Stdio::piped());+ let mut child = command.spawn().unwrap();+ let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();+ let port: u16 = lines.next_line().await.unwrap().unwrap().parse().unwrap();+ assert!(std::net::TcpListener::bind(("127.0.0.1", port)).is_err(), "the descendant holds the port");+ let pid = child.id().unwrap();+ *session.adapter_process.lock() = Some(child);+ session.kill_processes();+ let deadline = Instant::now() + Duration::from_secs(3);+ while std::net::TcpListener::bind(("127.0.0.1", port)).is_err() {+ if Instant::now() >= deadline {+ ide_core::process::kill_tree_of(pid);+ panic!("adapter cleanup left its descendant holding the port");+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ h.manager.stop(id).await.unwrap();+}++#[cfg(unix)]+#[tokio::test]+async fn stop_detaches_from_an_attached_program() {+ let mut child = std::process::Command::new("sleep").arg("60").spawn().unwrap();+ let h = harness(Script { debuggee_pid: Some(child.id()), ..Default::default() });+ let id = h.start(LaunchConfig { request: "attach".into(), ..config() }).await.unwrap();+ h.manager.stop(id).await.unwrap();+ let alive = child.try_wait().unwrap().is_none();+ let _ = child.kill();+ let _ = child.wait();+ assert!(alive, "Stop killed the attached program");+ assert!(!h.commands().contains(&"terminate".to_owned()));+ assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);+}diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rsindex e48b3074e..65f35c79b 100644--- a/crates/ide-run/src/process.rs+++ b/crates/ide-run/src/process.rs@@ -54,6 +54,12 @@ struct Entry {stdin: Mutex<Option<ide_core::input::InputWriter>>,/// The PTY master of a terminal-emulated run (resize; dropped on exit).pty: Option<Mutex<Option<Box<dyn MasterPty + Send>>>>,+ /// The Windows job over the launch: everything it starts joins the job, so a Stop+ /// reaches the tree even when the launcher exited first (and took the tracked pid's+ /// meaning along). `None` when the assignment failed; the kill then falls back to+ /// `taskkill /T /F` from the pid.+ #[cfg(windows)]+ job: Option<ide_core::process::Job>,stop: Option<StopCommand>,output: OutputFn,exited: AtomicBool,@@ -420,6 +426,10 @@ impl ProcessManager {std::io::ErrorKind::NotFound => IdeError::unavailable(format!("command not found: {}", config.command)),_ => IdeError::from(e),})?;+ // The job follows the launch's tree kernel-side; Stop reaches what the launcher+ // started even after the launcher itself is gone.+ #[cfg(windows)]+ let job = ide_core::process::Job::for_child(&child);let id = RunId::next();let stdin = (|| -> std::io::Result<_> {@@ -452,6 +462,8 @@ impl ProcessManager {pid: Mutex::new(Some(child.id())),stdin: Mutex::new(stdin),pty: None,+ #[cfg(windows)]+ job,stop,output: on_output.clone(),exited: AtomicBool::new(false),@@ -596,6 +608,9 @@ impl ProcessManager {pid: Mutex::new(child.process_id()),stdin: Mutex::new(Some(writer)),pty: Some(Mutex::new(Some(pair.master))),+ // By pid, not by handle: the PTY's child exposes its id only.+ #[cfg(windows)]+ job: child.process_id().and_then(ide_core::process::Job::for_pid),stop,output: on_output.clone(),exited: AtomicBool::new(false),@@ -700,18 +715,17 @@ impl ProcessManager {if entry.exited.load(Ordering::Acquire) && !group_alive(pid, &entry) {return Ok(());}- if already_stopping {- // Second stop request: don't wait out the grace period.- kill_tree(pid, true);- return Ok(());- }- if entry.stop.is_none() {- kill_tree(pid, false);- }let entry = entry.clone();std::thread::Builder::new().name(format!("openidea-run-stop-{}", id.0)).spawn(move || {+ if already_stopping {+ kill_tree(&entry, pid, true);+ return;+ }+ if entry.stop.is_none() {+ kill_tree(&entry, pid, false);+ }let exits_within = |limit: Duration| {let deadline = Instant::now() + limit;while Instant::now() < deadline {@@ -727,7 +741,7 @@ impl ProcessManager {if exits_within(grace) {return;}- kill_tree(pid, false);+ kill_tree(&entry, pid, false);}// A first Stop only asks the process tree to exit, as IDEA does: it waits for// the shutdown to finish (a Spring Boot app can take seconds) and a second Stop@@ -759,7 +773,7 @@ impl ProcessManager {if !entry.exited.load(Ordering::Acquire)&& let Some(pid) = *entry.pid.lock(){- kill_tree(pid, true);+ kill_tree(entry, pid, true);}}}@@ -770,7 +784,7 @@ impl ProcessManager {if !entry.exited.load(Ordering::Acquire)&& let Some(pid) = *entry.pid.lock(){- kill_tree(pid, true);+ kill_tree(entry, pid, true);}}}@@ -820,6 +834,12 @@ fn run_followup(}(entry.output)(OutputChunk::System { text: format!("{}\n", inv.display) });let mut child = cmd.spawn()?;+ // The follow-up run continues the same launch: it joins the run's job, so a Stop+ // reaches its tree too.+ #[cfg(windows)]+ if let Some(job) = entry.job.as_ref() {+ job.assign_pid(child.id());+ }*pid = Some(child.id());*entry.stdin.lock() = (|| -> std::io::Result<_> {Ok(match child.stdin.take() {@@ -987,13 +1007,24 @@ fn group_alive(pid: u32, _entry: &Entry) -> bool {unsafe { libc::kill(-(pid as libc::pid_t), 0) == 0 }}-#[cfg(not(unix))]+#[cfg(windows)]+fn group_alive(_pid: u32, entry: &Entry) -> bool {+ // The job sees what an exited launcher left behind; without one (the assignment+ // failed), a run is over when the launcher itself is.+ match entry.job.as_ref() {+ Some(job) => job.is_running(),+ None => !entry.exited.load(Ordering::Acquire),+ }+}++#[cfg(not(any(unix, windows)))]fn group_alive(_pid: u32, entry: &Entry) -> bool {!entry.exited.load(Ordering::Acquire)}#[cfg(unix)]-fn kill_tree(pid: u32, force: bool) {+fn kill_tree(entry: &Entry, pid: u32, force: bool) {+ let _ = entry;let sig = if force { libc::SIGKILL } else { libc::SIGINT };let pid = pid as libc::pid_t;if pid <= 0 {@@ -1021,9 +1052,15 @@ fn add_raw_args(cmd: &mut Command, args: &[String]) {}#[cfg(windows)]-fn kill_tree(pid: u32, _force: bool) {+fn kill_tree(entry: &Entry, pid: u32, _force: bool) {use std::os::windows::process::CommandExt;- // Console children have no reliable graceful signal from outside their console.+ // The job ends the whole launch kernel-side, members included that the launcher+ // started after any snapshot would have been taken.+ if entry.job.as_ref().is_some_and(|job| job.terminate()) {+ return;+ }+ // Console children have no reliable graceful signal from outside their console, and+ // without a job the tree can only be found from the tracked root's pid.let _ = Command::new("taskkill").args(["/T", "/F", "/PID", &pid.to_string()]).creation_flags(ide_core::process::CREATE_NO_WINDOW)@@ -1184,15 +1221,27 @@ fn spawn_pump(if let Some(pty) = &entry.pty {pty.lock().take();}- // A stopped run is over when the whole process group is gone, not when the child we- // spawned exits: a shell or `mvn` can end while the application it started keeps its- // port, and reporting "finished" then would let Run start into an occupied port.- // A second Stop kills the group, which ends this wait.+ // A stopped run is over when the whole process group (Unix) or the whole job+ // (Windows) is gone, not when the child we spawned exits: a shell or `mvn` can+ // end while the application it started keeps its port, and reporting "finished"+ // then would let Run start into an occupied port. A second Stop kills the group+ // or the job, which ends this wait.#[cfg(unix)]- if entry.stopping.load(Ordering::Acquire)- && let Some(pid) = *entry.pid.lock(){- while group_alive(pid, &entry) {+ let pid = *entry.pid.lock();+ if entry.stopping.load(Ordering::Acquire)+ && let Some(pid) = pid+ {+ while group_alive(pid, &entry) {+ std::thread::sleep(Duration::from_millis(50));+ }+ }+ }+ // Without a job the exited flag is the only probe, and it always reads "alive"+ // here: this thread is the one that sets it.+ #[cfg(windows)]+ if entry.stopping.load(Ordering::Acquire) && entry.job.is_some() {+ while group_alive(0, &entry) {std::thread::sleep(Duration::from_millis(50));}}diff --git a/crates/ide-run/tests/stop_group.rs b/crates/ide-run/tests/stop_group.rsindex 0f9917992..ebf7c842f 100644--- a/crates/ide-run/tests/stop_group.rs+++ b/crates/ide-run/tests/stop_group.rs@@ -48,9 +48,18 @@ fn assert_still_running(events: &Receiver<IdeEvent>, timeout: Duration) {#[test]fn a_stopped_run_keeps_its_port_until_the_group_is_gone() {+ stopped_launcher_with_descendant(false);+}++#[test]+fn a_second_stop_reaches_descendants_after_the_launcher_exits() {+ stopped_launcher_with_descendant(true);+}++fn stopped_launcher_with_descendant(force: bool) {let tmp = tempfile::tempdir().unwrap();let (sink, events) = channel_sink();- let pm = ProcessManager::new();+ let pm = Arc::new(ProcessManager::new());// The `mvn`-starts-a-JVM shape: the direct child dies on SIGINT while the process it// started ignores it and keeps its socket open until the test releases it.let script = tmp.path().join("hold.py");@@ -97,7 +106,20 @@ fn a_stopped_run_keeps_its_port_until_the_group_is_gone() {wait_for("the direct child to exit", || unsafe { libc::kill(pid, 0) != 0 });let exit = events.recv_timeout(Duration::from_secs(1));let port_held = std::net::TcpStream::connect(("127.0.0.1", port)).is_ok();- std::fs::write(&release_file, "").unwrap();+ if force {+ let (tx, rx) = mpsc::channel();+ let pm = pm.clone();+ std::thread::spawn(move || {+ let _ = tx.send(pm.stop(info.id));+ });+ let result = rx.recv_timeout(Duration::from_secs(1));+ if result.is_err() {+ std::fs::write(&release_file, "").unwrap();+ }+ result.expect("second Stop blocked waiting for the run's pid lock").unwrap();+ } else {+ std::fs::write(&release_file, "").unwrap();+ }assert!(matches!(exit, Err(mpsc::RecvTimeoutError::Timeout)),"run exited while its descendant held the port: {exit:?}"diff --git a/crates/ide-run/tests/stop_tree.rs b/crates/ide-run/tests/stop_tree.rsnew file mode 100644index 000000000..9b7e72118--- /dev/null+++ b/crates/ide-run/tests/stop_tree.rs@@ -0,0 +1,192 @@+//! Stopping a run on Windows ends the whole launched tree: the kernel job over the+//! launch reaches what a launcher started even when the launcher exited first (where a+//! `taskkill /T /F` from the tracked pid no longer finds the orphan), and the run only+//! reports its exit once the port the tree held is free again.+#![cfg(windows)]++use ide_core::{IdeEvent, RunId, SharedSink};+use ide_run::{OutputChunk, ProcessManager, RunConfig, StartOptions};+use parking_lot::Mutex;+use std::collections::BTreeMap;+use std::net::TcpListener;+use std::sync::Arc;+use std::sync::mpsc::{self, Receiver};+use std::time::{Duration, Instant};++static CONSOLE: Mutex<Vec<String>> = Mutex::new(Vec::new());++fn channel_sink() -> (SharedSink, Receiver<IdeEvent>) {+ let (tx, events) = mpsc::channel();+ let tx = Mutex::new(tx);+ let sink: SharedSink = Arc::new(move |e: IdeEvent| {+ let _ = tx.lock().send(e);+ });+ (sink, events)+}++fn capture_output() -> Box<dyn Fn(OutputChunk) + Send + Sync> {+ Box::new(move |chunk: OutputChunk| {+ let text = match &chunk {+ OutputChunk::Stdout { text } | OutputChunk::Stderr { text } | OutputChunk::System { text } => text,+ };+ CONSOLE.lock().push(text.clone());+ })+}++fn console_log() -> String {+ CONSOLE.lock().join("")+}++fn wait_for(what: &str, mut ready: impl FnMut() -> bool) {+ let deadline = Instant::now() + Duration::from_secs(60);+ while !ready() {+ assert!(Instant::now() < deadline, "timed out waiting for {what}; console:\n{}", console_log());+ std::thread::sleep(Duration::from_millis(50));+ }+}++fn wait_exit(events: &Receiver<IdeEvent>, id: RunId, timeout: Duration) -> Option<i32> {+ let deadline = Instant::now() + timeout;+ loop {+ let left = deadline.saturating_duration_since(Instant::now());+ match events.recv_timeout(left).expect("RunExited event") {+ IdeEvent::RunExited { run, code } if run == id => return code,+ _ => {}+ }+ }+}++/// A program that binds a port and holds it, like a Spring Boot JVM: the `mvn`-starts-a-JVM+/// shape. PowerShell is the one interpreter every Windows runner has.+fn port_holder(dir: &std::path::Path) -> String {+ let script = dir.join("hold-port.ps1");+ std::fs::write(+ &script,+ "$l = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0)\n\+ $l.Start()\n\+ Set-Content -Path $args[0] -Value $l.LocalEndpoint.Port\n\+ Start-Sleep -Seconds 300\n",+ )+ .unwrap();+ let port_file = dir.join("port");+ // Unquoted exe: under `start /B` a quoted first token would be the window title, and+ // the path has no spaces anyway.+ format!(+ "%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -NoProfile -ExecutionPolicy \+ Bypass -File \"{}\" \"{}\"",+ script.display(),+ port_file.display()+ )+}++fn config(line: &str) -> RunConfig {+ RunConfig {+ id: "boot".into(),+ name: "boot".into(),+ kind: "shell".into(),+ // A shell line, as a run configuration holds one: it runs through `cmd /D /S /C`,+ // which parses the line itself (the CRT quoting of separate args would mangle it).+ command: line.to_owned(),+ args: Vec::new(),+ cwd: None,+ env: BTreeMap::new(),+ detected: false,+ is_test: false,+ debug_adapter: None,+ allow_parallel: false,+ extras: Default::default(),+ }+}++fn holder_port(dir: &std::path::Path) -> u16 {+ wait_for("the holder's port", || std::fs::metadata(dir.join("port")).is_ok());+ std::fs::read_to_string(dir.join("port")).unwrap().trim().parse().unwrap()+}++#[test]+fn a_stop_reaches_the_tree_a_dead_launcher_left_behind() {+ let tmp = tempfile::tempdir().unwrap();+ let (sink, events) = channel_sink();+ let pm = ProcessManager::new();+ let holder = port_holder(tmp.path());+ // `start /B` detaches the holder from cmd's lifetime: cmd exits at once, the holder+ // keeps its port, and the run reports its exit while the port is still taken.+ let line = format!("start /B {}", holder);+ let info = pm.start(tmp.path(), &config(&line), &StartOptions::default(), sink, capture_output()).expect("start");+ let port = holder_port(tmp.path());++ // The launcher exited on its own; the run is over, but the holder it started lives.+ let code = wait_exit(&events, info.id, Duration::from_secs(30));+ assert_eq!(code, Some(0), "cmd exited by itself; console:\n{}", console_log());++ // Stop must still reach what it started: this is the reported bug, a port the next+ // start cannot bind because the launcher's orphan holds it.+ pm.stop(info.id).unwrap();+ wait_for("the holder's port to be free", || TcpListener::bind(("127.0.0.1", port)).is_ok());+}++#[test]+fn a_stop_kills_a_launch_whose_launcher_is_still_up() {+ let tmp = tempfile::tempdir().unwrap();+ let (sink, events) = channel_sink();+ let pm = ProcessManager::new();+ let holder = port_holder(tmp.path());+ let info = pm.start(tmp.path(), &config(&holder), &StartOptions::default(), sink, capture_output()).expect("start");+ let port = holder_port(tmp.path());++ pm.stop(info.id).unwrap();+ // The run is only finished once the tree is gone, so the port is free by the time the+ // console reports the exit and the next start can bind it.+ let code = wait_exit(&events, info.id, Duration::from_secs(30));+ assert_eq!(code, Some(1), "the job's termination exit code; console:\n{}", console_log());+ wait_for("the holder's port to be free", || TcpListener::bind(("127.0.0.1", port)).is_ok());+}++/// The reported shape itself: `cmd` starting a JVM that holds its port (a Spring Boot run+/// or debug launch). Runs where a JDK is installed (CI's Windows runners have one).+#[test]+fn a_stop_kills_the_jvm_a_launcher_started() {+ let Some(javac) = which_javac() else {+ eprintln!("skipped: no javac on this machine");+ return;+ };+ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(+ tmp.path().join("HoldPort.java"),+ "import java.net.ServerSocket;\n\+ public class HoldPort {\n\+ public static void main(String[] args) throws Exception {\n\+ ServerSocket server = new ServerSocket(Integer.parseInt(args[0]), 1, java.net.InetAddress.getByName(\"127.0.0.1\"));\n\+ System.out.println(\"listening\");\n\+ System.out.flush();\n\+ Thread.sleep(Long.MAX_VALUE);\n\+ }\n\+ }\n",+ )+ .unwrap();+ let status = std::process::Command::new(javac)+ .args(["-d", &tmp.path().display().to_string(), &tmp.path().join("HoldPort.java").display().to_string()])+ .stdout(std::process::Stdio::null())+ .status()+ .expect("javac runs");+ assert!(status.success(), "the holder compiles; console:\n{}", console_log());++ // A free port chosen by this process, handed to the JVM.+ let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();+ let (sink, events) = channel_sink();+ let pm = ProcessManager::new();+ let line = format!("java -cp \"{}\" HoldPort {port}", tmp.path().display());+ let info = pm.start(tmp.path(), &config(&line), &StartOptions::default(), sink, capture_output()).expect("start");+ // The JVM is cmd's child and announces itself on the run's console.+ wait_for("the JVM to listen", || std::net::TcpStream::connect(("127.0.0.1", port)).is_ok());++ pm.stop(info.id).unwrap();+ wait_exit(&events, info.id, Duration::from_secs(30));+ wait_for("the JVM's port to be free", || TcpListener::bind(("127.0.0.1", port)).is_ok());+}++/// `javac` as the run would resolve it: on the process's PATH.+fn which_javac() -> Option<std::path::PathBuf> {+ let path = std::env::var_os("PATH")?;+ ide_run::which::find_executable("javac", &path)+}