Skip to main content

clm_rust_core/layer0/
sys_ffi.rs

1//! Platform-Agnostic C FFI Redirection & Process Execution.
2//!
3//! Provides RAII wrappers (`FdRedirectGuard`) ensuring that host standard file descriptors
4//! (stdout, stderr) are strictly restored upon drop, early return, or thread panic,
5//! preserving host terminal integrity and eliminating duplicate raw unsafe FFI.
6
7use std::io;
8use std::os::raw::c_int;
9
10#[cfg(unix)]
11unsafe fn c_dup(fd: c_int) -> c_int {
12    unsafe extern "C" {
13        fn dup(fd: c_int) -> c_int;
14    }
15    unsafe { dup(fd) }
16}
17
18#[cfg(unix)]
19unsafe fn c_dup2(src: c_int, dst: c_int) -> c_int {
20    unsafe extern "C" {
21        fn dup2(src: c_int, dst: c_int) -> c_int;
22    }
23    unsafe { dup2(src, dst) }
24}
25
26#[cfg(unix)]
27unsafe fn c_close(fd: c_int) -> c_int {
28    unsafe extern "C" {
29        fn close(fd: c_int) -> c_int;
30    }
31    unsafe { close(fd) }
32}
33
34#[cfg(windows)]
35unsafe fn c_dup(fd: c_int) -> c_int {
36    unsafe extern "C" {
37        fn _dup(fd: c_int) -> c_int;
38    }
39    unsafe { _dup(fd) }
40}
41
42#[cfg(windows)]
43unsafe fn c_dup2(src: c_int, dst: c_int) -> c_int {
44    unsafe extern "C" {
45        fn _dup2(src: c_int, dst: c_int) -> c_int;
46    }
47    unsafe { _dup2(src, dst) }
48}
49
50#[cfg(windows)]
51unsafe fn c_close(fd: c_int) -> c_int {
52    unsafe extern "C" {
53        fn _close(fd: c_int) -> c_int;
54    }
55    unsafe { _close(fd) }
56}
57
58/// Duplicate an open file descriptor.
59#[inline]
60pub unsafe fn sys_dup(fd: c_int) -> c_int {
61    unsafe { c_dup(fd) }
62}
63
64/// Duplicate an open file descriptor onto another file descriptor.
65#[inline]
66pub unsafe fn sys_dup2(src: c_int, dst: c_int) -> c_int {
67    unsafe { c_dup2(src, dst) }
68}
69
70/// Close a raw file descriptor.
71#[inline]
72pub unsafe fn sys_close(fd: c_int) -> c_int {
73    unsafe { c_close(fd) }
74}
75
76/// Extracts a raw file descriptor from a std::fs::File across Unix and Windows.
77#[cfg(unix)]
78pub fn get_file_fd(file: &std::fs::File) -> c_int {
79    use std::os::unix::io::AsRawFd;
80    file.as_raw_fd()
81}
82
83#[cfg(windows)]
84pub fn get_file_fd(file: &std::fs::File) -> c_int {
85    use std::os::windows::io::AsRawHandle;
86    unsafe extern "C" {
87        fn _open_osfhandle(os_handle: isize, flags: c_int) -> c_int;
88    }
89    unsafe { _open_osfhandle(file.as_raw_handle() as isize, 0) }
90}
91
92#[cfg(not(any(unix, windows)))]
93pub fn get_file_fd(_file: &std::fs::File) -> c_int {
94    -1
95}
96
97/// RAII File Descriptor Redirection Guard.
98///
99/// Guarantees that target file descriptors (e.g. stdout=1, stderr=2) are restored
100/// to their original target upon scope exit, even if panics or early returns occur.
101/// Operates as a Cordis Disposable, preserving host terminal integrity in PKC edge nodes.
102#[derive(Debug)]
103pub struct FdRedirectGuard {
104    target_fd: c_int,
105    saved_fd: c_int,
106    active: bool,
107}
108
109impl FdRedirectGuard {
110    /// Redirects stdout (fd 1) to the given `new_fd`.
111    pub fn redirect_stdout_to(new_fd: c_int) -> io::Result<Self> {
112        Self::redirect(1, new_fd)
113    }
114
115    /// Redirects stderr (fd 2) to the given `new_fd`.
116    pub fn redirect_stderr_to(new_fd: c_int) -> io::Result<Self> {
117        Self::redirect(2, new_fd)
118    }
119
120    /// Redirects `target_fd` to `new_fd`, saving the original target for later restoration.
121    pub fn redirect(target_fd: c_int, new_fd: c_int) -> io::Result<Self> {
122        use std::io::Write;
123        if target_fd == 1 {
124            let _ = io::stdout().flush();
125        } else if target_fd == 2 {
126            let _ = io::stderr().flush();
127        }
128
129        let saved_fd = unsafe { sys_dup(target_fd) };
130        if saved_fd < 0 {
131            return Err(io::Error::last_os_error());
132        }
133
134        if unsafe { sys_dup2(new_fd, target_fd) } < 0 {
135            let err = io::Error::last_os_error();
136            unsafe { sys_close(saved_fd); }
137            return Err(err);
138        }
139
140        Ok(Self {
141            target_fd,
142            saved_fd,
143            active: true,
144        })
145    }
146
147    /// Returns the target file descriptor (e.g. 1 for stdout, 2 for stderr).
148    pub fn target_fd(&self) -> c_int {
149        self.target_fd
150    }
151
152    /// Returns the saved file descriptor holding the original destination.
153    pub fn saved_fd(&self) -> c_int {
154        self.saved_fd
155    }
156
157    /// Returns whether this guard is currently actively redirecting.
158    pub fn is_active(&self) -> bool {
159        self.active
160    }
161
162    /// Explicitly restores the original file descriptor before drop.
163    pub fn restore(&mut self) -> io::Result<()> {
164        if !self.active {
165            return Ok(());
166        }
167        use std::io::Write;
168        if self.target_fd == 1 {
169            let _ = io::stdout().flush();
170        } else if self.target_fd == 2 {
171            let _ = io::stderr().flush();
172        }
173
174        self.active = false;
175        let res = unsafe { sys_dup2(self.saved_fd, self.target_fd) };
176        unsafe { sys_close(self.saved_fd); }
177        if res < 0 {
178            Err(io::Error::last_os_error())
179        } else {
180            Ok(())
181        }
182    }
183}
184
185impl Drop for FdRedirectGuard {
186    fn drop(&mut self) {
187        let _ = self.restore();
188    }
189}
190
191/// Executes a command with a strict timeout, capturing stdout and stderr.
192pub fn run_command_with_timeout(
193    cmd: &mut std::process::Command,
194    timeout: std::time::Duration,
195) -> Result<(std::process::ExitStatus, String, String), String> {
196    use std::io::Read;
197    use std::sync::{Arc, Mutex};
198
199    let mut child = cmd
200        .stdout(std::process::Stdio::piped())
201        .stderr(std::process::Stdio::piped())
202        .spawn()
203        .map_err(|e| e.to_string())?;
204
205    let mut stdout = child.stdout.take().unwrap();
206    let mut stderr = child.stderr.take().unwrap();
207
208    let out_buf = Arc::new(Mutex::new(Vec::new()));
209    let err_buf = Arc::new(Mutex::new(Vec::new()));
210
211    let out_buf_clone = out_buf.clone();
212    let out_thread = std::thread::spawn(move || {
213        let mut buf = Vec::new();
214        let _ = stdout.read_to_end(&mut buf);
215        *out_buf_clone.lock().unwrap() = buf;
216    });
217
218    let err_buf_clone = err_buf.clone();
219    let err_thread = std::thread::spawn(move || {
220        let mut buf = Vec::new();
221        let _ = stderr.read_to_end(&mut buf);
222        *err_buf_clone.lock().unwrap() = buf;
223    });
224
225    let start = std::time::Instant::now();
226    let mut status = None;
227    while start.elapsed() < timeout {
228        match child.try_wait() {
229            Ok(Some(s)) => {
230                status = Some(s);
231                break;
232            }
233            Ok(None) => {
234                std::thread::sleep(std::time::Duration::from_millis(5));
235            }
236            Err(e) => {
237                return Err(e.to_string());
238            }
239        }
240    }
241
242    if let Some(s) = status {
243        let _ = out_thread.join();
244        let _ = err_thread.join();
245        let stdout_bytes = Arc::try_unwrap(out_buf).unwrap().into_inner().unwrap();
246        let stderr_bytes = Arc::try_unwrap(err_buf).unwrap().into_inner().unwrap();
247        let stdout_str = String::from_utf8_lossy(&stdout_bytes).into_owned();
248        let stderr_str = String::from_utf8_lossy(&stderr_bytes).into_owned();
249        Ok((s, stdout_str, stderr_str))
250    } else {
251        let _ = child.kill();
252        let _ = out_thread.join();
253        let _ = err_thread.join();
254        Err(format!("Timeout after {:?}", timeout))
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use std::fs::File;
262    use std::io::Read;
263    use std::sync::{Mutex, MutexGuard};
264
265    // Both tests repoint the process-wide fd 1. libtest runs tests on threads, so without this
266    // lock one test's write can land in the other's temp file (INV-588: `make test` runs the
267    // crate in one threaded `cargo test`, not a `--test-threads=1` slice).
268    static STDOUT_FD: Mutex<()> = Mutex::new(());
269
270    fn hold_stdout_fd() -> MutexGuard<'static, ()> {
271        STDOUT_FD.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
272    }
273
274    #[test]
275    fn test_fd_redirect_guard_restores_on_drop() {
276        let _fd1 = hold_stdout_fd();
277        let temp_file = tempfile::NamedTempFile::new().unwrap();
278        let file = File::create(temp_file.path()).unwrap();
279        let new_fd = get_file_fd(&file);
280        assert!(new_fd >= 0);
281
282        {
283            let guard = FdRedirectGuard::redirect_stdout_to(new_fd).unwrap();
284            assert!(guard.is_active());
285            #[cfg(unix)]
286            {
287                use std::os::unix::io::FromRawFd;
288                use std::io::Write;
289                let mut f = std::mem::ManuallyDrop::new(unsafe { File::from_raw_fd(1) });
290                f.write_all(b"Hello via redirected stdout!").unwrap();
291                f.flush().unwrap();
292            }
293            #[cfg(windows)]
294            {
295                use std::os::windows::io::FromRawHandle;
296                use std::io::Write;
297                unsafe extern "C" {
298                    fn _get_osfhandle(fd: std::os::raw::c_int) -> isize;
299                }
300                let handle = unsafe { _get_osfhandle(1) };
301                let mut f = std::mem::ManuallyDrop::new(unsafe { File::from_raw_handle(handle as _) });
302                f.write_all(b"Hello via redirected stdout!").unwrap();
303                f.flush().unwrap();
304            }
305            // Drop guard here to restore
306            drop(guard);
307        }
308
309        // Stdout should now be restored back to the console
310        println!("This goes to console normally.");
311
312        let mut content = String::new();
313        let mut read_f = File::open(temp_file.path()).unwrap();
314        read_f.read_to_string(&mut content).unwrap();
315        assert!(content.contains("Hello via redirected stdout!"));
316    }
317
318    #[test]
319    fn test_fd_redirect_guard_restores_on_panic() {
320        let _fd1 = hold_stdout_fd();
321        let temp_file = tempfile::NamedTempFile::new().unwrap();
322        let file = File::create(temp_file.path()).unwrap();
323        let new_fd = get_file_fd(&file);
324
325        let _ = std::panic::catch_unwind(move || {
326            let _guard = FdRedirectGuard::redirect_stdout_to(new_fd).unwrap();
327            panic!("Induced test panic while stdout redirected");
328        });
329
330        // Verify stdout is still usable and functional after unwinding panic
331        print!("Console restored after catch_unwind!");
332        use std::io::Write;
333        std::io::stdout().flush().unwrap();
334    }
335}