mxsh 0.1.0

Embeddable POSIX-style shell parser and runtime
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! System abstraction layer for mxsh.
//!
//! The runtime trait abstracts external child-process lifecycle.
//!
//! All I/O is fd-based. The shell state carries three [`FileDescriptor`] values
//! (stdin, stdout, stderr).
//! Builtins read/write through these fds.
//!
//! For testing, [`StringStdioIn`] and [`StringStdioOut`] create OS pipes backed by background
//! threads that pump data, so they produce real fds usable by both builtins and spawned processes.

#[cfg(feature = "unix-runtime")]
mod backend;
mod fd;
#[cfg(feature = "test-support")]
mod test_runtimes;
#[cfg(feature = "test-support")]
mod test_stdio;
#[cfg(feature = "unix-runtime")]
mod unix_exec;
mod wait;

use std::ffi::CString;
use std::io;
#[cfg(any(feature = "unix-runtime", feature = "test-support"))]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;

#[cfg(feature = "unix-runtime")]
use self::backend::{FdAction, exec, pid_from_handle, spawn_command};
pub use self::fd::{FileDescriptor, OsPipe};
#[cfg(feature = "test-support")]
pub use self::test_runtimes::{DeterministicRuntime, InMemoryCommand, InMemoryRuntime};
#[cfg(feature = "test-support")]
pub use self::test_stdio::{StringStdioIn, StringStdioOut};
use self::wait::wait_child_status;
#[cfg(feature = "unix-runtime")]
use self::wait::wait_pid_status;
#[cfg(feature = "unix-runtime")]
use self::wait::wait_process;
pub use self::wait::{ProcessEvent, WaitMode};

////////////////////////////////////////// other syscalls //////////////////////////////////////////

/// Get the parent PID.
pub fn parent_pid() -> u32 {
    unsafe { libc::getppid() as u32 }
}

/// Get the current umask (reads and restores it atomically).
pub fn get_umask() -> u32 {
    let mask = unsafe { libc::umask(0) };
    unsafe { libc::umask(mask) };
    mask as u32
}

/// Set the umask.
pub fn set_umask(mask: u32) {
    unsafe { libc::umask(mask as libc::mode_t) };
}

/// Process times from `times(2)`.
pub struct ProcessTimes {
    /// User time in seconds.
    pub user_secs: f64,
    /// System time in seconds.
    pub sys_secs: f64,
    /// Children user time in seconds.
    pub child_user_secs: f64,
    /// Children system time in seconds.
    pub child_sys_secs: f64,
}

/// Get process times via `times(2)`.
pub fn get_times() -> ProcessTimes {
    let mut tms = libc::tms {
        tms_utime: 0,
        tms_stime: 0,
        tms_cutime: 0,
        tms_cstime: 0,
    };
    unsafe { libc::times(&mut tms) };
    let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as f64;
    ProcessTimes {
        user_secs: tms.tms_utime as f64 / ticks,
        sys_secs: tms.tms_stime as f64 / ticks,
        child_user_secs: tms.tms_cutime as f64 / ticks,
        child_sys_secs: tms.tms_cstime as f64 / ticks,
    }
}

/// Expand a glob pattern into matching filenames.
pub fn glob_expand(pattern: &str) -> Vec<String> {
    let c_pattern = match CString::new(pattern) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };

    let mut glob_buf: libc::glob_t = unsafe { std::mem::zeroed() };
    let ret = unsafe { libc::glob(c_pattern.as_ptr(), 0, None, &mut glob_buf) };

    let mut results = Vec::new();
    if ret == 0 {
        for i in 0..glob_buf.gl_pathc {
            let path = unsafe { *glob_buf.gl_pathv.add(i) };
            if !path.is_null() {
                let s = unsafe { std::ffi::CStr::from_ptr(path) };
                if let Ok(s) = s.to_str() {
                    results.push(s.to_string());
                }
            }
        }
    }
    unsafe { libc::globfree(&mut glob_buf) };
    results
}

/////////////////////////////////////////// Runtime ////////////////////////////////////////////////

/// Opaque runtime-owned process identity used by the shell.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ProcessHandle(u64);

impl ProcessHandle {
    pub const fn new(raw: u64) -> Self {
        Self(raw)
    }

    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

/// Runtime spawn intent for one process.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpawnMode {
    Foreground,
    BackgroundJob,
}

/// Semantic process-group signals requested by the shell.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RuntimeSignal {
    Continue,
    Stop,
    Interrupt,
    Terminate,
}

/// Runtime spawn result including optional presentation metadata.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpawnedProcess {
    pub handle: ProcessHandle,
    pub display_pid: Option<u32>,
}

/// An inherited parent fd that should appear as `child_fd` in the spawned process.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PassedFileDescriptor {
    pub parent_fd: FileDescriptor,
    pub child_fd: FileDescriptor,
}

/// Fully resolved external command invocation.
#[derive(Debug, Clone)]
pub struct ExternalCommand {
    /// Program name (may be a bare name for PATH search or a path).
    pub program: String,
    /// Full argv including `argv[0]`.
    pub argv: Vec<String>,
    /// Environment variables for the child.
    pub env: Vec<(String, String)>,
    /// Working directory for the child.
    pub cwd: PathBuf,
    /// Whether the child should start in its own process group.
    pub create_process_group: bool,
    /// Additional inherited fds that should be dup'd into the child before exec.
    pub passed_fds: Vec<PassedFileDescriptor>,
}

#[cfg(feature = "embed")]
pub(crate) fn spawn_error_exit_status(err: &io::Error) -> i32 {
    if err.kind() == io::ErrorKind::NotFound || err.raw_os_error() == Some(libc::ENOENT) {
        127
    } else {
        126
    }
}

/// Provide the full runtime surface needed by mxsh execution.
pub trait Runtime {
    /// Runtime-owned foreground lease used to restore terminal ownership.
    type ForegroundGuard;

    /// Create an isolated runtime instance for subshell-style execution.
    ///
    /// Command substitution, subshell bodies, and shell-only pipeline stages
    /// use this to make runtime forking explicit instead of relying on `Clone`.
    fn fork(&self) -> Result<Self, std::io::Error>
    where
        Self: Sized;

    /// Spawn one external command and return a child handle.
    fn spawn_external_command(
        &mut self,
        command: &ExternalCommand,
        stdio: SpawnStdio,
        close_fds: &[FileDescriptor],
        mode: SpawnMode,
    ) -> Result<SpawnedProcess, std::io::Error>;

    /// Observe the next lifecycle event for a previously spawned process.
    fn wait_process(
        &mut self,
        process: ProcessHandle,
        mode: WaitMode,
    ) -> Result<ProcessEvent, std::io::Error>;

    /// Wait for a process identified only by a display pid when supported.
    ///
    /// `Ok(None)` means the runtime does not support pid-only waits. Unknown
    /// pids should return `io::ErrorKind::NotFound`.
    fn wait_display_pid(&mut self, _display_pid: u32) -> Result<Option<i32>, io::Error> {
        Ok(None)
    }

    /// Wait until `process` reaches a terminal status and return the shell exit code.
    fn wait_child(&mut self, process: ProcessHandle) -> i32 {
        wait_child_status(|| self.wait_process(process, WaitMode::Block))
    }

    /// Deliver a semantic signal to the process group associated with `process`.
    fn signal_process_group(
        &mut self,
        process: ProcessHandle,
        signal: RuntimeSignal,
    ) -> Result<(), std::io::Error>;

    /// Claim the terminal foreground for `process`.
    ///
    /// The returned guard represents runtime-owned state required to restore the
    /// previous foreground owner. Callers must pass that exact guard back to
    /// [`Runtime::release_foreground`] once foreground execution is done,
    /// including when command execution fails after the claim succeeds.
    fn claim_foreground(
        &mut self,
        process: ProcessHandle,
        tty: FileDescriptor,
    ) -> Result<Self::ForegroundGuard, std::io::Error>;

    /// Restore a previously claimed foreground lease.
    ///
    /// Implementations should make this operation idempotent and best-effort when
    /// possible so terminal ownership is restored even if earlier execution stages
    /// failed. If restoration cannot be completed, return the restore error after
    /// attempting any remaining cleanup that keeps terminal ownership safe.
    fn release_foreground(&mut self, guard: Self::ForegroundGuard) -> Result<(), std::io::Error>;

    /// Return true when the runtime can execute `program` without PATH-based host lookup.
    ///
    /// Implementations may keep this as a fast-path hint for runtimes with internal
    /// command registries, but callers must not treat it as authoritative lookup.
    /// Runtime-based PATH resolution and error classification belong in
    /// [`Runtime::resolve_command_path`].
    fn has_command(&self, _program: &str) -> bool {
        false
    }

    /// Resolve an external command using PATH-like lookup rules.
    ///
    /// `path_var` is a colon-separated search path used when `program` is not already
    /// absolute or explicitly relative. Successful lookup returns the exact program
    /// path the runtime will execute. Missing commands should return
    /// `io::ErrorKind::NotFound`; commands found but not executable should return
    /// `io::ErrorKind::PermissionDenied`.
    fn resolve_command_path(&self, program: &str, _path_var: &str) -> Result<PathBuf, io::Error> {
        if self.has_command(program) {
            Ok(PathBuf::from(program))
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("{program}: command not found"),
            ))
        }
    }

    /// Replace the current process with a new program.
    ///
    /// Non-`exec` runtimes should return `io::ErrorKind::Unsupported` to make
    /// limitations explicit.
    fn exec_replace(
        &self,
        program: &str,
        argv: &[String],
        env: &[(String, String)],
        cwd: &Path,
    ) -> Result<(), std::io::Error>;
}

#[cfg(any(feature = "unix-runtime", feature = "test-support"))]
fn resolve_executable_path(path: &Path) -> Result<PathBuf, io::Error> {
    let meta = match std::fs::metadata(path) {
        Ok(meta) => meta,
        Err(err) => {
            return Err(io::Error::new(io::ErrorKind::NotFound, err.to_string()));
        }
    };
    if !meta.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("{}: Permission denied", path.display()),
        ));
    }
    if meta.permissions().mode() & 0o111 == 0 {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("{}: Permission denied", path.display()),
        ));
    }
    Ok(path.to_path_buf())
}

#[cfg(any(feature = "unix-runtime", feature = "test-support"))]
fn resolve_command_path(program: &str, path_var: &str) -> Result<PathBuf, io::Error> {
    if program.contains('/') {
        return resolve_executable_path(Path::new(program));
    }
    for dir in path_var.split(':') {
        let candidate = Path::new(dir).join(program);
        match resolve_executable_path(&candidate) {
            Err(err) if err.kind() == io::ErrorKind::NotFound => {}
            other => return other,
        }
    }
    Err(io::Error::new(
        io::ErrorKind::NotFound,
        format!("{program}: command not found"),
    ))
}

/////////////////////////////////////////// UnixRuntime ////////////////////////////////////////////

/// Unix implementation of the runtime trait using `posix_spawnp` and OS pipes.
#[cfg(feature = "unix-runtime")]
#[derive(Clone, Debug)]
pub struct UnixRuntime {}

#[cfg(feature = "unix-runtime")]
#[derive(Clone, Copy, Debug)]
pub struct UnixForegroundGuard {
    tty: FileDescriptor,
    previous_pgid: libc::pid_t,
}

#[cfg(feature = "unix-runtime")]
impl UnixRuntime {
    /// Create a new UnixRuntime.
    pub fn new() -> Self {
        Self {}
    }
}

#[cfg(feature = "unix-runtime")]
impl Default for UnixRuntime {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "unix-runtime")]
impl Runtime for UnixRuntime {
    type ForegroundGuard = UnixForegroundGuard;

    fn fork(&self) -> Result<Self, std::io::Error> {
        Ok(Self::new())
    }

    fn spawn_external_command(
        &mut self,
        command: &ExternalCommand,
        stdio: SpawnStdio,
        close_fds: &[FileDescriptor],
        mode: SpawnMode,
    ) -> Result<SpawnedProcess, std::io::Error> {
        let fd_actions: Vec<FdAction> = close_fds.iter().copied().map(FdAction::Close).collect();
        let create_process_group =
            command.create_process_group || matches!(mode, SpawnMode::BackgroundJob);
        let pid = spawn_command(command, create_process_group, stdio, &fd_actions)?;
        Ok(SpawnedProcess {
            handle: ProcessHandle::new(pid as u64),
            display_pid: Some(pid as u32),
        })
    }

    fn wait_process(
        &mut self,
        process: ProcessHandle,
        mode: WaitMode,
    ) -> Result<ProcessEvent, std::io::Error> {
        wait_process(pid_from_handle(process)?, mode)
    }

    fn wait_display_pid(&mut self, display_pid: u32) -> Result<Option<i32>, io::Error> {
        wait_pid_status(display_pid as libc::pid_t).map(Some)
    }

    fn signal_process_group(
        &mut self,
        process: ProcessHandle,
        signal: RuntimeSignal,
    ) -> Result<(), std::io::Error> {
        let pid = pid_from_handle(process)?;
        let signal = match signal {
            RuntimeSignal::Continue => libc::SIGCONT,
            RuntimeSignal::Stop => libc::SIGSTOP,
            RuntimeSignal::Interrupt => libc::SIGINT,
            RuntimeSignal::Terminate => libc::SIGTERM,
        };
        if unsafe { libc::kill(-pid, signal) } == 0 {
            Ok(())
        } else {
            Err(std::io::Error::last_os_error())
        }
    }

    fn claim_foreground(
        &mut self,
        process: ProcessHandle,
        tty: FileDescriptor,
    ) -> Result<Self::ForegroundGuard, std::io::Error> {
        let pid = pid_from_handle(process)?;
        let previous_pgid = unsafe { libc::getpgrp() };
        if unsafe { libc::tcsetpgrp(tty.into_raw_fd(), pid) } == 0 {
            Ok(UnixForegroundGuard { tty, previous_pgid })
        } else {
            Err(std::io::Error::last_os_error())
        }
    }

    fn release_foreground(&mut self, guard: Self::ForegroundGuard) -> Result<(), std::io::Error> {
        if unsafe { libc::tcsetpgrp(guard.tty.into_raw_fd(), guard.previous_pgid) } == 0 {
            Ok(())
        } else {
            Err(std::io::Error::last_os_error())
        }
    }

    fn has_command(&self, _program: &str) -> bool {
        false
    }

    fn resolve_command_path(&self, program: &str, path_var: &str) -> Result<PathBuf, io::Error> {
        resolve_command_path(program, path_var)
    }

    fn exec_replace(
        &self,
        program: &str,
        argv: &[String],
        env: &[(String, String)],
        cwd: &Path,
    ) -> Result<(), std::io::Error> {
        exec(program, argv, env, cwd)
    }
}

///////////////////////////////////////////// SpawnStdio ///////////////////////////////////////////

/// Parent-provided stdio fds for child processes.
#[derive(Clone, Copy, Debug)]
pub struct SpawnStdio {
    /// Stdin fd for the child.
    pub stdin_fd: FileDescriptor,
    /// Stdout fd for the child.
    pub stdout_fd: FileDescriptor,
    /// Stderr fd for the child.
    pub stderr_fd: FileDescriptor,
}

impl Default for SpawnStdio {
    fn default() -> Self {
        Self {
            stdin_fd: FileDescriptor::STDIN,
            stdout_fd: FileDescriptor::STDOUT,
            stderr_fd: FileDescriptor::STDERR,
        }
    }
}

#[cfg(all(test, feature = "test-support", feature = "unix-runtime"))]
mod tests;