running-process 4.5.5

Subprocess and PTY runtime for the running-process project
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! PTY backend abstraction (#150).
//!
//! `native_pty_process.rs` was riddled with `#[cfg(windows)]` /
//! `#[cfg(unix)]` branches around the underlying portable-pty calls.
//! After the #150 rewrite we have two distinct backends:
//!
//! * Windows - `conpty::ConPtyBackend` (raw ConPTY via windows-sys
//!   with `PSEUDOCONSOLE_PASSTHROUGH_MODE` enabled)
//! * Unix - `unix::PortablePtyBackend` (a thin wrapper around
//!   portable-pty's native_pty_system, unchanged behavior)
//!
//! The `Backend` type alias resolves to one or the other per-target,
//! and `native_pty_process.rs` makes a single `Backend::openpty(...)`
//! call instead of branching.

use std::ffi::OsString;
use std::io::{self, Read, Write};
use std::path::Path;

/// Caller-facing PTY dimensions. Pixel fields are ignored on Windows
/// (ConPTY only consumes rows/cols). Mirrors portable-pty's shape so
/// caller code passes them through unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PtySize {
    /// Terminal row count in character cells.
    pub rows: u16,
    /// Terminal column count in character cells.
    pub cols: u16,
    /// Terminal width in pixels when the backend supports it.
    pub pixel_width: u16,
    /// Terminal height in pixels when the backend supports it.
    pub pixel_height: u16,
}

/// Platform-neutral handle for the master side of a pseudo-terminal.
pub trait PtyMaster: Send + 'static {
    /// Clone a reader for PTY output.
    fn try_clone_reader(&mut self) -> io::Result<Box<dyn Read + Send>>;
    /// Take the writer used to send input to the PTY.
    fn take_writer(&mut self) -> io::Result<Box<dyn Write + Send>>;
    /// Resize the PTY to the requested dimensions.
    fn resize(&self, size: PtySize) -> io::Result<()>;
    /// Return the current PTY dimensions. On Windows the value is
    /// the last size passed to `resize` (or the initial openpty
    /// size); ConPTY exposes no live query API. Restored in 4.0.1
    /// for downstream parity with portable-pty's `MasterPty::get_size`.
    fn get_size(&self) -> io::Result<PtySize>;
    /// On Unix returns the foreground process group leader of the
    /// PTY (used by tools like `tcsetpgrp` checks). Always returns
    /// `None` on Windows where the concept doesn't exist.
    #[cfg(unix)]
    fn process_group_leader(&self) -> Option<i32>;
}

/// Platform-neutral handle for a child process running inside a PTY.
pub trait PtyChild: Send + 'static {
    /// Return the operating system process identifier.
    fn pid(&self) -> u32;
    /// Poll without blocking. `Ok(None)` means still running.
    /// `Ok(Some(code))` means exited with that exit code.
    /// `&mut self` because portable-pty's underlying Child::try_wait
    /// takes &mut, and we keep the surface uniform across backends.
    fn try_wait(&mut self) -> io::Result<Option<u32>>;
    /// Block until the child exits, then return the exit code.
    fn wait(&mut self) -> io::Result<u32>;
    /// Terminate the child process.
    fn kill(&mut self) -> io::Result<()>;
    /// Returns the Windows process HANDLE, if applicable. `None`
    /// means the backend can't expose one (which is fatal for Job
    /// Object containment — `assign_child_to_windows_kill_on_close_job`
    /// requires a real handle). Matches portable_pty's signature.
    #[cfg(windows)]
    fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle>;
}

/// Platform-neutral handle for the slave side of a pseudo-terminal.
pub trait PtySlave: Send + 'static {
    /// Child process type produced by this slave handle.
    type Child: PtyChild;
    /// Spawn a child process attached to this slave PTY.
    fn spawn(
        self,
        argv: &[OsString],
        cwd: Option<&Path>,
        env: Option<&[(OsString, OsString)]>,
    ) -> io::Result<Self::Child>;
}

/// Factory trait for opening platform-specific pseudo-terminal pairs.
pub trait PtyBackend {
    /// Master-side handle type returned by this backend.
    type Master: PtyMaster;
    /// Slave-side handle type returned by this backend.
    type Slave: PtySlave;
    /// Open a new PTY with the requested dimensions.
    fn openpty(size: PtySize) -> io::Result<(Self::Master, Self::Slave)>;
}

#[cfg(windows)]
mod conpty {
    use super::*;
    use crate::pty::conpty_passthrough;

    pub(crate) struct ConPtyBackend;

    impl PtyBackend for ConPtyBackend {
        type Master = conpty_passthrough::ConPtyMaster;
        type Slave = conpty_passthrough::ConPtySlave;

        fn openpty(size: PtySize) -> io::Result<(Self::Master, Self::Slave)> {
            let pair = conpty_passthrough::openpty(conpty_passthrough::PtySize {
                rows: size.rows,
                cols: size.cols,
                pixel_width: size.pixel_width,
                pixel_height: size.pixel_height,
            })?;
            Ok((pair.master, pair.slave))
        }
    }

    impl PtyMaster for conpty_passthrough::ConPtyMaster {
        fn try_clone_reader(&mut self) -> io::Result<Box<dyn Read + Send>> {
            conpty_passthrough::ConPtyMaster::try_clone_reader(self)
        }
        fn take_writer(&mut self) -> io::Result<Box<dyn Write + Send>> {
            conpty_passthrough::ConPtyMaster::take_writer(self)
        }
        fn resize(&self, size: PtySize) -> io::Result<()> {
            conpty_passthrough::ConPtyMaster::resize(
                self,
                conpty_passthrough::PtySize {
                    rows: size.rows,
                    cols: size.cols,
                    pixel_width: size.pixel_width,
                    pixel_height: size.pixel_height,
                },
            )
        }
        fn get_size(&self) -> io::Result<PtySize> {
            let s = conpty_passthrough::ConPtyMaster::get_size(self);
            Ok(PtySize {
                rows: s.rows,
                cols: s.cols,
                pixel_width: s.pixel_width,
                pixel_height: s.pixel_height,
            })
        }
    }

    impl PtySlave for conpty_passthrough::ConPtySlave {
        type Child = conpty_passthrough::child::ConPtyChild;
        fn spawn(
            self,
            argv: &[OsString],
            cwd: Option<&Path>,
            env: Option<&[(OsString, OsString)]>,
        ) -> io::Result<Self::Child> {
            conpty_passthrough::ConPtySlave::spawn(self, argv, cwd, env)
        }
    }

    impl PtyChild for conpty_passthrough::child::ConPtyChild {
        fn pid(&self) -> u32 {
            conpty_passthrough::child::ConPtyChild::pid(self)
        }
        fn try_wait(&mut self) -> io::Result<Option<u32>> {
            conpty_passthrough::child::ConPtyChild::try_wait(self)
        }
        fn wait(&mut self) -> io::Result<u32> {
            conpty_passthrough::child::ConPtyChild::wait(self)
        }
        fn kill(&mut self) -> io::Result<()> {
            conpty_passthrough::child::ConPtyChild::kill(self)
        }
        fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
            Some(conpty_passthrough::child::ConPtyChild::as_raw_handle(self))
        }
    }
}

#[cfg(unix)]
mod unix {
    use super::*;
    use portable_pty::{
        native_pty_system, Child as PortableChild, CommandBuilder, MasterPty,
        PtySize as PortPtySize, SlavePty,
    };

    pub(crate) struct PortablePtyBackend;

    pub(crate) struct PortablePtyMaster(Box<dyn MasterPty + Send>);
    pub(crate) struct PortablePtySlave(Box<dyn SlavePty + Send>);
    pub(crate) struct PortablePtyChild(Box<dyn PortableChild + Send + Sync>);

    impl PtyBackend for PortablePtyBackend {
        type Master = PortablePtyMaster;
        type Slave = PortablePtySlave;

        fn openpty(size: PtySize) -> io::Result<(Self::Master, Self::Slave)> {
            let sys = native_pty_system();
            let pair = sys
                .openpty(PortPtySize {
                    rows: size.rows,
                    cols: size.cols,
                    pixel_width: size.pixel_width,
                    pixel_height: size.pixel_height,
                })
                .map_err(io::Error::other)?;
            Ok((PortablePtyMaster(pair.master), PortablePtySlave(pair.slave)))
        }
    }

    impl PtyMaster for PortablePtyMaster {
        fn try_clone_reader(&mut self) -> io::Result<Box<dyn Read + Send>> {
            self.0.try_clone_reader().map_err(io::Error::other)
        }
        fn take_writer(&mut self) -> io::Result<Box<dyn Write + Send>> {
            self.0.take_writer().map_err(io::Error::other)
        }
        fn resize(&self, size: PtySize) -> io::Result<()> {
            self.0
                .resize(PortPtySize {
                    rows: size.rows,
                    cols: size.cols,
                    pixel_width: size.pixel_width,
                    pixel_height: size.pixel_height,
                })
                .map_err(io::Error::other)
        }
        fn get_size(&self) -> io::Result<PtySize> {
            let s = self.0.get_size().map_err(io::Error::other)?;
            Ok(PtySize {
                rows: s.rows,
                cols: s.cols,
                pixel_width: s.pixel_width,
                pixel_height: s.pixel_height,
            })
        }
        fn process_group_leader(&self) -> Option<i32> {
            self.0.process_group_leader()
        }
    }

    impl PtySlave for PortablePtySlave {
        type Child = PortablePtyChild;
        fn spawn(
            self,
            argv: &[OsString],
            cwd: Option<&Path>,
            env: Option<&[(OsString, OsString)]>,
        ) -> io::Result<Self::Child> {
            if argv.is_empty() {
                return Err(io::Error::other(
                    "portable-pty spawn requires non-empty argv",
                ));
            }
            let mut cmd = CommandBuilder::new(&argv[0]);
            for arg in &argv[1..] {
                cmd.arg(arg);
            }
            if let Some(cwd) = cwd {
                cmd.cwd(cwd);
            }
            if let Some(env) = env {
                cmd.env_clear();
                for (k, v) in env {
                    cmd.env(k, v);
                }
            }
            let child = self.0.spawn_command(cmd).map_err(io::Error::other)?;
            Ok(PortablePtyChild(child))
        }
    }

    impl PtyChild for PortablePtyChild {
        fn pid(&self) -> u32 {
            self.0.process_id().unwrap_or(0)
        }
        fn try_wait(&mut self) -> io::Result<Option<u32>> {
            match self.0.try_wait()? {
                Some(status) => Ok(Some(portable_pty_exit_code(status))),
                None => Ok(None),
            }
        }
        fn wait(&mut self) -> io::Result<u32> {
            let status = self.0.wait()?;
            Ok(portable_pty_exit_code(status))
        }
        fn kill(&mut self) -> io::Result<()> {
            self.0.kill()
        }
    }

    /// Convert portable-pty's ExitStatus to a u32 exit code.
    /// Signal exits map to `128 + signal_index` per the standard
    /// shell convention.
    fn portable_pty_exit_code(status: portable_pty::ExitStatus) -> u32 {
        // ExitStatus is opaque; format and parse the debug form which
        // is "exited(code)" or "signal(name)". Cleaner would be to
        // pattern-match on its accessor — but portable-pty's
        // ExitStatus only exposes `exit_code() -> u32` directly.
        status.exit_code()
    }
}

// #150 W8: route Windows through ConPtyBackend (our new
// PSEUDOCONSOLE_PASSTHROUGH_MODE implementation).
#[cfg(windows)]
pub(crate) type Backend = conpty::ConPtyBackend;
#[cfg(unix)]
pub(crate) type Backend = unix::PortablePtyBackend;

// On Windows we still want the portable-pty wrapper available as
// the temporary backend. Mirror the Unix module under a different
// name so the cfg-pickup above works.
#[cfg(windows)]
#[allow(dead_code)]
mod unix_compat {
    use super::*;
    use portable_pty::{
        native_pty_system, Child as PortableChild, CommandBuilder, MasterPty,
        PtySize as PortPtySize, SlavePty,
    };

    pub(crate) struct PortablePtyBackend;
    pub(crate) struct PortablePtyMaster(Box<dyn MasterPty + Send>);
    pub(crate) struct PortablePtySlave(Box<dyn SlavePty + Send>);
    pub(crate) struct PortablePtyChild(Box<dyn PortableChild + Send + Sync>);

    impl PtyBackend for PortablePtyBackend {
        type Master = PortablePtyMaster;
        type Slave = PortablePtySlave;
        fn openpty(size: PtySize) -> io::Result<(Self::Master, Self::Slave)> {
            let sys = native_pty_system();
            let pair = sys
                .openpty(PortPtySize {
                    rows: size.rows,
                    cols: size.cols,
                    pixel_width: size.pixel_width,
                    pixel_height: size.pixel_height,
                })
                .map_err(io::Error::other)?;
            Ok((PortablePtyMaster(pair.master), PortablePtySlave(pair.slave)))
        }
    }

    impl PtyMaster for PortablePtyMaster {
        fn try_clone_reader(&mut self) -> io::Result<Box<dyn Read + Send>> {
            self.0.try_clone_reader().map_err(io::Error::other)
        }
        fn take_writer(&mut self) -> io::Result<Box<dyn Write + Send>> {
            self.0.take_writer().map_err(io::Error::other)
        }
        fn resize(&self, size: PtySize) -> io::Result<()> {
            self.0
                .resize(PortPtySize {
                    rows: size.rows,
                    cols: size.cols,
                    pixel_width: size.pixel_width,
                    pixel_height: size.pixel_height,
                })
                .map_err(io::Error::other)
        }
        fn get_size(&self) -> io::Result<PtySize> {
            let s = self.0.get_size().map_err(io::Error::other)?;
            Ok(PtySize {
                rows: s.rows,
                cols: s.cols,
                pixel_width: s.pixel_width,
                pixel_height: s.pixel_height,
            })
        }
    }

    impl PtySlave for PortablePtySlave {
        type Child = PortablePtyChild;
        fn spawn(
            self,
            argv: &[OsString],
            cwd: Option<&Path>,
            env: Option<&[(OsString, OsString)]>,
        ) -> io::Result<Self::Child> {
            if argv.is_empty() {
                return Err(io::Error::other(
                    "portable-pty spawn requires non-empty argv",
                ));
            }
            let mut cmd = CommandBuilder::new(&argv[0]);
            for arg in &argv[1..] {
                cmd.arg(arg);
            }
            if let Some(cwd) = cwd {
                cmd.cwd(cwd);
            }
            if let Some(env) = env {
                cmd.env_clear();
                for (k, v) in env {
                    cmd.env(k, v);
                }
            }
            let child = self.0.spawn_command(cmd).map_err(io::Error::other)?;
            Ok(PortablePtyChild(child))
        }
    }

    impl PtyChild for PortablePtyChild {
        fn pid(&self) -> u32 {
            self.0.process_id().unwrap_or(0)
        }
        fn try_wait(&mut self) -> io::Result<Option<u32>> {
            match self.0.try_wait()? {
                Some(status) => Ok(Some(status.exit_code())),
                None => Ok(None),
            }
        }
        fn wait(&mut self) -> io::Result<u32> {
            let status = self.0.wait()?;
            Ok(status.exit_code())
        }
        fn kill(&mut self) -> io::Result<()> {
            self.0.kill()
        }
        fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
            self.0.as_raw_handle()
        }
    }
}