Skip to main content

c/
system.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// system()
6// ============================================================
7
8#[no_mangle]
9pub unsafe extern "C" fn system(cmd: *const c_char) -> c_int {
10    if cmd.is_null() {
11        // test shell availability via fork+exec
12        let pid = sys_fork();
13        if pid == 0 {
14            let sh = b"/bin/sh\0".as_ptr() as *const c_char;
15            let dash_c = b"-c\0".as_ptr() as *const c_char;
16            let exit0 = b"exit 0\0".as_ptr() as *const c_char;
17            let argv = [b"sh\0".as_ptr() as *const c_char, dash_c, exit0, core::ptr::null()];
18            sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
19            _exit(127);
20        }
21        if pid < 0 { return -1; }
22        let mut status: c_int = 0;
23        loop {
24            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
25            if r >= 0 { return status; }
26            if r != -4 { return -1; } // not EINTR
27        }
28    }
29
30    let sa_ignore = KSigAction {
31        sa_handler: SIG_IGN,
32        sa_flags: SA_RESTORER,
33        sa_restorer: sig_restorer as *const () as usize,
34        sa_mask: [0],
35    };
36    let mut oldint: KSigAction = core::mem::zeroed();
37    let mut oldquit: KSigAction = core::mem::zeroed();
38
39    sys_rt_sigaction(SIGINT, &sa_ignore, &mut oldint, 8);
40    sys_rt_sigaction(SIGQUIT, &sa_ignore, &mut oldquit, 8);
41
42    let mut block_set: SigSetT = 0;
43    block_set |= 1u64 << (SIGCHLD - 1);
44    let mut oldmask: SigSetT = 0;
45    sys_rt_sigprocmask(SIG_BLOCK, &block_set, &mut oldmask, 8);
46
47    let pid = sys_fork();
48
49    if pid == 0 {
50        sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
51        sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
52        sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
53
54        let sh = b"/bin/sh\0".as_ptr() as *const c_char;
55        let argv = [
56            b"sh\0".as_ptr() as *const c_char,
57            b"-c\0".as_ptr() as *const c_char,
58            cmd,
59            core::ptr::null(),
60        ];
61        sys_execve(sh, argv.as_ptr(), __environ as *const *const c_char);
62        _exit(127);
63    }
64
65    let mut status: c_int = -1;
66    if pid > 0 {
67        loop {
68            let r = sys_wait4(pid as c_int, &mut status, 0, core::ptr::null_mut());
69            if r >= 0 { break; }
70            if r != -4 { break; } // not EINTR
71        }
72    }
73
74    sys_rt_sigaction(SIGINT, &oldint, core::ptr::null_mut(), 8);
75    sys_rt_sigaction(SIGQUIT, &oldquit, core::ptr::null_mut(), 8);
76    sys_rt_sigprocmask(SIG_SETMASK, &oldmask, core::ptr::null_mut(), 8);
77
78    status
79}
80