clm-kernel 0.0.1

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Platform-Agnostic C FFI Redirection & Process Execution.
//!
//! Provides RAII wrappers (`FdRedirectGuard`) ensuring that host standard file descriptors
//! (stdout, stderr) are strictly restored upon drop, early return, or thread panic,
//! preserving host terminal integrity and eliminating duplicate raw unsafe FFI.

use std::io;
use std::os::raw::c_int;

#[cfg(unix)]
unsafe fn c_dup(fd: c_int) -> c_int {
    unsafe extern "C" {
        fn dup(fd: c_int) -> c_int;
    }
    unsafe { dup(fd) }
}

#[cfg(unix)]
unsafe fn c_dup2(src: c_int, dst: c_int) -> c_int {
    unsafe extern "C" {
        fn dup2(src: c_int, dst: c_int) -> c_int;
    }
    unsafe { dup2(src, dst) }
}

#[cfg(unix)]
unsafe fn c_close(fd: c_int) -> c_int {
    unsafe extern "C" {
        fn close(fd: c_int) -> c_int;
    }
    unsafe { close(fd) }
}

#[cfg(windows)]
unsafe fn c_dup(fd: c_int) -> c_int {
    unsafe extern "C" {
        fn _dup(fd: c_int) -> c_int;
    }
    unsafe { _dup(fd) }
}

#[cfg(windows)]
unsafe fn c_dup2(src: c_int, dst: c_int) -> c_int {
    unsafe extern "C" {
        fn _dup2(src: c_int, dst: c_int) -> c_int;
    }
    unsafe { _dup2(src, dst) }
}

#[cfg(windows)]
unsafe fn c_close(fd: c_int) -> c_int {
    unsafe extern "C" {
        fn _close(fd: c_int) -> c_int;
    }
    unsafe { _close(fd) }
}

/// Duplicate an open file descriptor.
#[inline]
pub unsafe fn sys_dup(fd: c_int) -> c_int {
    unsafe { c_dup(fd) }
}

/// Duplicate an open file descriptor onto another file descriptor.
#[inline]
pub unsafe fn sys_dup2(src: c_int, dst: c_int) -> c_int {
    unsafe { c_dup2(src, dst) }
}

/// Close a raw file descriptor.
#[inline]
pub unsafe fn sys_close(fd: c_int) -> c_int {
    unsafe { c_close(fd) }
}

/// Extracts a raw file descriptor from a std::fs::File across Unix and Windows.
#[cfg(unix)]
pub fn get_file_fd(file: &std::fs::File) -> c_int {
    use std::os::unix::io::AsRawFd;
    file.as_raw_fd()
}

#[cfg(windows)]
pub fn get_file_fd(file: &std::fs::File) -> c_int {
    use std::os::windows::io::AsRawHandle;
    unsafe extern "C" {
        fn _open_osfhandle(os_handle: isize, flags: c_int) -> c_int;
    }
    unsafe { _open_osfhandle(file.as_raw_handle() as isize, 0) }
}

#[cfg(not(any(unix, windows)))]
pub fn get_file_fd(_file: &std::fs::File) -> c_int {
    -1
}

/// RAII File Descriptor Redirection Guard.
///
/// Guarantees that target file descriptors (e.g. stdout=1, stderr=2) are restored
/// to their original target upon scope exit, even if panics or early returns occur.
/// Operates as a Cordis Disposable, preserving host terminal integrity in PKC edge nodes.
#[derive(Debug)]
pub struct FdRedirectGuard {
    target_fd: c_int,
    saved_fd: c_int,
    active: bool,
}

impl FdRedirectGuard {
    /// Redirects stdout (fd 1) to the given `new_fd`.
    pub fn redirect_stdout_to(new_fd: c_int) -> io::Result<Self> {
        Self::redirect(1, new_fd)
    }

    /// Redirects stderr (fd 2) to the given `new_fd`.
    pub fn redirect_stderr_to(new_fd: c_int) -> io::Result<Self> {
        Self::redirect(2, new_fd)
    }

    /// Redirects `target_fd` to `new_fd`, saving the original target for later restoration.
    pub fn redirect(target_fd: c_int, new_fd: c_int) -> io::Result<Self> {
        use std::io::Write;
        if target_fd == 1 {
            let _ = io::stdout().flush();
        } else if target_fd == 2 {
            let _ = io::stderr().flush();
        }

        let saved_fd = unsafe { sys_dup(target_fd) };
        if saved_fd < 0 {
            return Err(io::Error::last_os_error());
        }

        if unsafe { sys_dup2(new_fd, target_fd) } < 0 {
            let err = io::Error::last_os_error();
            unsafe { sys_close(saved_fd); }
            return Err(err);
        }

        Ok(Self {
            target_fd,
            saved_fd,
            active: true,
        })
    }

    /// Returns the target file descriptor (e.g. 1 for stdout, 2 for stderr).
    pub fn target_fd(&self) -> c_int {
        self.target_fd
    }

    /// Returns the saved file descriptor holding the original destination.
    pub fn saved_fd(&self) -> c_int {
        self.saved_fd
    }

    /// Returns whether this guard is currently actively redirecting.
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Explicitly restores the original file descriptor before drop.
    pub fn restore(&mut self) -> io::Result<()> {
        if !self.active {
            return Ok(());
        }
        use std::io::Write;
        if self.target_fd == 1 {
            let _ = io::stdout().flush();
        } else if self.target_fd == 2 {
            let _ = io::stderr().flush();
        }

        self.active = false;
        let res = unsafe { sys_dup2(self.saved_fd, self.target_fd) };
        unsafe { sys_close(self.saved_fd); }
        if res < 0 {
            Err(io::Error::last_os_error())
        } else {
            Ok(())
        }
    }
}

impl Drop for FdRedirectGuard {
    fn drop(&mut self) {
        let _ = self.restore();
    }
}

/// Executes a command with a strict timeout, capturing stdout and stderr.
pub fn run_command_with_timeout(
    cmd: &mut std::process::Command,
    timeout: std::time::Duration,
) -> Result<(std::process::ExitStatus, String, String), String> {
    use std::io::Read;
    use std::sync::{Arc, Mutex};

    let mut child = cmd
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| e.to_string())?;

    let mut stdout = child.stdout.take().unwrap();
    let mut stderr = child.stderr.take().unwrap();

    let out_buf = Arc::new(Mutex::new(Vec::new()));
    let err_buf = Arc::new(Mutex::new(Vec::new()));

    let out_buf_clone = out_buf.clone();
    let out_thread = std::thread::spawn(move || {
        let mut buf = Vec::new();
        let _ = stdout.read_to_end(&mut buf);
        *out_buf_clone.lock().unwrap() = buf;
    });

    let err_buf_clone = err_buf.clone();
    let err_thread = std::thread::spawn(move || {
        let mut buf = Vec::new();
        let _ = stderr.read_to_end(&mut buf);
        *err_buf_clone.lock().unwrap() = buf;
    });

    let start = std::time::Instant::now();
    let mut status = None;
    while start.elapsed() < timeout {
        match child.try_wait() {
            Ok(Some(s)) => {
                status = Some(s);
                break;
            }
            Ok(None) => {
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            Err(e) => {
                return Err(e.to_string());
            }
        }
    }

    if let Some(s) = status {
        let _ = out_thread.join();
        let _ = err_thread.join();
        let stdout_bytes = Arc::try_unwrap(out_buf).unwrap().into_inner().unwrap();
        let stderr_bytes = Arc::try_unwrap(err_buf).unwrap().into_inner().unwrap();
        let stdout_str = String::from_utf8_lossy(&stdout_bytes).into_owned();
        let stderr_str = String::from_utf8_lossy(&stderr_bytes).into_owned();
        Ok((s, stdout_str, stderr_str))
    } else {
        let _ = child.kill();
        let _ = out_thread.join();
        let _ = err_thread.join();
        Err(format!("Timeout after {:?}", timeout))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Read;

    #[test]
    fn test_fd_redirect_guard_restores_on_drop() {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let file = File::create(temp_file.path()).unwrap();
        let new_fd = get_file_fd(&file);
        assert!(new_fd >= 0);

        {
            let guard = FdRedirectGuard::redirect_stdout_to(new_fd).unwrap();
            assert!(guard.is_active());
            #[cfg(unix)]
            {
                use std::os::unix::io::FromRawFd;
                use std::io::Write;
                let mut f = std::mem::ManuallyDrop::new(unsafe { File::from_raw_fd(1) });
                f.write_all(b"Hello via redirected stdout!").unwrap();
                f.flush().unwrap();
            }
            #[cfg(windows)]
            {
                use std::os::windows::io::FromRawHandle;
                use std::io::Write;
                let mut f = std::mem::ManuallyDrop::new(unsafe { File::from_raw_handle(1 as _) });
                f.write_all(b"Hello via redirected stdout!").unwrap();
                f.flush().unwrap();
            }
            // Drop guard here to restore
            drop(guard);
        }

        // Stdout should now be restored back to the console
        println!("This goes to console normally.");

        let mut content = String::new();
        let mut read_f = File::open(temp_file.path()).unwrap();
        read_f.read_to_string(&mut content).unwrap();
        assert!(content.contains("Hello via redirected stdout!"));
    }

    #[test]
    fn test_fd_redirect_guard_restores_on_panic() {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let file = File::create(temp_file.path()).unwrap();
        let new_fd = get_file_fd(&file);

        let _ = std::panic::catch_unwind(move || {
            let _guard = FdRedirectGuard::redirect_stdout_to(new_fd).unwrap();
            panic!("Induced test panic while stdout redirected");
        });

        // Verify stdout is still usable and functional after unwinding panic
        print!("Console restored after catch_unwind!");
        use std::io::Write;
        std::io::stdout().flush().unwrap();
    }
}