Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 6 additions & 6 deletions issues/every-program-sees-only-the-files-it-was-given.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 4 additions & 5 deletions issues/the-capability-end-state-is-twelve-answers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 11 additions & 7 deletions issues/the-kernel-is-small-interrupts-post-and-threads-wait.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -158,15 +159,18 @@ 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`). 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.
Expand Down
35 changes: 0 additions & 35 deletions kernel/pure/cwd.rs

This file was deleted.

1 change: 0 additions & 1 deletion kernel/pure/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 1 addition & 3 deletions kernel/src/loader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,6 @@ pub fn spawn<C: Commit>(
path: &str,
argv: &[&str],
commit: C,
cwd: String,
env: Vec<u8>,
backing: Arc<crate::file_backing::SharedImage>,
parent: Parent,
Expand Down Expand Up @@ -329,7 +328,6 @@ pub fn spawn<C: Commit>(
let (handles, endowments, held) = commit.commit(start::Own::new(&object, &notice))?;
let proc_data = Arc::new(Lock::new(ProcessData {
handles,
cwd,
env,
elf: ElfInfo {
elf_alloc: exe_tls_template,
Expand Down Expand Up @@ -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}"),
Expand Down
1 change: 0 additions & 1 deletion kernel/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,6 @@ const _: () = assert!(2 * MAX_LIBRARIES * core::mem::size_of::<elf::LoadedLib>()
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<u8>,

Expand Down
14 changes: 2 additions & 12 deletions kernel/src/syscall/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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::<SpawnArgs>(UserAddr::new(a1)) else { return bad_addr };
Expand All @@ -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::<usize>() + argv).saturating_sub(2 * crate::user_ptr::MAX_USER_STR as usize);
Expand All @@ -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
{
Expand Down Expand Up @@ -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 => {
Expand Down
14 changes: 2 additions & 12 deletions kernel/src/syscall/proc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,17 @@ pub(super) fn spawn_place(place: u64) -> Result<process::Parent, u64> {
.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<u8>,
image: alloc::sync::Arc<crate::file_backing::SharedImage>,
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(),
}
Expand Down Expand Up @@ -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
})
}
25 changes: 0 additions & 25 deletions sdk/abi/src/syscall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`].
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1286,22 +1277,6 @@ pub fn fstat(handle: RawHandle) -> Result<Stat, SyscallError> {
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
Expand Down
4 changes: 2 additions & 2 deletions sdk/std/sys/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
let dir = match &self.cwd {
Some(dir) if Path::new(dir).is_absolute() => Path::new(dir).to_path_buf(),
Expand Down
68 changes: 68 additions & 0 deletions sdk/toyos/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<u8>> {
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<String> {
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 {
Expand Down Expand Up @@ -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() {
Expand Down
12 changes: 6 additions & 6 deletions sdk/toyos/src/files/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,17 +195,17 @@ fn held(word: u64) -> Option<Arc<Held>> {
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<Option<String>> = 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()
}

Expand Down
Loading