From 0b66e169144c5a1122dcae6d10bc96f5d9bda2a2 Mon Sep 17 00:00:00 2001 From: japabu Date: Thu, 5 Nov 2026 08:59:11 +0100 Subject: [PATCH 1/4] The kernel keeps no working directory: a spawn states it in the child's PWD Step 9's file half left SYS_GETCWD (21): the kernel copied each spawn's starting directory out of SpawnArgs, judged it absolute and at most MAX_PATH (kernel/pure/cwd.rs), kept it in ProcessData for the process's life and answered it once to the SDK. The working directory has been the SDK's own state since #1152; the kernel only carried its first value. That value now travels in data the parent already hands the child, its environment, under POSIX's own name for it, PWD. The SDK's helper spawn, which std's Command, libc's posix_spawn and the supervisor's launcher all go through, writes PWD= in place of any PWD the environment held (toyos::files::starting_in) and refuses a directory that is not absolute, is past MAX_PATH or holds a NUL, as the kernel refused it before. The child's SDK reads its spawn-time environment once and starts there (starting_directory); a spawn that states none, such as the kernel's start of the supervisor, starts its child at the root of its view, which is where every raw-syscall spawn in the tree put it. Deleted: SYS_GETCWD, syscall::getcwd, SpawnArgs::cwd_ptr/cwd_len, the kernel's ProcessData::cwd, sys_getcwd, the spawn's cwd copy and kernel::cwd. The raw spawns in the guest tests lose their cwd fields, and abuse_spawn_argv its working-directory refusals, which are now the SDK's and held by its host tests. Co-Authored-By: Claude Opus 5.5 --- ...-capability-end-state-is-twelve-answers.md | 9 ++- kernel/pure/cwd.rs | 35 ---------- kernel/pure/lib.rs | 1 - kernel/src/loader/mod.rs | 4 +- kernel/src/process.rs | 1 - kernel/src/syscall/dispatch.rs | 14 +--- kernel/src/syscall/proc.rs | 14 +--- sdk/abi/src/syscall.rs | 25 ------- sdk/std/sys/process.rs | 4 +- sdk/toyos/src/files.rs | 68 +++++++++++++++++++ sdk/toyos/src/files/owner.rs | 12 ++-- sdk/toyos/src/spawn.rs | 17 ++--- .../rust-tests/src/bin/abuse_elf_loader.rs | 4 -- .../rust-tests/src/bin/abuse_elf_segments.rs | 4 -- .../rust-tests/src/bin/abuse_handle_table.rs | 6 -- .../rust-tests/src/bin/abuse_page_straddle.rs | 4 -- .../rust-tests/src/bin/abuse_spawn_argv.rs | 23 +------ .../guest/rust-tests/src/bin/process_tree.rs | 2 - .../src/bin/spawn_child_ends_first.rs | 2 - .../rust-tests/src/bin/spawn_image_object.rs | 3 - .../rust-tests/src/bin/spawn_lands_claimed.rs | 2 - 21 files changed, 97 insertions(+), 157 deletions(-) delete mode 100644 kernel/pure/cwd.rs diff --git a/issues/the-capability-end-state-is-twelve-answers.md b/issues/the-capability-end-state-is-twelve-answers.md index 6bd9293aeda..0b6834ec9f7 100644 --- a/issues/the-capability-end-state-is-twelve-answers.md +++ b/issues/the-capability-end-state-is-twelve-answers.md @@ -211,12 +211,11 @@ and nothing else is:** `DUP|TRANSFER|WAIT|READ|MANAGE` by type (`kernel/src/object/ops.rs:74`), and must dup-narrow and close if it wants to hold less. -The child's cwd is not implicit: `SpawnArgs` states it (`cwd_ptr`/`cwd_len`), -and the kernel starts the child there or refuses the spawn — `InvalidArgument` -for a path that is not absolute, `NotFound` for one naming no directory — with -no default to the caller's (`spawn_cwd` in `kernel/src/syscall/fs.rs`). +The child's cwd is no kernel state: the SDK's spawn states it as the child's +`PWD` (`toyos::files::starting_in`), refusing one that is not absolute, and +the child's SDK starts its working directory there (`starting_directory`). std states `Command::current_dir`, or the caller's own directory when there is -none, and `tests/guest/rust-tests/src/bin/spawn_cwd.rs` holds both routes to it. +none. Beyond that a child holds nothing, plus question 5's ambient set, which every process has. diff --git a/kernel/pure/cwd.rs b/kernel/pure/cwd.rs deleted file mode 100644 index 05b4c1fa5b7..00000000000 --- a/kernel/pure/cwd.rs +++ /dev/null @@ -1,35 +0,0 @@ -//! A spawned child's working directory, as `SYS_SPAWN` takes it from its -//! caller: absolute, and no longer than the `MAX_PATH` a program reads it back -//! into by `SYS_GETCWD`. Nothing else is judged here: the directory is a file -//! server's, which the caller's client asked, and `.` and `..` are read off -//! the text by the client that uses it. - -use toyos_abi::syscall::MAX_PATH; - -/// Whether `cwd` may start a child. -pub fn spawnable(cwd: &str) -> bool { - cwd.starts_with('/') && cwd.len() <= MAX_PATH -} - -#[cfg(test)] -mod tests { - use super::*; - use alloc::string::String; - - #[test] - fn an_absolute_directory_that_fits_starts_a_child() { - assert!(spawnable("/")); - assert!(spawnable("/home/toy/../toy/./x")); - let longest = alloc::format!("/{}", "a".repeat(MAX_PATH - 1)); - assert!(spawnable(&longest)); - } - - #[test] - fn an_empty_relative_or_overlong_directory_is_refused() { - assert!(!spawnable("")); - assert!(!spawnable("home/toy")); - assert!(!spawnable("./x")); - let past: String = alloc::format!("/{}", "a".repeat(MAX_PATH)); - assert!(!spawnable(&past)); - } -} diff --git a/kernel/pure/lib.rs b/kernel/pure/lib.rs index bc34a429782..62f6159432f 100644 --- a/kernel/pure/lib.rs +++ b/kernel/pure/lib.rs @@ -12,7 +12,6 @@ extern crate std; pub mod bootwrite; pub mod clock; pub mod cpu; -pub mod cwd; pub mod dmaguard; pub mod event; pub mod frames; diff --git a/kernel/src/loader/mod.rs b/kernel/src/loader/mod.rs index b2ebfa33ade..6d539e831cf 100644 --- a/kernel/src/loader/mod.rs +++ b/kernel/src/loader/mod.rs @@ -178,7 +178,6 @@ pub fn spawn( path: &str, argv: &[&str], commit: C, - cwd: String, env: Vec, backing: Arc, parent: Parent, @@ -329,7 +328,6 @@ pub fn spawn( let (handles, endowments, held) = commit.commit(start::Own::new(&object, ¬ice))?; let proc_data = Arc::new(Lock::new(ProcessData { handles, - cwd, env, elf: ElfInfo { elf_alloc: exe_tls_template, @@ -483,7 +481,7 @@ pub fn spawn_supervisor(images: crate::bootimage::Objects) -> Pid { ); // Built by the kernel and owing nobody anything: no table but the supervisor's own holds it. let table = SupervisorTable { job, handles, entries, labels }; - match spawn(SUPERVISOR, &[SUPERVISOR], table, String::from("/"), Vec::new(), image, Parent::Root) { + match spawn(SUPERVISOR, &[SUPERVISOR], table, Vec::new(), image, Parent::Root) { Ok((pid, ())) => pid, Err(crate::object::Refusal::Error(e)) => panic!("spawn_supervisor: failed to spawn: {e:?}"), Err(crate::object::Refusal::Handle(e)) => panic!("spawn_supervisor: {e}"), diff --git a/kernel/src/process.rs b/kernel/src/process.rs index 5cdb923da1d..aa9db74d283 100644 --- a/kernel/src/process.rs +++ b/kernel/src/process.rs @@ -296,7 +296,6 @@ const _: () = assert!(2 * MAX_LIBRARIES * core::mem::size_of::() pub struct ProcessData { /// Every kernel object this process can name; stdio is handles `0`, `1`, `2`. pub handles: HandleTable, - pub cwd: String, /// Inherited environment variables (KEY=VALUE\0KEY2=VALUE2\0...) pub env: Vec, diff --git a/kernel/src/syscall/dispatch.rs b/kernel/src/syscall/dispatch.rs index ddab00f98a7..4b3f418ca95 100644 --- a/kernel/src/syscall/dispatch.rs +++ b/kernel/src/syscall/dispatch.rs @@ -27,7 +27,6 @@ use super::device::{ sys_device_reg_read, }; use super::event::{sys_event_create, sys_event_signal, sys_event_take, sys_handle_wait}; -use super::proc::sys_getcwd; use super::handles::{sys_close, sys_handle_dup, with_object, with_object_ref}; use super::io::{ sys_null, sys_random, sys_read, sys_read_nonblock, sys_write, sys_write_nonblock, @@ -107,10 +106,6 @@ pub(crate) fn syscall_dispatch(num: u64, a1: u64, a2: u64, a3: u64, a4: u64) -> SYS_SHUTDOWN => sys_shutdown(RawHandle(a1 as u32)), SYS_REBOOT => sys_reboot(RawHandle(a1 as u32)), SYS_MACHINE_STOPS => sys_machine_stops(RawHandle(a1 as u32), a2), - SYS_GETCWD => { - let Some(mut buf) = ctx.user_bytes_mut(UserAddr::new(a1), a2) else { return bad_addr }; - sys_getcwd(&mut buf) - } SYS_PIPE => sys_pipe(), SYS_SPAWN => { let Ok(args) = ctx.copy_in::(UserAddr::new(a1)) else { return bad_addr }; @@ -137,7 +132,7 @@ pub(crate) fn syscall_dispatch(num: u64, a1: u64, a2: u64, a3: u64, a4: u64) -> // for every two bytes at most, held until the call returns; each // length is refused past its bound below, so this charges no more // than that. - let copies = [args.path_len, args.argv_len, args.cwd_len, args.labels_len, args.env_len] + let copies = [args.path_len, args.argv_len, args.labels_len, args.env_len] .map(|len| len.min(crate::user_ptr::MAX_USER_STR) as usize); let argv = crate::mm::charge::array::<&str>(copies[1] / 2 + 1); let past = (copies.iter().sum::() + argv).saturating_sub(2 * crate::user_ptr::MAX_USER_STR as usize); @@ -147,11 +142,6 @@ pub(crate) fn syscall_dispatch(num: u64, a1: u64, a2: u64, a3: u64, a4: u64) -> }; let path = match ctx.user_str(UserAddr::new(args.path_ptr), args.path_len) { Ok(s) => s, Err(e) => return e.to_u64() }; let text = match ctx.user_str(UserAddr::new(args.argv_ptr), args.argv_len) { Ok(s) => s, Err(e) => return e.to_u64() }; - let cwd = match ctx.user_str(UserAddr::new(args.cwd_ptr), args.cwd_len) { - Ok(cwd) if kernel::cwd::spawnable(&cwd) => cwd, - Ok(_) => return SyscallError::InvalidArgument.to_u64(), - Err(e) => return e.to_u64(), - }; if args.endow_count as usize > toyos_abi::syscall::MAX_SPAWN_ENDOWMENTS || args.labels_len > toyos_abi::syscall::MAX_SPAWN_LABELS_LEN as u64 { @@ -187,7 +177,7 @@ pub(crate) fn syscall_dispatch(num: u64, a1: u64, a2: u64, a3: u64, a4: u64) -> alloc::vec::Vec::new() }; let argv: alloc::vec::Vec<&str> = text.split('\0').filter(|s| !s.is_empty()).collect(); - sys_spawn(&path, &argv, pending, cwd, env, image, parent) + sys_spawn(&path, &argv, pending, env, image, parent) } SYS_PROCESS_WAIT => sys_process_wait(RawHandle(a1 as u32), a2), SYS_PROCESS_KILL => { diff --git a/kernel/src/syscall/proc.rs b/kernel/src/syscall/proc.rs index d6f306bb804..9fe384dcd5b 100644 --- a/kernel/src/syscall/proc.rs +++ b/kernel/src/syscall/proc.rs @@ -66,18 +66,17 @@ pub(super) fn spawn_place(place: u64) -> Result { .map_err(|refused| refused.refuse()) } -/// Start a program in `cwd` under `parent` and return the handle to it the spawn's commit put in the caller's table. +/// Start a program under `parent` and return the handle to it the spawn's commit put in the caller's table. pub(super) fn sys_spawn( path: &str, args: &[&str], pending: crate::loader::PendingHandles, - cwd: alloc::string::String, env: Vec, image: alloc::sync::Arc, parent: process::Parent, ) -> u64 { // Nothing to clean up: spawn's frame owns the child's resources on error. - match process::spawn(path, args, pending, cwd, env, image, parent) { + match process::spawn(path, args, pending, env, image, parent) { Ok((_, handle)) => u64::from(handle.0), Err(e) => e.refuse(), } @@ -363,12 +362,3 @@ pub(super) fn sys_account_info(ctx: &crate::user_ptr::SyscallContext, job: RawHa Err(e) => e.to_u64(), } } - -/// The initial working-directory string the parent supplied at spawn. -pub(super) fn sys_getcwd(out: &mut crate::user_ptr::UserBytesMut) -> u64 { - process::with_process_data(|data| { - let cwd = data.cwd.as_bytes(); - if cwd.len() <= out.len() { out.write_at(0, cwd); } - cwd.len() as u64 - }) -} diff --git a/sdk/abi/src/syscall.rs b/sdk/abi/src/syscall.rs index 6a44724d9a2..10f9ba136a5 100644 --- a/sdk/abi/src/syscall.rs +++ b/sdk/abi/src/syscall.rs @@ -7,7 +7,6 @@ pub const SYS_CLOSE: u64 = 10; pub const SYS_FSTAT: u64 = 14; /// What a path names, as a [`Stat`]: [`stat`]. pub const SYS_SHUTDOWN: u64 = 19; -pub const SYS_GETCWD: u64 = 21; pub const SYS_PIPE: u64 = 24; /// Start a program, endowing it exactly what the caller names. Answers a /// `Process` handle — see [`spawn`]. @@ -423,14 +422,6 @@ crate::user_safe! { /// The label blob every [`EndowEntry`]'s `label_off`/`label_len` indexes. pub labels_ptr: u64, pub labels_len: u64, - /// The child's working directory, kept as text for its - /// [`SYS_GETCWD`]: absolute and at most [`MAX_PATH`] bytes, or the - /// spawn is refused `InvalidArgument`. It names a file server's - /// directory, which the caller's client asked that server about. - /// **Always the caller's statement**: the kernel never substitutes the - /// caller's own. - pub cwd_ptr: u64, - pub cwd_len: u64, /// The program's bytes, in a memory object the caller holds — its file /// server's for the file, or one the caller read the program into: /// `image` is a handle to it carrying `MAP`, and `image_len` how many of @@ -1286,22 +1277,6 @@ pub fn fstat(handle: RawHandle) -> Result { Ok(stat) } -/// Get the initial working directory supplied by spawn. Runtime changes -/// belong to the SDK process state (`toyos::files::getcwd`). -/// -/// Returns the length the path *needs*, not the number of bytes written: -/// `n <= buf.len()` means the path is in `buf[..n]`, and `n > buf.len()` means -/// nothing was written and `n` is the size to allocate before retrying. Pass an -/// empty buffer to ask the length alone. `0` is the error return. -/// -/// The required length rather than a truncated count, because a count cannot -/// distinguish an exact fit from a silent truncation — and a caller with a fixed -/// buffer would take a valid-looking path to the wrong directory. -pub fn getcwd(buf: &mut [u8]) -> usize { - let n = syscall(SYS_GETCWD, buf.as_mut_ptr() as u64, buf.len() as u64, 0, 0); - if SyscallError::from_u64(n).is_some() { 0 } else { n as usize } -} - /// Fill `buf` with cryptographically secure random bytes. /// /// `Err` is a source that had nothing to give, and `buf` then holds no diff --git a/sdk/std/sys/process.rs b/sdk/std/sys/process.rs index e77c5949e69..7023a2e9157 100644 --- a/sdk/std/sys/process.rs +++ b/sdk/std/sys/process.rs @@ -319,8 +319,8 @@ impl Command { Err(io::Error::from(io::ErrorKind::NotFound)) } - /// The directory the child starts in, always absolute: the kernel starts a - /// child only where its spawn says, and a relative `cwd` is relative to ours. + /// The directory the child starts in, always absolute: a child starts + /// only where its spawn says, and a relative `cwd` is relative to ours. fn child_cwd(&self) -> io::Result { let dir = match &self.cwd { Some(dir) if Path::new(dir).is_absolute() => Path::new(dir).to_path_buf(), diff --git a/sdk/toyos/src/files.rs b/sdk/toyos/src/files.rs index f39a96c7920..9a81377acd3 100644 --- a/sdk/toyos/src/files.rs +++ b/sdk/toyos/src/files.rs @@ -486,6 +486,44 @@ pub fn getcwd(out: &mut [u8]) -> usize { unsafe { toyos_fs_getcwd(out.as_mut_ptr(), out.len()) } } +/// The environment variable a spawn states its child's starting directory in, +/// POSIX's: [`starting_in`] writes it, and the child's working directory +/// starts there ([`starting_directory`]). +pub const START: &str = "PWD"; + +/// `env`, `KEY=VALUE\0` repeated, stating `dir` as the child's starting +/// directory in place of any [`START`] it held. `None` for a `dir` that is not +/// absolute, is past [`fs::MAX_PATH`] or holds a NUL, which no child reads back. +pub fn starting_in(env: &[u8], dir: &str) -> Option> { + if !dir.starts_with('/') || dir.len() > fs::MAX_PATH || dir.contains('\0') { + return None; + } + let mut out = Vec::with_capacity(env.len() + START.len() + dir.len() + 2); + for entry in env.split(|&b| b == 0).filter(|e| !e.is_empty() && stated(e).is_none()) { + out.extend_from_slice(entry); + out.push(0); + } + out.extend_from_slice(START.as_bytes()); + out.push(b'='); + out.extend_from_slice(dir.as_bytes()); + out.push(0); + Some(out) +} + +/// The directory a process starts in, read from the environment its spawn +/// gave it: its [`START`], lexically clean, or `/`, its view's root, where it +/// states none. `None` for one [`starting_in`] would not have written. +pub fn starting_directory(env: &[u8]) -> Option { + let Some(dir) = env.split(|&b| b == 0).find_map(stated) else { return Some(String::from("/")) }; + let dir = core::str::from_utf8(dir).ok().filter(|d| d.starts_with('/') && d.len() <= fs::MAX_PATH)?; + Some(absolute("/", dir)) +} + +/// The value of an environment entry naming [`START`]. +fn stated(entry: &[u8]) -> Option<&[u8]> { + entry.strip_prefix(START.as_bytes())?.strip_prefix(b"=") +} + /// `path`, absolute against `cwd` and without `.` or `..`, which are read off /// the text (`issues/a-working-directory-path-reads-its-dot-dot-off-the-text.md`). pub fn absolute(cwd: &str, path: &str) -> String { @@ -522,6 +560,36 @@ mod tests { assert_eq!(absolute("/", "../../.."), "/"); } + /// What a parent states is what its child starts in, whatever the + /// environment it was given already said. + #[test] + fn a_child_starts_where_its_spawn_says_and_nowhere_its_environment_said() { + let given = b"HOME=/home/toy\0PWD=/elsewhere\0PWDX=/x\0TERM=toyos\0"; + let env = starting_in(given, "/home/toy/Games").expect("an absolute directory"); + assert_eq!(starting_directory(&env).as_deref(), Some("/home/toy/Games")); + assert_eq!(env, b"HOME=/home/toy\0PWDX=/x\0TERM=toyos\0PWD=/home/toy/Games\0"); + assert_eq!(starting_directory(&starting_in(b"", "/").unwrap()).as_deref(), Some("/")); + assert_eq!(starting_directory(b"PWD=/a/./b/../c\0").as_deref(), Some("/a/c")); + } + + #[test] + fn a_spawn_stating_no_directory_starts_its_child_at_the_root() { + assert_eq!(starting_directory(b"").as_deref(), Some("/")); + assert_eq!(starting_directory(b"PWDX=/x\0HOME=/home\0").as_deref(), Some("/")); + } + + #[test] + fn a_directory_no_child_can_read_back_is_never_stated() { + let longest = alloc::format!("/{}", "a".repeat(fs::MAX_PATH - 1)); + assert!(starting_in(b"", &longest).is_some()); + for dir in ["", "home/toy", "./x", "/a\0b", &alloc::format!("/{}", "a".repeat(fs::MAX_PATH))] { + assert_eq!(starting_in(b"", dir), None, "{dir:?}"); + } + for env in [&b"PWD=home\0"[..], b"PWD=\0", b"PWD=/\xff\0"] { + assert_eq!(starting_directory(env), None, "{env:?}"); + } + } + /// The path boundary refuses empty, non-UTF-8 and oversized names. #[test] fn the_empty_path_names_nothing() { diff --git a/sdk/toyos/src/files/owner.rs b/sdk/toyos/src/files/owner.rs index a03981411cf..59736282758 100644 --- a/sdk/toyos/src/files/owner.rs +++ b/sdk/toyos/src/files/owner.rs @@ -195,17 +195,17 @@ fn held(word: u64) -> Option> { OPEN.lock().get(usize::try_from(word).ok()?)?.clone() } -/// Process-owned working directory, shared by every SDK copy through this owner. -/// The kernel supplies only the spawn's initial value. +/// Process-owned working directory, shared by every SDK copy through this owner, +/// starting where the spawn's environment says ([`super::starting_directory`]). static CWD: Lock> = Lock::new(None); fn cwd() -> String { let mut cwd = CWD.lock(); cwd.get_or_insert_with(|| { - let mut buf = alloc::vec![0u8; syscall::MAX_PATH]; - let n = syscall::getcwd(&mut buf); - assert!(n > 0 && n <= buf.len(), "spawn supplied an invalid working directory"); - String::from_utf8(buf[..n].to_vec()).expect("spawn supplied a non-UTF-8 working directory") + let mut env = alloc::vec![0; syscall::get_env(&mut [])]; + let n = syscall::get_env(&mut env); + assert_eq!(n, env.len(), "the spawn's environment changed size"); + super::starting_directory(&env).expect("the spawn stated a starting directory that is not absolute UTF-8") }).clone() } diff --git a/sdk/toyos/src/spawn.rs b/sdk/toyos/src/spawn.rs index 57c364c6d30..f5e4430798f 100644 --- a/sdk/toyos/src/spawn.rs +++ b/sdk/toyos/src/spawn.rs @@ -5,9 +5,9 @@ //! answers is the one way to start that kind. //! //! **A helper inherits.** It holds this process's namespace under `svc`, its -//! environment as given, and exactly the descriptors and endowments its spawn -//! names; never this process's launcher, which only an endowment the caller -//! names hands on. +//! environment as given but for its starting directory, and exactly the +//! descriptors and endowments its spawn names; never this process's launcher, +//! which only an endowment the caller names hands on. //! //! **An independent launch runs its row.** The launcher starts the program a //! manifest row declares, holding that row's authority and the connectors @@ -59,7 +59,8 @@ pub struct Spawn<'a> { pub argv: &'a [u8], /// `KEY=VALUE\0` repeated: the child's environment. pub env: &'a [u8], - /// Absolute: the kernel starts a child only where its spawn says. + /// Absolute: the child starts only where its spawn says, which a helper + /// states in its environment ([`crate::files::starting_in`]). pub cwd: &'a str, /// `(child descriptor, caller's handle, its kind)`, each a number once: /// the child starts with these and no other descriptors. The caller keeps @@ -200,6 +201,8 @@ impl Helper<'_> { pub fn spawn(self, image: Option<&Image>) -> Result { let s = self.0; let path = image_and_name(s.program, s.image).0; + let env = crate::files::starting_in(s.env, s.cwd) + .ok_or(Refused::Invalid("a working directory that is not absolute, is too long or holds a NUL"))?; let names_svc = s.endow.iter().any(|(label, _)| *label == SVC_LABEL); if s.endow.len() + s.fds.len() + usize::from(!names_svc) > MAX_SPAWN_ENDOWMENTS { return Err(Refused::Invalid("more endowments and descriptors than a spawn carries")); @@ -258,14 +261,12 @@ impl Helper<'_> { path_len: path.len() as u64, argv_ptr: s.argv.as_ptr() as u64, argv_len: s.argv.len() as u64, - env_ptr: s.env.as_ptr() as u64, - env_len: s.env.len() as u64, + env_ptr: env.as_ptr() as u64, + env_len: env.len() as u64, endow_ptr: entries.as_ptr() as u64, endow_count: count as u64, labels_ptr: labels.as_ptr() as u64, labels_len: used as u64, - cwd_ptr: s.cwd.as_ptr() as u64, - cwd_len: s.cwd.len() as u64, image, image_len, place: match s.parent { diff --git a/tests/guest/rust-tests/src/bin/abuse_elf_loader.rs b/tests/guest/rust-tests/src/bin/abuse_elf_loader.rs index d92342729cd..39903ab4170 100644 --- a/tests/guest/rust-tests/src/bin/abuse_elf_loader.rs +++ b/tests/guest/rust-tests/src/bin/abuse_elf_loader.rs @@ -24,8 +24,6 @@ use toyos_abi::syscall::{self, SpawnArgs, SyscallError}; use toyos_abi::RawHandle; use toyos_abi::end::End; -/// Where the child starts: `SpawnArgs` names a working directory or the spawn is refused. -const CWD: &str = "/"; /// Where each case's file is written. A spawn reads it back into a memory /// object and hands the kernel that, as every spawn of a served program does. @@ -258,8 +256,6 @@ fn spawn_argv(path: &str, argv: &str) -> Result { endow_count: 0, labels_ptr: 0, labels_len: 0, - cwd_ptr: CWD.as_ptr() as u64, - cwd_len: CWD.len() as u64, image, image_len, place: u64::from(toyos_abi::HANDLE_INVALID.0), diff --git a/tests/guest/rust-tests/src/bin/abuse_elf_segments.rs b/tests/guest/rust-tests/src/bin/abuse_elf_segments.rs index ee9b0affb19..b9c1ea278c7 100644 --- a/tests/guest/rust-tests/src/bin/abuse_elf_segments.rs +++ b/tests/guest/rust-tests/src/bin/abuse_elf_segments.rs @@ -17,8 +17,6 @@ use std::fs; use toyos_abi::syscall::{self, SpawnArgs, SyscallError}; -/// Where the child starts: `SpawnArgs` names a working directory or the spawn is refused. -const CWD: &str = "/"; /// Kernel-served, so a path spawn reaches the kernel's own open; every refusal /// is asked again with the same bytes handed over as an image. @@ -152,8 +150,6 @@ fn spawn_as(path: &str, image: &[u8]) -> SyscallError { endow_count: 0, labels_ptr: 0, labels_len: 0, - cwd_ptr: CWD.as_ptr() as u64, - cwd_len: CWD.len() as u64, image: toyos::AsHandle::as_handle(&object).raw().0 as u64, image_len: image.len() as u64, place: u64::from(toyos_abi::HANDLE_INVALID.0), diff --git a/tests/guest/rust-tests/src/bin/abuse_handle_table.rs b/tests/guest/rust-tests/src/bin/abuse_handle_table.rs index f7f85f7b329..9b84e6a9cfc 100644 --- a/tests/guest/rust-tests/src/bin/abuse_handle_table.rs +++ b/tests/guest/rust-tests/src/bin/abuse_handle_table.rs @@ -41,8 +41,6 @@ const SELF: &str = "/system/bin/test_rs_abuse_handle_table"; /// The role a spawned copy of this binary takes: it exits at once. const CHILD: &str = "endowed"; -/// Where the child starts: `SpawnArgs` names a working directory or the spawn is refused. -const CWD: &str = "/"; /// Mirrors `RawHandle::MAX_SLOTS`. A cap that moves should fail this test /// loudly. @@ -90,8 +88,6 @@ fn main() { endow_count, labels_ptr: (region as u64) + (REGION / 8) as u64, labels_len: LABELS.len() as u64, - cwd_ptr: CWD.as_ptr() as u64, - cwd_len: CWD.len() as u64, image, image_len, place: u64::from(toyos_abi::HANDLE_INVALID.0), @@ -210,8 +206,6 @@ fn spawn_endowed(entries: &[EndowEntry], labels: &[u8]) -> Result(); @@ -103,8 +101,6 @@ fn main() { endow_count: 0, labels_ptr: 0, labels_len: 0, - cwd_ptr: CWD.as_ptr() as u64, - cwd_len: CWD.len() as u64, image, image_len, place: u64::from(toyos_abi::HANDLE_INVALID.0), diff --git a/tests/guest/rust-tests/src/bin/abuse_spawn_argv.rs b/tests/guest/rust-tests/src/bin/abuse_spawn_argv.rs index 08cf8e3ef9e..d53243c097e 100644 --- a/tests/guest/rust-tests/src/bin/abuse_spawn_argv.rs +++ b/tests/guest/rust-tests/src/bin/abuse_spawn_argv.rs @@ -1,12 +1,10 @@ -//! The kernel must survive a process that hands `SYS_SPAWN` absurd path, argv, -//! env or working directory, and refuse each at its boundary. +//! The kernel must survive a process that hands `SYS_SPAWN` absurd path, argv +//! or env, and refuse each at its boundary. //! //! `path_len`, `argv_len` and `env_len` are raw `u64` fields of a user-supplied //! `SpawnArgs`. The path is copied, the argv blob is split into a `Vec<&str>` //! (16 bytes per token) and the env blob is copied with `to_vec()`, so each one //! sizes a kernel allocation. An argv with no non-empty token also has no `argv[0]`. -//! A working directory that is empty, relative or longer than `MAX_PATH` would -//! reach a child that cannot read it back. //! //! Every case carries a real image, and the same arguments with an honest argv //! start a child, so each refusal is its own field's. @@ -17,10 +15,7 @@ mod image; use std::process::Command; use toyos::process::Process; -use toyos_abi::syscall::{self, VmAt, VmProt, SpawnArgs, SyscallError, MAX_PATH}; - -/// Where the child starts. -const CWD: &str = "/"; +use toyos_abi::syscall::{self, VmAt, VmProt, SpawnArgs, SyscallError}; /// The program every case hands over, whatever its argv names. const PROGRAM: &str = "/system/bin/echo"; @@ -56,8 +51,6 @@ fn main() { endow_count: 0, labels_ptr: 0, labels_len: 0, - cwd_ptr: CWD.as_ptr() as u64, - cwd_len: CWD.len() as u64, image, image_len, place: u64::from(toyos_abi::HANDLE_INVALID.0), @@ -91,16 +84,6 @@ fn main() { // SAFETY: the handle `SYS_SPAWN` just answered, held nowhere else. unsafe { Process::from_raw(child) }.wait().expect("wait for the honest child"); - let relative = "tmp"; - let overlong = format!("/{}", "a".repeat(MAX_PATH)); - for (what, cwd) in [("an empty", ""), ("a relative", relative), ("an overlong", overlong.as_str())] { - let err = unsafe { - syscall::spawn(&SpawnArgs { argv_len: 2, cwd_ptr: cwd.as_ptr() as u64, cwd_len: cwd.len() as u64, ..base }) - } - .expect_err("a working directory a child cannot read back must be refused"); - assert_eq!(err, SyscallError::InvalidArgument, "wrong error for {what} working directory"); - } - // No non-empty token: there is no argv[0] to load. let err = unsafe { syscall::spawn(&base) }.expect_err("an empty argv must be rejected"); assert_eq!(err, SyscallError::InvalidArgument, "wrong error for empty argv"); diff --git a/tests/guest/rust-tests/src/bin/process_tree.rs b/tests/guest/rust-tests/src/bin/process_tree.rs index 195e0fb2934..29d29d92b2c 100644 --- a/tests/guest/rust-tests/src/bin/process_tree.rs +++ b/tests/guest/rust-tests/src/bin/process_tree.rs @@ -245,8 +245,6 @@ fn spawn_under(place: RawHandle) -> Result { endow_count: 0, labels_ptr: 0, labels_len: 0, - cwd_ptr: "/".as_ptr() as u64, - cwd_len: 1, image, image_len, place: u64::from(place.0), diff --git a/tests/guest/rust-tests/src/bin/spawn_child_ends_first.rs b/tests/guest/rust-tests/src/bin/spawn_child_ends_first.rs index 3c26b0d3ad8..005736e417a 100644 --- a/tests/guest/rust-tests/src/bin/spawn_child_ends_first.rs +++ b/tests/guest/rust-tests/src/bin/spawn_child_ends_first.rs @@ -112,8 +112,6 @@ fn spawn(own: &Image, role: &str, stdout: Option) -> Result (SharedMemory, u64) { @@ -42,8 +41,6 @@ fn spawn(image: RawHandle, len: u64) -> Result { endow_count: 0, labels_ptr: 0, labels_len: 0, - cwd_ptr: CWD.as_ptr() as u64, - cwd_len: CWD.len() as u64, image: image.0 as u64, image_len: len, place: u64::from(toyos_abi::HANDLE_INVALID.0), diff --git a/tests/guest/rust-tests/src/bin/spawn_lands_claimed.rs b/tests/guest/rust-tests/src/bin/spawn_lands_claimed.rs index 0312a5042c7..13c771280bd 100644 --- a/tests/guest/rust-tests/src/bin/spawn_lands_claimed.rs +++ b/tests/guest/rust-tests/src/bin/spawn_lands_claimed.rs @@ -93,8 +93,6 @@ fn spawn_under(place: RawHandle) -> Result { endow_count: 0, labels_ptr: 0, labels_len: 0, - cwd_ptr: "/".as_ptr() as u64, - cwd_len: 1, image, image_len, place: u64::from(place.0), From 926544f8206c1546c35ec899f61fe93464256e25 Mon Sep 17 00:00:00 2001 From: japabu Date: Thu, 5 Nov 2026 09:40:01 +0100 Subject: [PATCH 2/4] std_fs: a child starts where its spawn says, not where its PWD said A check that a child std spawns with current_dir starts there, through the SDK's PWD and the child's SDK reading it: the binary runs itself in a fresh /tmp directory under an inherited PWD naming another, and the child prints its working directory. std_fs is a shared member, so this runs on metal (testcases), not on a filtered QEMU run. Co-Authored-By: Claude Opus 5.5 --- tests/guest/rust-tests/src/bin/std_fs.rs | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/guest/rust-tests/src/bin/std_fs.rs b/tests/guest/rust-tests/src/bin/std_fs.rs index 4570e715ef0..823d59a0076 100644 --- a/tests/guest/rust-tests/src/bin/std_fs.rs +++ b/tests/guest/rust-tests/src/bin/std_fs.rs @@ -5,6 +5,10 @@ use std::os::toyos::io::{AsRawFd, FromRawFd}; use std::process::{Command, Stdio}; fn main() { + if std::env::args().nth(1).as_deref() == Some(CWD_ARG) { + println!("{}", std::env::current_dir().expect("a working directory").display()); + return; + } let entries: Vec<_> = fs::read_dir("/system/bin") .expect("should be able to read /system/bin") .filter_map(|e| e.ok()) @@ -25,10 +29,31 @@ fn main() { file_types(); create_new_is_exclusive_on_tmp(); the_empty_path_names_nothing(); + a_child_starts_where_its_spawn_says(); println!("all fs tests passed"); } +/// What this binary, run with it, prints: its working directory. +const CWD_ARG: &str = "cwd"; + +/// A child starts in the directory its spawn names, and not in one the +/// environment it inherits names. +fn a_child_starts_where_its_spawn_says() { + let dir = "/tmp/std_fs_child_start"; + let _ = fs::remove_dir(dir); + fs::create_dir(dir).expect("make the child's directory"); + let ran = Command::new("/system/bin/test_rs_std_fs") + .arg(CWD_ARG) + .current_dir(dir) + .env("PWD", "/system") + .output() + .expect("spawn this binary"); + assert!(ran.status.success(), "the child exited {:?}", ran.status); + assert_eq!(String::from_utf8_lossy(&ran.stdout), format!("{dir}\n"), "where the child started"); + fs::remove_dir(dir).expect("remove the child's directory"); +} + /// The empty path names nothing, wherever the working directory is served: /// an open, a stat and a removal of it are `NotFound`, and the empty working /// directory a removal would take is still there. From 13e944b3beca957df4b0da38df256b8224d4c3d3 Mon Sep 17 00:00:00 2001 From: japabu Date: Thu, 5 Nov 2026 09:07:12 +0100 Subject: [PATCH 3/4] issues: step 9's file half leaves only its windows #1182 removes SYS_GETCWD, so the small-kernel track's first item is the windows that half owes, beside its measured lines, and the isolation track's stage 1 no longer lists the kernel's working directory as left. Co-Authored-By: Claude Opus 5.5 --- ...ry-program-sees-only-the-files-it-was-given.md | 12 ++++++------ ...l-is-small-interrupts-post-and-threads-wait.md | 15 ++++++++------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/issues/every-program-sees-only-the-files-it-was-given.md b/issues/every-program-sees-only-the-files-it-was-given.md index c7ef2755ed0..56601ad14af 100644 --- a/issues/every-program-sees-only-the-files-it-was-given.md +++ b/issues/every-program-sees-only-the-files-it-was-given.md @@ -92,12 +92,12 @@ nameable by every program and make confused-deputy bugs structural. on the file server's. A process given an empty view names nothing. **Done** (#1181; the track's step 8): fileserver's `resolve` suite, red with the grant's root ignored, and `toyos::files`' - `an_empty_view_names_nothing_but_an_empty_root`. Left of the design above: - a spawn still states its child's working directory as text the kernel - keeps for `SYS_GETCWD`, a later step of - `issues/the-kernel-is-small-interrupts-post-and-threads-wait.md`; and a - row the image declares is still minted the whole tree but `/state`, - which stage 2 narrows to the files its row declares. + `an_empty_view_names_nothing_but_an_empty_root`. The kernel keeps no + working directory (#1182): a spawn states its child's in the child's + `PWD`, a name the child resolves in its own view, so it reaches nothing + that view does not hold. Left of the design above: a row the image + declares is still minted the whole tree but `/state`, which stage 2 + narrows to the files its row declares. 2. **Every row declares its files.** `system.toml` states each program's view; the build refuses a row that names a path no role provides. The shell and terminal get the session's view, doom its `/apps` directory, and daemons diff --git a/issues/the-kernel-is-small-interrupts-post-and-threads-wait.md b/issues/the-kernel-is-small-interrupts-post-and-threads-wait.md index fbabd598d66..409301bfd29 100644 --- a/issues/the-kernel-is-small-interrupts-post-and-threads-wait.md +++ b/issues/the-kernel-is-small-interrupts-post-and-threads-wait.md @@ -16,8 +16,9 @@ kernel's part of a restart, and named module tests hold each program's ## What is left, in order -1. **What step 9's file half left** (stage 4): `SYS_GETCWD`, and the - measurement that half owes. +1. **What step 9's file half left** (stage 4): its windows, by stage 6 + step 2's rule. Its lines are measured: `kernel/src` held 230 files and + 59,012 lines before #1152 and 223 and 56,800 after #1182. 2. **P1 of the Wi-Fi track** (`issues/there-is-no-wifi.md`): a BAR stays where firmware put it, handed over in 4 KiB pages with its MSI-X table's page, under the owner's Q2 ruling. The orchestrator ruled on #900 that @@ -158,15 +159,15 @@ Beside that order, each waiting on something outside it: an empty `/` (`toyos::files`' `an_empty_view_names_nothing_but_an_empty_root`). Not this step's: a declared row's own view, which still holds the whole tree but - `/state` (the isolation track's stage 2), and `SYS_GETCWD` (step 9's - file half, item 1 above). + `/state` (the isolation track's stage 2). 9. **Delete the kernel storage stack.** **Partly done** (#536). Two halves are left, and they land apart: - **The file half**: the VFS, tmpfs (`tmpfs.rs`, `fs_rename.rs`), the page cache (`file_cache.rs`) and the file syscalls. **Done but for - two items** (#1152): `SYS_GETCWD` (21) stays, since the kernel - records a spawn's starting directory, which the SDK reads once - (`toyos::files`); and the measurement below is owed. `/tmp` is the + its windows** (#1152, #1182; item 1 above). The kernel keeps no + working directory: a spawn states its child's in the child's `PWD`, + which the SDK writes and the child's SDK starts from + (`toyos::files::starting_in`). `/tmp` is the MEMORY file server's, one for the machine, of which each installed package's `/tmp` is its own directory (#1181); per session, as the owner ruled ("Per session", 2026-10-03), is the isolation track's stage 3. From 0e98591f74dbea25999df797157a7d7d2526527e Mon Sep 17 00:00:00 2001 From: japabu Date: Thu, 5 Nov 2026 09:40:01 +0100 Subject: [PATCH 4/4] review r1 of #1182: no stale sys_getcwd contract, and the env named as kernel-held query_modules_size's header pointed its contract at sys_getcwd and sys_readdir, neither of which exists now; the next line states the contract itself. The small-kernel record names the environment (ProcessData::env, SYS_GET_ENV) as userland data the kernel still holds, with a startup memory object as its likely exit, so "the kernel keeps no working directory" is not read as "the kernel holds no path text". Co-Authored-By: Claude Opus 5.5 --- .../the-kernel-is-small-interrupts-post-and-threads-wait.md | 5 ++++- tests/guest/rust-tests/src/bin/query_modules_size.rs | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/issues/the-kernel-is-small-interrupts-post-and-threads-wait.md b/issues/the-kernel-is-small-interrupts-post-and-threads-wait.md index 409301bfd29..5bb38420b7d 100644 --- a/issues/the-kernel-is-small-interrupts-post-and-threads-wait.md +++ b/issues/the-kernel-is-small-interrupts-post-and-threads-wait.md @@ -167,7 +167,10 @@ Beside that order, each waiting on something outside it: its windows** (#1152, #1182; item 1 above). The kernel keeps no working directory: a spawn states its child's in the child's `PWD`, which the SDK writes and the child's SDK starts from - (`toyos::files::starting_in`). `/tmp` is the + (`toyos::files::starting_in`). The kernel still holds userland data + it never reads, path text among it: the environment + (`ProcessData::env`, answered by `SYS_GET_ENV`), whose likely exit + is a startup memory object the parent fills for the child. `/tmp` is the MEMORY file server's, one for the machine, of which each installed package's `/tmp` is its own directory (#1181); per session, as the owner ruled ("Per session", 2026-10-03), is the isolation track's stage 3. diff --git a/tests/guest/rust-tests/src/bin/query_modules_size.rs b/tests/guest/rust-tests/src/bin/query_modules_size.rs index d2dbf276f73..a8dc4a85e0a 100644 --- a/tests/guest/rust-tests/src/bin/query_modules_size.rs +++ b/tests/guest/rust-tests/src/bin/query_modules_size.rs @@ -6,8 +6,8 @@ //! returned a bare one, and a caller had no way to size a retry and no way to //! learn that was why it failed. A doc comment is a claim to verify. //! -//! The contract now is `sys_getcwd`'s and `sys_readdir`'s: the return is the -//! length in bytes either way, and nothing is written unless all of it fits. +//! The contract now: the return is the length in bytes either way, and +//! nothing is written unless all of it fits. use core::mem::size_of;