Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ members = [
# T-Ground-Engine Phase 1 — type-structure validation for Rust target
# primitive declarations loaded through v3-compiler's public accessor.
"src/v3/grounding_engine",
# Linux ExecuteCommand unshare bootstrap — fd3 sentinel + FD_CLOEXEC before execvp
"src/v3/execute_command_bootstrap",
# v1 compiler — ARCHIVED. No longer in the build or generation path.
# Retained in src/v1/ for historical reference. Can be deleted.
]
Expand Down
16 changes: 16 additions & 0 deletions src/v3/execute_command_bootstrap/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "execute-command-bootstrap"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "Linux bootstrap for ExecuteCommand unshare: fd3 sentinel + FD_CLOEXEC before execvp"

[[bin]]
name = "gunbc_execute_command_bootstrap"
path = "src/main.rs"

[target.'cfg(target_os = "linux")'.dependencies]
libc = { version = "0.2", default-features = false }

[target.'cfg(target_os = "linux")'.dev-dependencies]
libc = { version = "0.2", default-features = false }
134 changes: 134 additions & 0 deletions src/v3/execute_command_bootstrap/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//! `gunbc_execute_command_bootstrap` — Linux-only helper invoked under `unshare(1)` instead of a
//! pure `sh -c` bootstrap so **fd 3** can be marked `FD_CLOEXEC` immediately before `execvp(3)`,
//! closing the sentinel channel atomically on successful exec (POSIX `sh` cannot do this between
//! sentinel writes and `exec`).
//!
//! **Protocol on fd 3** (write end held by this process until `exec` or terminal failure):
//! - `s` — helper started
//! - `e` — about to `execvp` the logical user command
//! - `f` — `execvp` returned (final exec failed); parent may observe `sef` vs `se` + EOF
//!
//! **Invocation:** `argv[1]` is the logical program (`execvp` file), `argv[2..]` are its arguments.
//! This matches the prior `sh -c 'exec …' "$0" "$@"'` shape (`$0` / `$@` after the script).

#[cfg(not(target_os = "linux"))]
fn main() {
eprintln!("gunbc_execute_command_bootstrap: Linux only (build artifact for non-Linux CI).");
std::process::exit(2);
}

#[cfg(target_os = "linux")]
fn main() {
linux::main();
}

#[cfg(target_os = "linux")]
mod linux {
use std::ffi::{CString, OsStr};
use std::io::ErrorKind;
use std::os::unix::ffi::OsStrExt;
use std::process::exit;

const SENTINEL_FD: i32 = 3;

fn write_all(fd: i32, bytes: &[u8]) -> std::io::Result<()> {
let mut off = 0usize;
while off < bytes.len() {
let n = unsafe {
libc::write(
fd,
bytes[off..].as_ptr().cast::<libc::c_void>(),
bytes.len() - off,
)
};
if n < 0 {
return Err(std::io::Error::last_os_error());
}
if n == 0 {
return Err(std::io::Error::new(
ErrorKind::WriteZero,
"write(2) returned 0 on sentinel fd",
));
}
off += n as usize;
}
Ok(())
}

fn set_cloexec_on_sentinel_fd() -> std::io::Result<()> {
let flags = unsafe { libc::fcntl(SENTINEL_FD, libc::F_GETFD) };
if flags < 0 {
return Err(std::io::Error::last_os_error());
}
let rc = unsafe { libc::fcntl(SENTINEL_FD, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
if rc < 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}

fn cstrings_from_user_argv() -> Result<Vec<CString>, ()> {
let mut out = Vec::new();
for arg in std::env::args_os().skip(1) {
let Some(cs) = cstring_from_os_str(&arg) else {
return Err(());
};
out.push(cs);
}
Ok(out)
}

fn cstring_from_os_str(s: &OsStr) -> Option<CString> {
CString::new(s.as_bytes()).ok()
}

pub(super) fn main() {
let user_argv = match cstrings_from_user_argv() {
Ok(v) if !v.is_empty() => v,
Ok(_) => {
// No logical command — invalid invocation; do not emit partial sentinel stream.
exit(127);
}
Err(()) => {
// Cannot represent argv for `execvp` (e.g. interior NUL) — same `sef` surface as a
// failed exec so the parent can fail-closed.
let _ = write_all(SENTINEL_FD, b"s");
let _ = write_all(SENTINEL_FD, b"e");
let _ = write_all(SENTINEL_FD, b"f");
exit(125);
}
};

if write_all(SENTINEL_FD, b"s").is_err() {
exit(124);
}

let mut argv: Vec<*const libc::c_char> = user_argv
.iter()
.map(|s| s.as_ptr().cast::<libc::c_char>())
.collect();
argv.push(std::ptr::null());

if write_all(SENTINEL_FD, b"e").is_err() {
let _ = write_all(SENTINEL_FD, b"f");
exit(123);
}

if set_cloexec_on_sentinel_fd().is_err() {
let _ = write_all(SENTINEL_FD, b"f");
exit(122);
}

unsafe {
libc::execvp(argv[0], argv.as_ptr());
}

let _ = write_all(SENTINEL_FD, b"f");
let code = if std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT) {
127
} else {
126
};
exit(code);
}
}
81 changes: 81 additions & 0 deletions src/v3/execute_command_bootstrap/tests/sentinel_fd3_protocol.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#![cfg(target_os = "linux")]

//! Hermetic receipts for the fd3 sentinel stream (`s` / `e` / `f`) and CLOEXEC-before-exec
//! behavior. The parent simulates the runner by wiring the write end of a pipe to fd 3 in the
//! child before exec.

use std::io::Read;
use std::os::fd::FromRawFd;
use std::os::unix::process::CommandExt;
use std::process::Command;

fn pipe() -> (i32, i32) {
let mut fds = [0_i32; 2];
unsafe {
assert_eq!(libc::pipe(fds.as_mut_ptr()), 0, "pipe(2)");
}
(fds[0], fds[1])
}

fn spawn_bootstrap_with_sentinel_fd(
bin: &str,
read_fd: i32,
write_fd: i32,
args: &[&str],
) -> std::process::Child {
let mut cmd = Command::new(bin);
for a in args {
cmd.arg(a);
}
unsafe {
cmd.pre_exec(move || {
if libc::dup2(write_fd, 3) < 0 {
return Err(std::io::Error::last_os_error());
}
if write_fd != 3 {
libc::close(write_fd);
}
libc::close(read_fd);
Ok(())
});
}
cmd.spawn().expect("spawn bootstrap")
}

fn read_pipe_to_end(read_fd: i32) -> Vec<u8> {
unsafe {
let mut file = std::fs::File::from_raw_fd(read_fd);
let mut buf = Vec::new();
file.read_to_end(&mut buf).expect("read sentinel pipe");
buf
}
}

#[test]
fn exec_true_emits_se_then_eof_on_sentinel_fd() {
let (r, w) = pipe();
let bin = env!("CARGO_BIN_EXE_gunbc_execute_command_bootstrap");
let mut child = spawn_bootstrap_with_sentinel_fd(bin, r, w, &["true"]);
unsafe {
libc::close(w);
}
let buf = read_pipe_to_end(r);
let status = child.wait().expect("wait");
assert!(status.success(), "status={status:?}");
assert_eq!(buf.as_slice(), b"se", "got={buf:?}");
}

#[test]
fn exec_missing_file_emits_sef() {
let (r, w) = pipe();
let bin = env!("CARGO_BIN_EXE_gunbc_execute_command_bootstrap");
let missing = "/nonexistent/gunbc_execute_command_bootstrap_probe_9f2a1c";
let mut child = spawn_bootstrap_with_sentinel_fd(bin, r, w, &[missing]);
unsafe {
libc::close(w);
}
let buf = read_pipe_to_end(r);
let status = child.wait().expect("wait");
assert_eq!(status.code(), Some(127));
assert_eq!(buf.as_slice(), b"sef", "got={buf:?}");
}
Loading