PM: merge F3 hardening: suspended Phpactor start, ConPTY in a job, completion cancel, syntax proptest
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-27 17:30:10 +01:00
commit d2c853c42f
17 changed files with 468 additions and 36 deletions

View file

@ -19,6 +19,14 @@
//! runs these commands through the `engine_execute_waiting` IPC, on a
//! worker thread, so the window never waits either.
//!
//! **Superseded completions:** CodeMirror asks again as the user types and
//! drops the older answer. Each new `lsp.completion` therefore cancels the
//! previous one still pending on the same server (`$/cancelRequest`, via
//! [`Server::cancel`]), so Phpactor stops computing a list nobody reads.
//! The cancelled command resolves with the empty result, not an error.
//! Hover and signature help are not cancelled: they are asked once per
//! pause, not per keystroke.
//!
//! Without a session (no project, toolchain not ready, server failed) the
//! commands fail with `failed`; a server that does not offer the feature,
//! and a buffer that is not PHP, give the empty result. Server answers are
@ -26,11 +34,12 @@
//! empty result.
use std::path::Path;
use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use lutra_lsp::types::position_to_json;
use lutra_lsp::uri::path_to_uri;
use lutra_lsp::{LspError, Range, Server};
use lutra_lsp::{LspError, Range, RequestId, Server};
use lutra_text::{ColumnUnit, Position};
use serde::Deserialize;
use serde_json::{Map, Value, json};
@ -65,6 +74,13 @@ pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
/// for the queue in front of it ([`Pending::wait`] adds one more second).
const WAIT_TIMEOUT: Duration = Duration::from_secs(11);
/// The latest `textDocument/completion` request: the address of the
/// [`Server`] it went to and its id. One slot for the process is enough:
/// there is one PHP session per engine, and a slot taken over by another
/// engine's server only means one older request runs to its end. The
/// address keeps a request from being cancelled on another server.
static LATEST_COMPLETION: Mutex<Option<(usize, RequestId)>> = Mutex::new(None);
/// Registers the commands of this module.
///
/// # Errors
@ -146,6 +162,7 @@ impl Command for Completion {
None => json!({"triggerKind": 1}),
}),
convert: completion_result,
supersede: true,
},
)
}
@ -183,6 +200,7 @@ impl Command for Hover {
empty: json!({ "contents": "" }),
context: None,
convert: hover_result,
supersede: false,
},
)
}
@ -220,6 +238,7 @@ impl Command for SignatureHelp {
empty: json!({ "signatures": [], "activeSignature": 0, "activeParameter": 0 }),
context: None,
convert: signature_result,
supersede: false,
},
)
}
@ -243,6 +262,9 @@ struct Ask {
context: Option<Value>,
/// Converts the server's answer into the command's result.
convert: fn(&Value) -> Value,
/// Whether this request cancels the previous one of its kind still
/// pending (completion; see the module docs).
supersede: bool,
}
/// Validates the request, queues it on the session (see the module docs)
@ -262,6 +284,7 @@ fn ask(state: &mut State, ask: Ask) -> Result<Outcome, EngineError> {
empty,
context,
convert,
supersede,
} = ask;
let open = state
.buffers
@ -300,17 +323,28 @@ fn ask(state: &mut State, ask: Ask) -> Result<Outcome, EngineError> {
let _ = sender.send(Ok(empty));
return;
}
let empty = empty.clone();
if supersede {
cancel_latest(server);
}
let reply = sender.clone();
let sent = server.request_with(
method,
request,
REQUEST_TIMEOUT,
Box::new(move |result: Result<Value, LspError>| {
let _ = reply.send(result.map(|value| convert(&value)));
let _ = reply.send(match result {
Err(LspError::Cancelled) => Ok(empty),
other => other.map(|value| convert(&value)),
});
}),
);
if let Err(e) = sent {
let _ = sender.send(Err(e));
match sent {
Ok(request) if supersede => remember_latest(server, request),
Ok(_) => {}
Err(e) => {
let _ = sender.send(Err(e));
}
}
});
if !queued {
@ -325,6 +359,33 @@ fn ask(state: &mut State, ask: Ask) -> Result<Outcome, EngineError> {
)))
}
/// The address that identifies `server` in [`LATEST_COMPLETION`].
fn server_key(server: &Server) -> usize {
std::ptr::from_ref(server).addr()
}
/// Cancels the latest completion request if it went to `server` and is
/// still pending; its command then resolves with the empty result. A
/// poisoned slot is used as it is: it only holds plain data.
fn cancel_latest(server: &Server) {
let latest = LATEST_COMPLETION
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
if let Some((key, id)) = latest
&& key == server_key(server)
{
server.cancel(id);
}
}
/// Records `id` as the latest completion request, sent to `server`.
fn remember_latest(server: &Server, id: RequestId) {
*LATEST_COMPLETION
.lock()
.unwrap_or_else(PoisonError::into_inner) = Some((server_key(server), id));
}
/// The command's value from the converted answer.
///
/// # Errors

View file

@ -147,6 +147,39 @@ fn completion_sees_the_edit_before_it_and_is_capped() {
assert_eq!(items[0]["label"], "item000");
}
#[test]
fn a_new_completion_cancels_the_one_it_supersedes() {
let (_dir, mut engine) = project(&[("a.php", "<?php\nSLOW")], true);
let id = open(&mut engine, "a.php");
let mut slow = engine
.execute(
"lsp.completion",
json!({"id": id, "position": {"line": 1, "column": 4}}),
)
.unwrap();
let slow = slow.pending.take().unwrap();
engine
.execute(
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 6, "to": 10, "insert": ""}]}),
)
.unwrap();
let fresh = ask(
&mut engine,
"lsp.completion",
json!({"id": id, "position": {"line": 1, "column": 0}}),
)
.unwrap();
assert_eq!(fresh["items"].as_array().unwrap().len(), 4);
let started = std::time::Instant::now();
let superseded = engine.resolve(slow.wait()).unwrap().value;
assert!(
started.elapsed() < std::time::Duration::from_secs(5),
"the superseded request was not cancelled"
);
assert_eq!(superseded, json!({"items": [], "incomplete": false}));
}
#[test]
fn hover_and_signature_help() {
let (_dir, mut engine) = project(&[("a.php", "<?php\r\npair(1, 2);\r\n")], true);

View file

@ -16,7 +16,9 @@
//! document version; `didClose` publishes no diagnostics; `didSave` sends
//! `fake/saved` with the text it received.
//! - Requests: `textDocument/hover` answers `hover L:C`,
//! `textDocument/completion` a scripted list (see [`completion`]),
//! `textDocument/completion` a scripted list (see [`completion`]), or,
//! when the document contains `SLOW`, nothing until it is cancelled (like
//! `fake/sleep`),
//! `textDocument/signatureHelp` one signature whose active parameter is
//! the column modulo 2,
//! `textDocument/definition` the same position, `fake/echo` its params,
@ -260,6 +262,10 @@ impl Fake {
.get(uri)
.map(Buffer::text)
.unwrap_or_default();
if text.contains("SLOW") {
self.sleeping.push(id);
return;
}
respond(
id,
Ok(completion(

View file

@ -493,7 +493,7 @@ impl Shared {
use std::os::windows::process::CommandExt;
command.creation_flags(CREATE_NO_WINDOW);
}
lutra_proc::spawn(command).map_err(|error| LspError::Spawn {
lutra_proc::spawn_suspended(command).map_err(|error| LspError::Spawn {
command: self.launch.command.to_string_lossy().into_owned(),
detail: error.to_string(),
})

View file

@ -21,6 +21,7 @@ doc = false
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_JobObjects",
"Win32_System_Threading",
] }

View file

@ -13,10 +13,13 @@
//! process prints `ready` and sleeps. A test reading that output sees
//! end of file only once the grandchild is gone too, which is how it
//! checks that no process was left behind.
//! - `tree-on-input`: reads one line from standard input first, then acts
//! as `tree-plain`. A test adopts the helper in between, so the
//! grandchild starts only after the helper is in its job.
//!
//! Any other argument exits with code 2.
use std::io::Write;
use std::io::{BufRead, Write};
use std::process::{Command, ExitCode, Stdio};
use std::thread;
use std::time::Duration;
@ -29,6 +32,13 @@ fn main() -> ExitCode {
let role = std::env::args().nth(1).unwrap_or_default();
match role.as_str() {
"tree-plain" | "tree-proc" => tree(role == "tree-proc"),
"tree-on-input" => {
let mut line = String::new();
if std::io::stdin().lock().read_line(&mut line).is_err() {
return ExitCode::from(3);
}
tree(false)
}
_ => ExitCode::from(2),
}
}

View file

@ -25,10 +25,17 @@
//! by an explicit [`Child::kill`] or drop, which then signal the direct
//! child only.
//!
//! A child starts running before it is put into its job (Windows) or before
//! its watchdog exists (Unix), so a grandchild it starts in that window
//! (microseconds) can escape; language servers and git start their own
//! children much later.
//! A child started by [`spawn`] runs before it is put into its job (Windows)
//! or before its watchdog exists (Unix), so a grandchild it starts in that
//! window (microseconds) can escape. Short-lived tools (git, `php -l`, the
//! PHP probe) accept that: they start their own children (git hooks) much
//! later, when they are in the job already. [`spawn_suspended`] closes the
//! window on Windows for long-lived children (Phpactor) at the cost of a
//! system-wide thread snapshot (about 60 ms per start).
//!
//! [`adopt`] (Windows) puts a process started by someone else, the
//! integrated terminal's ConPTY shell, into a kill-on-close job and returns
//! a [`Guard`] that holds it.
use std::io;
use std::ops::{Deref, DerefMut};
@ -90,10 +97,46 @@ pub struct Child {
/// starting the watchdog). When the group cannot be set up, the child that
/// was already started is killed and reaped before the error is returned,
/// so it never runs unguarded.
pub fn spawn(mut command: Command) -> io::Result<Child> {
Group::prepare(&mut command);
pub fn spawn(command: Command) -> io::Result<Child> {
spawn_with(command, Group::prepare, Group::attach)
}
/// Like [`spawn`], but on Windows the child is created suspended and resumed
/// only once it is in its job, so not even its first instruction runs
/// outside it. Meant for long-lived children: finding the child's primary
/// thread to resume it takes a snapshot of every thread on the machine
/// (about 60 ms). On other platforms it is [`spawn`].
///
/// On Windows the creation flags of `command` are replaced by
/// `CREATE_SUSPENDED | CREATE_NO_WINDOW`.
///
/// # Errors
/// The errors of [`spawn`], and on Windows the error of resuming the child;
/// the child is killed and reaped before an error is returned.
pub fn spawn_suspended(command: Command) -> io::Result<Child> {
#[cfg(windows)]
{
spawn_with(command, Group::prepare_suspended, Group::attach_suspended)
}
#[cfg(not(windows))]
{
spawn(command)
}
}
/// Starts `command` after `prepare` and puts it into the group `attach`
/// creates; kills and reaps the child when `attach` fails.
///
/// # Errors
/// The error of [`Command::spawn`] or of `attach`.
fn spawn_with(
mut command: Command,
prepare: fn(&mut Command),
attach: fn(&std::process::Child) -> io::Result<Group>,
) -> io::Result<Child> {
prepare(&mut command);
let mut inner = command.spawn()?;
match Group::attach(&inner) {
match attach(&inner) {
Ok(group) => Ok(Child { inner, group }),
Err(error) => {
let _ = inner.kill();
@ -103,6 +146,53 @@ pub fn spawn(mut command: Command) -> io::Result<Child> {
}
}
/// A kill-on-close job for a process Lutra did not start through [`spawn`]
/// (Windows only, see [`adopt`]). Dropping it kills the process and
/// everything it started.
#[cfg(windows)]
pub struct Guard {
/// The job object.
group: Group,
}
/// Puts the process behind `process` into a new kill-on-close job, so it
/// and everything it starts from now on die with Lutra or with the returned
/// [`Guard`]. Processes it started before are not adopted.
///
/// `process` needs `PROCESS_SET_QUOTA | PROCESS_TERMINATE` access (a handle
/// from `CreateProcess` has all access) and stays owned by the caller.
///
/// # Errors
/// The OS error of creating the job or assigning the process to it.
#[cfg(windows)]
pub fn adopt(process: std::os::windows::io::RawHandle) -> io::Result<Guard> {
Group::adopt(process).map(|group| Guard { group })
}
#[cfg(windows)]
impl Guard {
/// Terminates every process in the job.
pub fn kill(&mut self) {
self.group.kill();
}
}
#[cfg(windows)]
impl std::fmt::Debug for Guard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Guard").finish_non_exhaustive()
}
}
#[cfg(windows)]
impl Drop for Guard {
/// Kills the job's processes; closing the job handle right after would
/// do the same.
fn drop(&mut self) {
self.group.kill();
}
}
impl Child {
/// Kills the child and every process in its group, without waiting for
/// the child; call [`std::process::Child::wait`] to reap it.

View file

@ -1,23 +1,46 @@
//! Windows: one job object per child with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`
//! (<https://learn.microsoft.com/windows/win32/procthread/job-objects>).
//!
//! This is the one module in Lutra that allows `unsafe`: the job object API
//! is only reachable through FFI. Every call gets valid arguments by
//! construction: handles come from `CreateJobObjectW` (owned by an
//! [`OwnedHandle`] right away) or from a live [`std::process::Child`], and
//! the limit structure is a plain C struct that is valid when zeroed.
//! A child started with [`Group::prepare`] runs before it joins its job (a
//! window of microseconds). [`Group::prepare_suspended`] closes that window:
//! the child is created suspended (`CREATE_SUSPENDED`), put into its job and
//! only then resumed. The standard library keeps the primary thread's handle
//! to itself, so the thread is found through a Tool Help snapshot of the
//! system's threads (`CreateToolhelp32Snapshot`, `Thread32First` /
//! `Thread32Next`) and resumed with `OpenThread` + `ResumeThread`. The
//! snapshot covers every thread on the machine and costs about 60 ms
//! (measured 2026-10-27: 43 → 107 ms per `cmd /c exit`), which is why only
//! long-lived children pay for it.
//!
//! [`Group::adopt`] puts a process someone else started (the terminal's
//! ConPTY shell) into a new job by its handle.
//!
//! This is the one module in Lutra that allows `unsafe`: the job object,
//! Tool Help and thread APIs are only reachable through FFI. Every call gets
//! valid arguments by construction: handles come from `CreateJobObjectW`,
//! `CreateToolhelp32Snapshot` or `OpenThread` (owned by an [`OwnedHandle`]
//! right away) or from a live [`std::process::Child`], and the limit and
//! thread entry structures are plain C structs that are valid when zeroed.
#![allow(unsafe_code)]
use std::io;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
use std::os::windows::process::CommandExt;
use std::process::Command;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
SetInformationJobObject, TerminateJobObject,
};
use windows_sys::Win32::System::Threading::{
CREATE_NO_WINDOW, CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME,
};
/// The exit code a process killed with its job reports.
const KILLED_EXIT_CODE: u32 = 1;
@ -40,6 +63,40 @@ impl Group {
/// The OS error of `CreateJobObjectW`, `SetInformationJobObject` or
/// `AssignProcessToJobObject`.
pub(crate) fn attach(child: &std::process::Child) -> io::Result<Self> {
Self::adopt(child.as_raw_handle())
}
/// Makes the process start suspended and without a console window
/// (`CREATE_SUSPENDED | CREATE_NO_WINDOW`). These replace any creation
/// flags set on `command` before: the standard library cannot read them
/// back, and every tool Lutra runs is a console program whose window
/// must stay hidden.
pub(crate) fn prepare_suspended(command: &mut Command) {
command.creation_flags(CREATE_SUSPENDED | CREATE_NO_WINDOW);
}
/// Creates a kill-on-close job, puts the suspended `child` into it and
/// resumes it.
///
/// # Errors
/// The errors of [`Group::attach`] and of resuming the child (see
/// [`resume`]). The job is closed on error, which kills the child once
/// it is in the job.
pub(crate) fn attach_suspended(child: &std::process::Child) -> io::Result<Self> {
let group = Self::attach(child)?;
resume(child.id())?;
Ok(group)
}
/// Creates a kill-on-close job and puts the process behind `process`
/// into it. The handle needs `PROCESS_SET_QUOTA | PROCESS_TERMINATE`
/// access (a handle from `CreateProcess` has all access) and stays owned
/// by the caller.
///
/// # Errors
/// The OS error of `CreateJobObjectW`, `SetInformationJobObject` or
/// `AssignProcessToJobObject`.
pub(crate) fn adopt(process: RawHandle) -> io::Result<Self> {
let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
if raw.is_null() {
return Err(io::Error::last_os_error());
@ -60,8 +117,7 @@ impl Group {
if set == 0 {
return Err(io::Error::last_os_error());
}
let assigned =
unsafe { AssignProcessToJobObject(job.as_raw_handle(), child.as_raw_handle()) };
let assigned = unsafe { AssignProcessToJobObject(job.as_raw_handle(), process) };
if assigned == 0 {
return Err(io::Error::last_os_error());
}
@ -75,3 +131,52 @@ impl Group {
let _ = unsafe { TerminateJobObject(self.job.as_raw_handle(), KILLED_EXIT_CODE) };
}
}
/// Resumes every thread of the suspended process `pid`. A process created
/// with `CREATE_SUSPENDED` has exactly one thread, its primary thread, with
/// a suspend count of one.
///
/// # Errors
/// The OS error of `CreateToolhelp32Snapshot`, `OpenThread` or
/// `ResumeThread`, or `NotFound` when the snapshot holds no thread of `pid`.
fn resume(pid: u32) -> io::Result<()> {
let raw = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
if raw == INVALID_HANDLE_VALUE || raw.is_null() {
return Err(io::Error::last_os_error());
}
let snapshot = unsafe { OwnedHandle::from_raw_handle(raw) };
let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
entry.dwSize = u32::try_from(std::mem::size_of::<THREADENTRY32>()).map_err(io::Error::other)?;
let mut resumed = 0usize;
let mut more = unsafe { Thread32First(snapshot.as_raw_handle(), &raw mut entry) } != 0;
while more {
if entry.th32OwnerProcessID == pid {
resume_thread(entry.th32ThreadID)?;
resumed += 1;
}
more = unsafe { Thread32Next(snapshot.as_raw_handle(), &raw mut entry) } != 0;
}
if resumed == 0 {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("no thread of process {pid} to resume"),
));
}
Ok(())
}
/// Opens thread `tid` and decrements its suspend count once.
///
/// # Errors
/// The OS error of `OpenThread` or `ResumeThread`.
fn resume_thread(tid: u32) -> io::Result<()> {
let raw = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, tid) };
if raw.is_null() {
return Err(io::Error::last_os_error());
}
let thread = unsafe { OwnedHandle::from_raw_handle(raw) };
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
return Err(io::Error::last_os_error());
}
Ok(())
}

View file

@ -8,7 +8,7 @@
#![allow(clippy::unwrap_used)]
use std::io::{BufRead, BufReader, Read};
use std::io::{BufRead, BufReader, Read, Write};
use std::process::{ChildStdout, Command, Stdio};
use std::sync::mpsc;
use std::thread;
@ -101,3 +101,37 @@ fn a_missing_program_is_an_error() {
let error = lutra_proc::spawn(Command::new("lutra-proc-no-such-program")).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
}
#[test]
fn a_suspended_start_runs_and_takes_the_whole_tree() {
let mut child = lutra_proc::spawn_suspended(helper("unknown-role")).unwrap();
assert_eq!(child.wait().unwrap().code(), Some(2));
let mut parent = lutra_proc::spawn_suspended(helper("tree-plain")).unwrap();
let reader = ready(parent.stdout.take().unwrap());
drop(parent);
assert_gone(reader);
}
#[test]
fn hard_kill_works_when_a_suspended_start_parent_guards_its_child() {
let mut parent = lutra_proc::spawn_suspended(helper("tree-proc")).unwrap();
let reader = ready(parent.stdout.take().unwrap());
std::process::Child::kill(&mut parent).unwrap();
parent.wait().unwrap();
assert_gone(reader);
}
#[cfg(windows)]
#[test]
fn dropping_an_adopt_guard_takes_the_tree_started_after_it() {
use std::os::windows::io::AsRawHandle;
let mut command = helper("tree-on-input");
command.stdin(Stdio::piped());
let mut parent = command.spawn().unwrap();
let guard = lutra_proc::adopt(parent.as_raw_handle()).unwrap();
parent.stdin.take().unwrap().write_all(b"go\n").unwrap();
let reader = ready(parent.stdout.take().unwrap());
drop(guard);
assert_gone(reader);
parent.wait().unwrap();
}

View file

@ -6,3 +6,4 @@
# everyone who runs the test benefits from these saved cases.
cc c8b0a3ee622e3fac3ec69a94aebc22f23c9b3870156159ba6d9c2c5387d5eced # shrinks to fixture = Index(0), steps = [[(5318099958520493566, 19, 12), (10643632058251538265, 19, 18)], [(11062977690082286900, 37, 1)], [(3728561719478013405, 20, 10)]]
cc 3129b8640200f6a3b49b6579ba02346c578c68a5fb37bf929f93fb1aa0f4ef9b # shrinks to fixture = Index(14757395258967641293), steps = [[(14373769676898819633, 13, 21)], [(0, 0, 0)]]
cc 4efe36814ff9aa1f8c9bdc1fad55604ae0481a45732032f1c02d772977c1be4b # shrinks to fixture = Index(0), seeds = [(8685451444708560058, 1, 15)]

View file

@ -3,9 +3,17 @@
//!
//! tree-sitter recovers from syntax errors heuristically, and the recovery
//! may differ between an incremental and a fresh parse of the same broken
//! text. Tree equality is therefore asserted whenever the edited text
//! parses without errors, and an undo round trip must always end at the
//! fresh tree of the (error-free) original.
//! text. Equality is therefore asserted whenever the edited text parses
//! without errors, and an undo round trip must always end at the fresh
//! result of the (error-free) original.
//!
//! Equality means the same outline, the same folding ranges and the same
//! sequence of leaf node kinds, not the same S-expression: an incremental
//! reparse may reuse a node where a fresh parse picks another wrapper for
//! the same tokens (tree-sitter-php 0.25.1 keeps `(union_type
//! (primitive_type))` for `array &$cache` after an undo, a fresh parse gives
//! `(primitive_type)`). Every structural feature Lutra builds on the tree
//! reads outline, folding or leaves, so wrapper nodes may differ.
#![allow(
clippy::unwrap_used,
@ -87,6 +95,18 @@ fn edit_for(text: &str, (start, len, fragment): (usize, usize, usize)) -> Edit {
Edit::replace(start..end.max(start), FRAGMENTS[fragment])
}
/// The kinds of the named leaf nodes of `tree`, in document order, read
/// from its S-expression: a leaf is a node that closes right after its kind.
fn leaf_kinds(tree: &lutra_syntax::Tree) -> Vec<String> {
let sexp = tree.to_sexp().replace('(', " ( ").replace(')', " ) ");
let tokens: Vec<&str> = sexp.split_whitespace().collect();
tokens
.windows(3)
.filter(|window| window[0] == "(" && window[2] == ")")
.map(|window| window[1].to_owned())
.collect()
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
@ -134,7 +154,7 @@ proptest! {
let _ = outline(&tree);
let _ = folding(&tree);
if !fresh.has_errors() {
prop_assert_eq!(tree.to_sexp(), fresh.to_sexp());
prop_assert_eq!(leaf_kinds(&tree), leaf_kinds(&fresh));
prop_assert_eq!(outline(&tree), outline(&fresh));
prop_assert_eq!(folding(&tree), folding(&fresh));
}
@ -166,7 +186,7 @@ proptest! {
}
prop_assert_eq!(tree.text().text(), original);
if !expected.has_errors() {
prop_assert_eq!(tree.to_sexp(), expected.to_sexp());
prop_assert_eq!(leaf_kinds(&tree), leaf_kinds(&expected));
prop_assert_eq!(outline(&tree), outline(&expected));
prop_assert_eq!(folding(&tree), folding(&expected));
}

View file

@ -15,6 +15,9 @@ layer = 3
portable-pty = "0.9.0"
thiserror = "2.0.21"
[target.'cfg(windows)'.dependencies]
lutra-proc.workspace = true
[lints]
workspace = true

View file

@ -132,6 +132,10 @@ pub struct Session {
killer: Box<dyn ChildKiller + Send + Sync>,
/// Process id of the shell, if the platform reports one.
pid: Option<u32>,
/// The kill-on-close job the shell was adopted into (Windows), so the
/// shell and what it started die with the session or with Lutra.
#[cfg(windows)]
guard: lutra_proc::Guard,
}
impl std::fmt::Debug for Session {
@ -189,6 +193,15 @@ impl Session {
}
let mut child = pair.slave.spawn_command(cmd).map_err(spawn_error)?;
drop(pair.slave);
#[cfg(windows)]
let guard = match adopt(child.as_ref()) {
Ok(guard) => guard,
Err(e) => {
let _ = child.kill();
let _ = child.wait();
return Err(e);
}
};
let mut killer = child.clone_killer();
let pid = child.process_id();
let started = (|| {
@ -235,6 +248,8 @@ impl Session {
master,
killer,
pid,
#[cfg(windows)]
guard,
})
}
@ -344,7 +359,9 @@ impl Session {
}
/// Kills the shell unless it already exited, stops the reader and drops
/// buffered output. The pty closes once the waiter sees the exit.
/// buffered output. The pty closes once the waiter sees the exit. On
/// Windows it also kills every process left in the shell's job, such as
/// a background server the shell started, even after the shell exited.
/// Killing is best effort: an error means the process is already gone,
/// so it is ignored.
pub fn kill(&mut self) {
@ -360,9 +377,27 @@ impl Session {
if !exited {
let _ = self.killer.kill();
}
#[cfg(windows)]
self.guard.kill();
}
}
/// Adopts the ConPTY shell `child` into a kill-on-close job
/// ([`lutra_proc::adopt`]). The shell runs for a few microseconds before
/// that; a process it starts in that window is not in the job, and the
/// pseudo console still ends it when Lutra closes its pipes.
///
/// # Errors
/// [`TerminalError::Spawn`] when portable-pty gives no process handle or
/// the job cannot be set up.
#[cfg(windows)]
fn adopt(child: &dyn portable_pty::Child) -> Result<lutra_proc::Guard, TerminalError> {
let handle = child
.as_raw_handle()
.ok_or_else(|| TerminalError::Spawn("the shell has no process handle".into()))?;
lutra_proc::adopt(handle).map_err(spawn_error)
}
impl Drop for Session {
fn drop(&mut self) {
self.kill();