From a4025ceb8ad0c46ffb66476268cf15b9ce7be025 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 18:38:37 +0000 Subject: [PATCH 1/2] xtask: signal drmtest by its pid, not job %2 The shell session started drmtest in the background and then sent it SIGUSR1 as job %2, assuming the earlier USB mouse step's background job still held %1. When that job had already finished and been reported, the shell numbered drmtest %1 and the step failed with "kill: %2: no such job". Use $! (the last background pid) for the three signals. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rq8xUwPzGmf9wALtX2i7uM --- xtask/src/main.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 1878597..d52ddcf 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -864,7 +864,7 @@ fn shell_session(img: &Path) -> Result<(), String> { println!("xtask: shell session: `{cmd}` -> DRMTEST-SHOWN"); // The centre column is the first of the right half. check_screen("SETCRTC", &["red", "blue", "blue"], &mut child)?; - let cmd = "kill -USR1 %2"; + let cmd = "kill -USR1 $!"; send(cmd); let Some(end) = wait_for("DRMTEST-CURSOR", at, 60) else { return fail( @@ -883,7 +883,7 @@ fn shell_session(img: &Path) -> Result<(), String> { // The cursor is an opaque red 64x64 image centred on the screen, so // only the middle sample point is covered. check_screen("CURSOR", &["green", "red", "green"], &mut child)?; - let cmd = "kill -USR1 %2"; + let cmd = "kill -USR1 $!"; send(cmd); let Some(end) = wait_for("DRMTEST-OK ", at, 60) else { return fail(format!("`{cmd}` did not print `DRMTEST-OK`"), &mut child); @@ -901,7 +901,7 @@ fn shell_session(img: &Path) -> Result<(), String> { .collect(); println!("xtask: shell session: `{cmd}` -> DRMTEST-OK {size}"); check_screen("cursor hidden", &["green", "green", "green"], &mut child)?; - let cmd = "kill %2; wait; echo KILLED-$((40 + 2))"; + let cmd = "kill $!; wait; echo KILLED-$((40 + 2))"; send(cmd); if wait_for("KILLED-42", at, 60).is_none() { return fail(format!("`{cmd}` did not print `KILLED-42`"), &mut child); From d54882fe1ea7e7bb13bce3f9b73425b01bb0f2ba Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 18:38:48 +0000 Subject: [PATCH 2/2] UTS and IPC namespaces, System V shared memory CLONE_NEWUTS and CLONE_NEWIPC for clone and unshare. A UTS namespace holds its own host and domain names: uname, sethostname (170) and setdomainname (171) use the caller's, and changing them needs privilege over the user namespace that owns it (EPERM before EINVAL, as on Linux). An IPC namespace holds its own System V objects. Both are owned by the caller's user namespace (the new one with CLONE_NEWUSER); CLONE_NEWIPC|CLONE_SYSVSEM is EINVAL. /proc//ns/{uts,ipc} name them. System V shared memory (ipc.rs, syscall/ipc.rs): shmget (29), shmat (30), shmctl (31) and shmdt (67). A segment is an unnamed tmpfs file mapped MAP_SHARED, so fork shares it; the attach count is counted from the live address spaces, so fork, munmap and exit change it as on Linux. IPC_RMID frees the key at once and the memory after the last detach. shmat handles SHM_RND, SHM_REMAP, SHM_RDONLY and SHM_EXEC; shmctl IPC_STAT, IPC_SET, IPC_RMID, IPC_INFO, SHM_INFO, SHM_STAT(_ANY) and SHM_LOCK/UNLOCK. Ids are allocated as Linux 6.x does (cyclic indexes, a sequence number that advances when an index is reused). /proc/sys/kernel gains hostname and domainname (per UTS namespace), osrelease, ostype and shmmax/shmall/shmmni; /proc/sysvipc/shm lists segments in Linux's columns. userland/tests/sysvipc.c covers both namespaces and shared memory; it prints the same on Linux, as root or as nobody, and on SegOS. Three kernel tests cover shmget's rules, id allocation and removal, and the UTS name rules. The shell session runs BusyBox's `unshare -r -u` with `hostname`, and attaches one segment twice through glibc from Python's ctypes. All 36 kernel tests and the full QEMU session pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rq8xUwPzGmf9wALtX2i7uM --- README.md | 3 +- docs/plan.md | 35 ++- kernel/src/fs/procfs.rs | 123 ++++++++ kernel/src/ipc.rs | 519 ++++++++++++++++++++++++++++++++ kernel/src/ktest.rs | 9 + kernel/src/main.rs | 1 + kernel/src/proc/mod.rs | 40 ++- kernel/src/proc/ns.rs | 120 +++++++- kernel/src/syscall/info.rs | 28 +- kernel/src/syscall/ipc.rs | 248 +++++++++++++++ kernel/src/syscall/mem.rs | 2 +- kernel/src/syscall/mod.rs | 7 + kernel/src/syscall/process.rs | 17 +- userland/tests/sysvipc.c | 386 ++++++++++++++++++++++++ userland/tests/sysvipc.expected | 94 ++++++ xtask/src/main.rs | 15 +- 16 files changed, 1626 insertions(+), 21 deletions(-) create mode 100644 kernel/src/ipc.rs create mode 100644 kernel/src/syscall/ipc.rs create mode 100644 userland/tests/sysvipc.c create mode 100644 userland/tests/sysvipc.expected diff --git a/README.md b/README.md index 0c2e130..bb3a746 100644 --- a/README.md +++ b/README.md @@ -306,7 +306,8 @@ musl-gcc -static -O2 -o /tmp/t userland/tests/NAME.c && /tmp/t > userland/tests/ | `bootinfo/` | the boot protocol: what segboot hands the kernel | | `kernel/src/hal/` | x86-64: instructions, serial, GDT/TSS, IDT and the trap path, `syscall` entry, ACPI tables (CPUs, I/O APIC, power off), local APIC and timer, I/O APIC, RTC, per-CPU data, starting CPUs | | `kernel/src/mm/` | frame allocator with reference counts, page tables, kernel heap allocator, process address spaces with copy-on-write (`vm.rs`) | -| `kernel/src/proc/` | processes: `fork`/`clone`, `execve` (with `#!`), exit and `wait4`, process groups and sessions, signals, the ELF loader, user faults | +| `kernel/src/proc/` | processes: `fork`/`clone`, `execve` (with `#!`), exit and `wait4`, process groups and sessions, signals, the ELF loader, user faults, namespaces (user, PID, mount, network, UTS, IPC) | +| `kernel/src/ipc.rs` | System V shared memory segments, one table per IPC namespace | | `kernel/src/syscall/` | the Linux system calls, by Linux number | | `kernel/src/fs/` | the VFS with symbolic links, tmpfs, `/dev` devices, pipes, `/proc`, the initramfs (cpio) unpacker | | `kernel/src/tty.rs` | the console terminal: line discipline, termios, job control | diff --git a/docs/plan.md b/docs/plan.md index e2a789e..7de4abc 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -422,9 +422,10 @@ The demo: Firefox and Chromium run on the Wayland desktop. and real AMD/Intel GPUs. Local QEMU has no virtio-gpu device, so only the command layouts are covered by kernel tests; the device path is not exercised here. -2. **What browsers need**: seccomp-BPF, `inotify`, user, PID, network and - mount namespaces, `/dev/shm`, fontconfig, a D-Bus session bus, `chroot` - and CLONE_FS (all done, below). +2. **What browsers need**: seccomp-BPF, `inotify`, user, PID, network, + mount, UTS and IPC namespaces, `/dev/shm` and System V shared memory, + fontconfig, a D-Bus session bus, `chroot` and CLONE_FS (all done, + below). *Done so far.* Firefox renders a page headless (a screenshot), and the shell session has a step that runs it on weston (it runs where @@ -447,9 +448,27 @@ The demo: Firefox and Chromium run on the Wayland desktop. namespaces (CLONE_NEWNS with CLONE_FS or CLONE_THREAD is EINVAL, as on Linux); `/proc//ns/mnt`, the caller's `/proc/mounts` and `/proc//mounts` show the right table. `tests/namespaces` mounts a - tmpfs in one namespace and checks it is invisible in the parent's. Not - yet: UTS, IPC and cgroup namespaces (EINVAL), `setns`, `/proc` mounted - per PID namespace, capabilities (everything is root). **`/dev/shm`**, **fontconfig** + tmpfs in one namespace and checks it is invisible in the parent's. + **UTS and IPC namespaces** (CLONE_NEWUTS, CLONE_NEWIPC): a new UTS + namespace starts with its parent's names; `sethostname` and + `setdomainname` change only it (`uname`, `/proc/sys/kernel/hostname` + and `domainname`) and need privilege over the user namespace that owns + it, as on Linux. A new IPC namespace has its own, empty set of + System V objects; `/proc//ns/{uts,ipc}` name them. **System V + shared memory** (`ipc.rs`, `syscall/ipc.rs`): `shmget` (keys, + IPC_PRIVATE, IPC_CREAT/IPC_EXCL), `shmat` (anywhere or at an address, + SHM_RND, SHM_REMAP, SHM_RDONLY), `shmdt` and `shmctl` (IPC_STAT, + IPC_SET, IPC_RMID, IPC_INFO, SHM_INFO, SHM_STAT, SHM_LOCK). A + segment is an unnamed tmpfs file mapped shared, so `fork` shares it; + the attach count is counted from the live address spaces, so `fork`, + `munmap` and exit change it as on Linux; IPC_RMID frees the key at + once and the memory after the last detach. Ids are allocated as Linux + 6.x does (cyclic indexes, a sequence number that moves on when an + index is reused); `/proc/sysvipc/shm` and `/proc/sys/kernel/shm*` + are there. `userland/tests/sysvipc.c` prints the same on Linux, as + root or not, and on SegOS. Not yet: cgroup namespaces (EINVAL), + `setns`, `/proc` mounted per PID namespace, SysV semaphores and + message queues, capabilities (everything is root). **`/dev/shm`**, **fontconfig** and **D-Bus**: the shell session creates POSIX shared memory from Python, `fc-match` finds DejaVu Sans, and `dbus-run-session` starts Ubuntu's `dbus-daemon`, which answers `dbus-send`. **Network @@ -475,8 +494,8 @@ The demo: Firefox and Chromium run on the Wayland desktop. poll). Ubuntu's `aplay` plays through libasound unchanged; QEMU records the card's output and `cargo xtask test` measures the 440 Hz tone in it. Not yet: capture, mmap transfers, mixer controls, - interrupts (the position is followed by a kernel thread), dmix (no - SysV shared memory). + interrupts (the position is followed by a kernel thread), dmix (SysV + shared memory is there now; its semaphores are not). 4. **USB** (`drivers/xhci.rs`, done): the xHCI controller is taken from the firmware, reset, and given a device context array, scratchpads, a command ring and an event ring; connected root ports are reset, their diff --git a/kernel/src/fs/procfs.rs b/kernel/src/fs/procfs.rs index a7e5ba2..e256fc2 100644 --- a/kernel/src/fs/procfs.rs +++ b/kernel/src/fs/procfs.rs @@ -180,6 +180,14 @@ fn ns_dir(pid: u32, parent: &Arc) -> Arc { "user:[{}]", p.user_ns.lock().ino ))), + entry("uts", 0x2a, |p| Ok(format!( + "uts:[{}]", + p.uts_ns.lock().ino + ))), + entry("ipc", 0x2b, |p| Ok(format!( + "ipc:[{}]", + p.ipc_ns.lock().ino + ))), ] }) } @@ -352,6 +360,8 @@ pub fn root(root: &Arc) -> Arc { ] }) ), + ("sys".into(), sys_dir(me)), + ("sysvipc".into(), sysvipc_dir(me)), ]; for p in proc::all() { let pid = p.pid; @@ -361,6 +371,119 @@ pub fn root(root: &Arc) -> Arc { }) } +/// `/proc/sys`: the `kernel` settings programs read (host and domain +/// names, release, SysV shared memory limits). +fn sys_dir(proc_dir: &Arc) -> Arc { + GenDir::create(INO_BASE | 17, Arc::downgrade(proc_dir), |sys| { + alloc::vec![( + "kernel".into(), + GenDir::create(INO_BASE | 18, Arc::downgrade(sys), |k| { + use crate::ipc::{SHMALL, SHMMAX, SHMMNI}; + alloc::vec![ + ("hostname".into(), uts_file(INO_BASE | 19, k, false)), + ("domainname".into(), uts_file(INO_BASE | 20, k, true)), + ( + "osrelease".into(), + file(INO_BASE | 21, k, || format!( + "6.6.0-segos-{}\n", + crate::VERSION + )) + ), + ("ostype".into(), file(INO_BASE | 22, k, || "Linux\n".into())), + ( + "shmmax".into(), + file(INO_BASE | 23, k, || format!("{SHMMAX}\n")) + ), + ( + "shmall".into(), + file(INO_BASE | 24, k, || format!("{SHMALL}\n")) + ), + ( + "shmmni".into(), + file(INO_BASE | 25, k, || format!("{SHMMNI}\n")) + ), + ] + }) + )] + }) +} + +/// `/proc/sys/kernel/hostname` or `domainname`: the caller's UTS +/// namespace's name; a write sets it (up to a newline, at most 64 bytes), +/// with `sethostname`'s permission rule. +fn uts_file(ino: u64, parent: &Arc, domain: bool) -> Arc { + Arc::new(RwFile { + ino, + generate: Box::new(move || { + let n = crate::proc::ns::current_uts().names(); + let mut v = if domain { n.domainname } else { n.hostname }; + if let Some(i) = v.iter().position(|&b| b == 0) { + v.truncate(i); + } + v.push(b'\n'); + v + }), + write: Box::new(move |off, data| { + if off != 0 { + return Ok(data.len()); + } + let line = data.split(|&b| b == b'\n').next().unwrap_or(&[]); + let name = &line[..line.len().min(crate::proc::ns::UTS_LEN)]; + crate::proc::ns::current_uts().set(domain, name, &caller_user_ns()?)?; + Ok(data.len()) + }), + parent: Arc::downgrade(parent), + }) +} + +/// `/proc/sysvipc/shm`: the caller's IPC namespace's shared memory +/// segments, in Linux's columns (util-linux `ipcs` reads it). +fn sysvipc_dir(proc_dir: &Arc) -> Arc { + GenDir::create(INO_BASE | 26, Arc::downgrade(proc_dir), |d| { + alloc::vec![("shm".into(), file(INO_BASE | 27, d, sysvipc_shm))] + }) +} + +fn sysvipc_shm() -> String { + let mut out = String::from( + " key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n", + ); + let Some(p) = crate::task::current().user().map(|u| u.process.clone()) else { + return out; + }; + let ns = p.ipc_ns.lock().clone(); + let caller = crate::ipc::Caller { + user_ns: p.user_ns.lock().clone(), + pid: p.pid, + }; + let segments = ns.shm.lock().segments(); + for seg in segments { + let st = crate::ipc::stat(&seg, &caller, &p.pid_ns); + let rss = seg.size.next_multiple_of(4096); + let _ = writeln!( + out, + "{:10} {:10} {:4o} {:21} {:5} {:5} {:5} {:5} {:5} {:5} {:5} {:10} {:10} {:10} {:21} {:21}", + st.perm.key, + seg.id, + st.perm.mode, + st.segsz, + st.cpid, + st.lpid, + st.nattch, + st.perm.uid, + st.perm.gid, + st.perm.cuid, + st.perm.cgid, + st.atime, + st.dtime, + st.ctime, + rss, + 0 + ); + } + out +} + fn meminfo() -> String { let total = crate::mm::frame::total_count() * 4; let free = crate::mm::frame::free_count() * 4; diff --git a/kernel/src/ipc.rs b/kernel/src/ipc.rs new file mode 100644 index 0000000..cef951c --- /dev/null +++ b/kernel/src/ipc.rs @@ -0,0 +1,519 @@ +//! System V IPC: shared memory segments (`shmget`, `shmat`, `shmdt`, +//! `shmctl`), one table per IPC namespace. +//! +//! A segment's memory is an unnamed tmpfs file, as memfd's is: `shmat` +//! maps it `MAP_SHARED`, so `fork` shares it and the page cache keeps +//! its pages alive while any mapping (or the segment) holds the file. +//! The attach count is not kept by hand; it is counted from the address +//! spaces of the live processes (one per mapping that starts at the +//! segment's beginning), so `fork`, `munmap` and exit change it the way +//! they do on Linux. A segment removed with IPC_RMID while attached +//! stays (reachable by id only) until its last mapping goes; tables +//! drop such segments when they are next looked at. + +use crate::abi::{Errno, KResult, Pod}; +use crate::fs::{FileType, Inode}; +use crate::mm::vm::{AddressSpace, Kind}; +use crate::proc::ns::{Ids, IpcNs, UserNs}; +use crate::sync::SpinLock; +use alloc::collections::BTreeMap; +use alloc::sync::{Arc, Weak}; +use alloc::vec::Vec; + +/// `IPC_PRIVATE`: a key that always makes a new object. +pub const IPC_PRIVATE: i32 = 0; +pub const IPC_CREAT: u32 = 0o1000; +pub const IPC_EXCL: u32 = 0o2000; + +/// `shm_perm.mode` bits beyond the permissions. +pub const SHM_DEST: u32 = 0o1000; +pub const SHM_LOCKED: u32 = 0o2000; + +/// Linux's defaults (`/proc/sys/kernel/shm*`). +pub const SHMMIN: u64 = 1; +pub const SHMMAX: u64 = u64::MAX - (1 << 24); +pub const SHMALL: u64 = u64::MAX - (1 << 24); +pub const SHMMNI: u32 = 4096; +/// Ids are `seq << 15 | index` (IPCMNI_SHIFT), as on Linux. +const SEQ_SHIFT: u32 = 15; +const SEQ_MAX: u32 = (i32::MAX as u32) >> SEQ_SHIFT; +/// Indexes run below this (IPCMNI); SHMMNI bounds how many are in use. +const IPCMNI: u32 = 1 << SEQ_SHIFT; + +const PAGE: u64 = 4096; + +pub struct Segment { + pub id: i32, + pub size: u64, + /// The memory: an unnamed tmpfs file of `size` bytes. + pub inode: Arc, + pub meta: SpinLock, +} + +/// What `IPC_STAT` reports (ids are kernel ids, times in seconds). +#[derive(Clone, Copy)] +pub struct Meta { + /// The key; IPC_PRIVATE once removed. + pub key: i32, + pub uid: u32, + pub gid: u32, + pub cuid: u32, + pub cgid: u32, + /// Permission bits, SHM_DEST and SHM_LOCKED. + pub mode: u32, + pub seq: u16, + pub atime: i64, + pub dtime: i64, + pub ctime: i64, + /// Kernel pids of the creator and of the last `shmat`/`shmdt`. + pub cpid: u32, + pub lpid: u32, +} + +/// Segments by the inode number of their memory, so that `shmdt` (and +/// `/proc`) can tell a segment's mapping from any other shared mapping. +static BY_INODE: SpinLock>> = SpinLock::new(BTreeMap::new()); + +impl Drop for Segment { + fn drop(&mut self) { + BY_INODE.lock().remove(&self.inode.ino()); + } +} + +fn same_inode(a: &Arc, b: &Arc) -> bool { + core::ptr::addr_eq(Arc::as_ptr(a), Arc::as_ptr(b)) +} + +/// The segment whose memory `inode` is, if it is one. (A segment whose +/// IPC namespace is gone is no longer known here: its mappings stay +/// until unmapped, but `shmdt` no longer recognises them.) +pub fn segment_of(inode: &Arc) -> Option> { + BY_INODE + .lock() + .get(&inode.ino()) + .and_then(Weak::upgrade) + .filter(|s| same_inode(&s.inode, inode)) +} + +/// The address spaces of every live process, each once. +fn address_spaces() -> Vec> { + let mut spaces: Vec> = Vec::new(); + for p in crate::proc::all() { + for t in p.threads() { + let Some(mm) = t.user().and_then(|u| u.try_mm()) else { + continue; + }; + if !spaces.iter().any(|s| Arc::ptr_eq(s, &mm)) { + spaces.push(mm); + } + } + } + spaces +} + +impl Segment { + /// The number of current attaches: mappings of the segment that start + /// at its beginning, in all address spaces. + pub fn nattch(&self) -> u64 { + address_spaces() + .iter() + .map(|mm| { + mm.regions() + .iter() + .filter(|v| { + v.kind == Kind::Shared + && v.file + .as_ref() + .is_some_and(|(f, off)| *off == 0 && same_inode(f, &self.inode)) + }) + .count() as u64 + }) + .sum() + } + + /// Removed and no longer attached: gone for good. + fn is_dead(&self) -> bool { + let removed = self.meta.lock().mode & SHM_DEST != 0; + removed && self.nattch() == 0 + } +} + +pub fn now_secs() -> i64 { + (crate::time::realtime_ns() / crate::time::NS_PER_SEC) as i64 +} + +/// The caller's credentials, as far as SysV IPC is concerned: every +/// process runs as kernel uid and gid 0; privilege (CAP_IPC_OWNER, +/// CAP_SYS_ADMIN) comes from being in the namespace's owner or above. +pub struct Caller { + pub user_ns: Arc, + pub pid: u32, +} + +impl Caller { + pub fn capable(&self, ns: &IpcNs) -> bool { + self.user_ns.is_ancestor_of(&ns.owner) + } + + /// `ipcperms`: whether the caller may have access `want` (the 0o7 + /// bits: 4 read, 2 write) to an object with `meta`. + pub fn may(&self, ns: &IpcNs, meta: &Meta, want: u32) -> bool { + let granted = if meta.uid == 0 || meta.cuid == 0 { + meta.mode >> 6 + } else if meta.gid == 0 || meta.cgid == 0 { + meta.mode >> 3 + } else { + meta.mode + }; + want & !granted & 0o7 == 0 || self.capable(ns) + } + + /// Whether the caller owns the object (or is privileged): who may + /// IPC_SET and IPC_RMID it. + pub fn owns(&self, ns: &IpcNs, meta: &Meta) -> bool { + meta.uid == 0 || meta.cuid == 0 || self.capable(ns) + } + + pub fn view(&self, which: Ids, kid: u32) -> u32 { + self.user_ns.view(which, kid) + } +} + +pub struct ShmTable { + by_index: BTreeMap>, + /// The sequence number (`ipc_ids.seq`): it moves on whenever an + /// index at or below the last one handed out is used again, so a + /// recycled index gets a new id. + seq: u32, + last_index: Option, +} + +impl Default for ShmTable { + fn default() -> Self { + Self::new() + } +} + +impl ShmTable { + pub const fn new() -> Self { + Self { + by_index: BTreeMap::new(), + seq: 0, + last_index: None, + } + } + + /// Drops segments that were removed and are no longer attached. + fn prune(&mut self) { + self.by_index.retain(|_, s| !s.is_dead()); + } + + /// `shmget`: the id of the segment with `key`, made if need be. + pub fn get( + &mut self, + ns: &IpcNs, + caller: &Caller, + key: i32, + size: u64, + flags: u32, + ) -> KResult { + self.prune(); + if key != IPC_PRIVATE { + let found = self + .by_index + .values() + .find(|s| s.meta.lock().key == key) + .cloned(); + if let Some(s) = found { + if flags & IPC_CREAT != 0 && flags & IPC_EXCL != 0 { + return Err(Errno::EEXIST); + } + if s.size < size { + return Err(Errno::EINVAL); + } + let want = (flags >> 6 | flags >> 3 | flags) & 0o7; + if !caller.may(ns, &s.meta.lock(), want) { + return Err(Errno::EACCES); + } + return Ok(s.id); + } + if flags & IPC_CREAT == 0 { + return Err(Errno::ENOENT); + } + } + if !(SHMMIN..=SHMMAX).contains(&size) { + return Err(Errno::EINVAL); + } + if self.by_index.len() >= SHMMNI as usize { + return Err(Errno::ENOSPC); + } + // Cyclic, as `idr_alloc_cyclic`: the first free index after the + // last one handed out, wrapping around. + let next = self.last_index.map_or(0, |l| l + 1); + let index = (next..IPCMNI) + .chain(0..next.min(IPCMNI)) + .find(|i| !self.by_index.contains_key(i)) + .ok_or(Errno::ENOSPC)?; + if self.last_index.is_some_and(|last| index <= last) { + self.seq += 1; + if self.seq >= SEQ_MAX { + self.seq = 0; + } + } + self.last_index = Some(index); + let seq = self.seq; + let id = (seq << SEQ_SHIFT | index) as i32; + // The memory: a file in a private tmpfs directory, unlinked. + let dir = crate::fs::tmpfs::Dir::new_root(0o700); + let name = alloc::format!("SYSV{key:08x}"); + let inode = dir.create(&name, FileType::Regular, 0o600)?; + dir.remove(&name, false)?; + inode.truncate(size)?; + let now = now_secs(); + let seg = Arc::new(Segment { + id, + size, + inode: inode.clone(), + meta: SpinLock::new(Meta { + key, + uid: 0, + gid: 0, + cuid: 0, + cgid: 0, + mode: flags & 0o777, + seq: seq as u16, + atime: 0, + dtime: 0, + ctime: now, + cpid: caller.pid, + lpid: 0, + }), + }); + BY_INODE.lock().insert(inode.ino(), Arc::downgrade(&seg)); + self.by_index.insert(index, seg); + Ok(id) + } + + /// The segment with id `id` (EINVAL if there is none, or its + /// sequence number is stale). + pub fn find(&mut self, id: i32) -> KResult> { + if id < 0 { + return Err(Errno::EINVAL); + } + let index = id as u32 & ((1 << SEQ_SHIFT) - 1); + let s = self.by_index.get(&index).cloned().ok_or(Errno::EINVAL)?; + if s.id != id { + return Err(Errno::EINVAL); + } + if s.is_dead() { + self.by_index.remove(&index); + return Err(Errno::EINVAL); + } + Ok(s) + } + + /// `IPC_RMID`: the key is freed now, the segment once unattached. + pub fn remove(&mut self, seg: &Arc) { + { + let mut m = seg.meta.lock(); + m.mode |= SHM_DEST; + m.key = IPC_PRIVATE; + } + self.prune(); + } + + /// The highest index in use (`IPC_INFO`/`SHM_INFO` report it), or 0. + pub fn max_index(&mut self) -> u32 { + self.prune(); + self.by_index.keys().next_back().copied().unwrap_or(0) + } + + /// The segment at table index `index` (`SHM_STAT`). + pub fn at_index(&mut self, index: u32) -> KResult> { + self.prune(); + self.by_index.get(&index).cloned().ok_or(Errno::EINVAL) + } + + /// Segments in use, and the pages they hold (`SHM_INFO`). + pub fn usage(&mut self) -> (u32, u64) { + self.prune(); + let pages = self.by_index.values().map(|s| s.size.div_ceil(PAGE)).sum(); + (self.by_index.len() as u32, pages) + } + + pub fn segments(&mut self) -> Vec> { + self.prune(); + self.by_index.values().cloned().collect() + } +} + +/// `struct ipc64_perm` (x86-64). +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct IpcPerm { + pub key: i32, + pub uid: u32, + pub gid: u32, + pub cuid: u32, + pub cgid: u32, + pub mode: u32, + pub seq: u16, + pub pad2: u16, + pub pad3: u32, + pub unused1: u64, + pub unused2: u64, +} + +/// `struct shmid64_ds` (x86-64). +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct ShmidDs { + pub perm: IpcPerm, + pub segsz: u64, + pub atime: i64, + pub dtime: i64, + pub ctime: i64, + pub cpid: i32, + pub lpid: i32, + pub nattch: u64, + pub unused4: u64, + pub unused5: u64, +} + +/// `struct shminfo64`: what IPC_INFO reports. +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct ShmInfo64 { + pub shmmax: u64, + pub shmmin: u64, + pub shmmni: u64, + pub shmseg: u64, + pub shmall: u64, + pub unused: [u64; 4], +} + +/// `struct shm_info`: what SHM_INFO reports. +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct ShmInfo { + pub used_ids: i32, + pub pad: u32, + pub shm_tot: u64, + pub shm_rss: u64, + pub shm_swp: u64, + pub swap_attempts: u64, + pub swap_successes: u64, +} + +unsafe impl Pod for ShmidDs {} +unsafe impl Pod for ShmInfo64 {} +unsafe impl Pod for ShmInfo {} + +const _: () = assert!(size_of::() == 48); +const _: () = assert!(size_of::() == 112); +const _: () = assert!(size_of::() == 72); +const _: () = assert!(size_of::() == 48); + +/// `shmid64_ds` for `seg` as `caller` sees it (pids in its PID +/// namespace, ids in its user namespace). +pub fn stat(seg: &Segment, caller: &Caller, pid_ns: &crate::proc::ns::PidNs) -> ShmidDs { + let m = *seg.meta.lock(); + ShmidDs { + perm: IpcPerm { + key: m.key, + uid: caller.view(Ids::Uid, m.uid), + gid: caller.view(Ids::Gid, m.gid), + cuid: caller.view(Ids::Uid, m.cuid), + cgid: caller.view(Ids::Gid, m.cgid), + mode: m.mode, + seq: m.seq, + ..Default::default() + }, + segsz: seg.size, + atime: m.atime, + dtime: m.dtime, + ctime: m.ctime, + cpid: pid_ns.nr(m.cpid) as i32, + lpid: pid_ns.nr(m.lpid) as i32, + nattch: seg.nattch(), + ..Default::default() + } +} + +#[cfg(feature = "ktest")] +pub(crate) mod tests { + use super::*; + + fn caller() -> Caller { + Caller { + user_ns: UserNs::initial(), + pid: 0, + } + } + + /// Keys, IPC_CREAT/IPC_EXCL and sizes, as `shmget` checks them. + pub(crate) fn get_rules() { + let ns = IpcNs::new(&UserNs::initial()); + let c = caller(); + let mut t = ns.shm.lock(); + assert_eq!(t.get(&ns, &c, 7, 100, 0o600), Err(Errno::ENOENT)); + assert_eq!(t.get(&ns, &c, 7, 0, IPC_CREAT | 0o600), Err(Errno::EINVAL)); + let id = t.get(&ns, &c, 7, 100, IPC_CREAT | 0o600).unwrap(); + assert_eq!(id, 0); + assert_eq!(t.get(&ns, &c, 7, 0, 0), Ok(id)); + assert_eq!(t.get(&ns, &c, 7, 101, 0), Err(Errno::EINVAL)); + assert_eq!( + t.get(&ns, &c, 7, 100, IPC_CREAT | IPC_EXCL), + Err(Errno::EEXIST) + ); + // The memory is a file of exactly the asked size. + assert_eq!(t.find(id).unwrap().inode.size(), 100); + // IPC_PRIVATE always makes a new one. + assert_eq!(t.get(&ns, &c, IPC_PRIVATE, 1, 0), Ok(1)); + assert_eq!(t.get(&ns, &c, IPC_PRIVATE, 1, 0), Ok(2)); + } + + /// Ids: cyclic indexes, and a new sequence number once an index at or + /// below the last one is used again; removal frees the key. + pub(crate) fn ids_and_removal() { + let ns = IpcNs::new(&UserNs::initial()); + let c = caller(); + let mut t = ns.shm.lock(); + let a = t.get(&ns, &c, 1, 4096, IPC_CREAT).unwrap(); + let b = t.get(&ns, &c, 2, 4096, IPC_CREAT).unwrap(); + assert_eq!((a, b), (0, 1)); + let seg = t.find(a).unwrap(); + t.remove(&seg); + drop(seg); + assert_eq!(t.find(a).err(), Some(Errno::EINVAL)); + assert_eq!(t.get(&ns, &c, 1, 4096, 0), Err(Errno::ENOENT)); + // Index 2 next (cyclic), still sequence 0. + assert_eq!(t.get(&ns, &c, 1, 4096, IPC_CREAT), Ok(2)); + // Force a wrap: the next free index after the last is 0 again + // once the top is reached, with sequence 1. + t.last_index = Some(IPCMNI - 1); + let wrapped = t.get(&ns, &c, 3, 4096, IPC_CREAT).unwrap(); + assert_eq!(wrapped, 1 << SEQ_SHIFT); + // A stale id (right index, old sequence) is not found. + assert_eq!(t.find(0).err(), Some(Errno::EINVAL)); + assert!(t.find(wrapped).is_ok()); + } + + /// `sethostname`'s rules: privilege over the owner first, then the + /// length; a copied namespace starts with its parent's names. + pub(crate) fn uts_names() { + use crate::proc::ns::UtsNs; + let root = UserNs::initial(); + let child = UserNs::new(&root).unwrap(); + let uts = UtsNs::copy_of(&UtsNs::initial(), &root); + assert_eq!(uts.names().hostname, UtsNs::initial().names().hostname); + assert_eq!(uts.set(false, b"x", &child), Err(Errno::EPERM)); + assert_eq!(uts.set(false, &[b'a'; 65], &root), Err(Errno::EINVAL)); + uts.set(false, &[b'a'; 64], &root).unwrap(); + assert_eq!(uts.names().hostname.len(), 64); + let own = UtsNs::copy_of(&uts, &child); + own.set(true, b"example.org", &child).unwrap(); + assert_eq!(own.names().domainname, b"example.org"); + assert_eq!(uts.names().domainname, b"(none)"); + } +} diff --git a/kernel/src/ktest.rs b/kernel/src/ktest.rs index b3b17e4..53ce966 100644 --- a/kernel/src/ktest.rs +++ b/kernel/src/ktest.rs @@ -92,6 +92,15 @@ const TESTS: &[(&str, fn())] = &[ "fanotify: child and ignored masks", crate::fs::event::fan_tests::child_and_ignored_masks, ), + ( + "sysv shm: shmget keys, flags and sizes", + crate::ipc::tests::get_rules, + ), + ( + "sysv shm: ids and removal", + crate::ipc::tests::ids_and_removal, + ), + ("uts: host and domain names", crate::ipc::tests::uts_names), ]; pub fn run(boot: &'static BootInfo) -> ! { diff --git a/kernel/src/main.rs b/kernel/src/main.rs index 550f53f..505b1ad 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -21,6 +21,7 @@ mod font; mod fs; mod hal; mod input; +mod ipc; #[macro_use] mod klog; #[cfg(feature = "ktest")] diff --git a/kernel/src/proc/mod.rs b/kernel/src/proc/mod.rs index 7da84a0..7b69df7 100644 --- a/kernel/src/proc/mod.rs +++ b/kernel/src/proc/mod.rs @@ -80,6 +80,10 @@ pub struct Process { pub net_ns: SpinLock>, /// The mount table this process sees (a private copy after CLONE_NEWNS). pub mnt_ns: SpinLock>, + /// Host and domain names (a private copy after CLONE_NEWUTS). + pub uts_ns: SpinLock>, + /// System V IPC objects (a new, empty set after CLONE_NEWIPC). + pub ipc_ns: SpinLock>, pub sigactions: SpinLock<[SigAction; signal::NSIG]>, pub children: SpinLock>>, /// Bumped and woken whenever a child changes state. @@ -239,6 +243,11 @@ impl UserThread { .expect("user thread without an address space") } + /// The address space, unless the thread has exited and let it go. + pub fn try_mm(&self) -> Option> { + self.mm.lock().clone() + } + /// Makes the thread exit with wait status `status` when the current /// system call returns. pub fn request_exit(&self, status: i32) { @@ -392,6 +401,8 @@ fn new_process( fs: SpinLock::new(FsState::new(cwd)), net_ns: SpinLock::new(ns::NetNs::initial()), mnt_ns: SpinLock::new(ns::MntNs::initial()), + uts_ns: SpinLock::new(ns::UtsNs::initial()), + ipc_ns: SpinLock::new(ns::IpcNs::initial()), sigactions: SpinLock::new([SigAction::default(); signal::NSIG]), children: SpinLock::new(Vec::new()), child_events: AtomicU64::new(0), @@ -523,8 +534,10 @@ pub mod clone_flags { pub const CLONE_NEWUSER: u64 = 0x1000_0000; pub const CLONE_NEWPID: u64 = 0x2000_0000; pub const CLONE_NEWNET: u64 = 0x4000_0000; - /// UTS, IPC and cgroup namespaces: not yet. - pub const UNSUPPORTED: u64 = 0x0e00_0000; + pub const CLONE_NEWUTS: u64 = 0x0400_0000; + pub const CLONE_NEWIPC: u64 = 0x0800_0000; + /// cgroup namespaces: not yet. + pub const UNSUPPORTED: u64 = 0x0200_0000; } /// `fork`, `vfork` and `clone`. `frame` is the parent's saved user state; @@ -540,14 +553,20 @@ pub fn clone( tls: u64, ) -> KResult { use clone_flags::*; - if flags & UNSUPPORTED != 0 || (flags & CLONE_SIGHAND != 0 && flags & CLONE_VM == 0) { + if flags & UNSUPPORTED != 0 + || (flags & CLONE_SIGHAND != 0 && flags & CLONE_VM == 0) + || (flags & CLONE_NEWIPC != 0 && flags & CLONE_SYSVSEM != 0) + { return Err(Errno::EINVAL); } // A new namespace cannot share the caller's thread group, and a new // user or mount namespace cannot share its filesystem state; the init // of a PID namespace cannot give itself siblings. let me = &t.process; - if (flags & (CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS) != 0 && flags & CLONE_THREAD != 0) + // (Namespaces are per process here, so a thread cannot have its own + // UTS or IPC namespace either.) + let new_ns = CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC; + if (flags & new_ns != 0 && flags & CLONE_THREAD != 0) || (flags & (CLONE_NEWUSER | CLONE_NEWNS) != 0 && flags & CLONE_FS != 0) || (flags & CLONE_PARENT != 0 && me.pid_ns.level > 0 && me.pid_ns.reaper() == me.pid) { @@ -627,6 +646,19 @@ pub fn clone( } else { parent.mnt_ns.lock().clone() }; + // New UTS and IPC namespaces belong to the child's user namespace + // (the new one, with CLONE_NEWUSER). + let owner = child.user_ns.get_mut().clone(); + *child.uts_ns.get_mut() = if flags & CLONE_NEWUTS != 0 { + ns::UtsNs::copy_of(&parent.uts_ns.lock(), &owner) + } else { + parent.uts_ns.lock().clone() + }; + *child.ipc_ns.get_mut() = if flags & CLONE_NEWIPC != 0 { + ns::IpcNs::new(&owner) + } else { + parent.ipc_ns.lock().clone() + }; child.trace = AtomicU32::new(parent.trace.load(Ordering::Relaxed)); *child.sigactions.get_mut() = *parent.sigactions.lock(); child diff --git a/kernel/src/proc/ns.rs b/kernel/src/proc/ns.rs index b8d449d..f78c64f 100644 --- a/kernel/src/proc/ns.rs +++ b/kernel/src/proc/ns.rs @@ -1,5 +1,6 @@ //! Namespaces (`clone`/`unshare` with CLONE_NEWUSER, CLONE_NEWPID, -//! CLONE_NEWNET and CLONE_NEWNS), as browser sandboxes use them. +//! CLONE_NEWNET, CLONE_NEWNS, CLONE_NEWUTS and CLONE_NEWIPC), as browser +//! sandboxes and container tools use them. //! //! Every process runs as root (kernel uid and gid 0). A user namespace //! only changes how ids look from inside it: through its `uid_map` and @@ -28,6 +29,8 @@ const MAX_LEVEL: u32 = 32; /// PROC_USER_INIT_INO and PROC_PID_INIT_INO). const USER_INIT_INO: u64 = 0xeffffffd; const PID_INIT_INO: u64 = 0xeffffffc; +const UTS_INIT_INO: u64 = 0xeffffffe; +const IPC_INIT_INO: u64 = 0xefffffff; /// Later namespaces are numbered from here on, as Linux's are. static NEXT_INO: AtomicU64 = AtomicU64::new(0xf000_0000); @@ -378,6 +381,121 @@ pub fn current_mnt() -> Arc { .unwrap_or_else(MntNs::initial) } +/// `__NEW_UTS_LEN`: the longest host or domain name. +pub const UTS_LEN: usize = 64; + +/// The names a UTS namespace holds: what `uname` reports as `nodename` +/// and `domainname`, as raw bytes (`sethostname` keeps whatever it is +/// given, NULs included; readers stop at the first NUL). +#[derive(Clone)] +pub struct UtsNames { + pub hostname: Vec, + pub domainname: Vec, +} + +/// A UTS namespace: its own host and domain names. Changing them needs +/// privilege over `owner`, the user namespace it was created in. +pub struct UtsNs { + pub ino: u64, + pub owner: Arc, + names: SpinLock, +} + +static INIT_UTS: SpinLock>> = SpinLock::new(None); + +impl UtsNs { + pub fn initial() -> Arc { + INIT_UTS + .lock() + .get_or_insert_with(|| { + Arc::new(UtsNs { + ino: UTS_INIT_INO, + owner: UserNs::initial(), + names: SpinLock::new(UtsNames { + hostname: b"segos".to_vec(), + domainname: b"(none)".to_vec(), + }), + }) + }) + .clone() + } + + /// A new namespace owned by `owner`, starting with `from`'s names. + pub fn copy_of(from: &Arc, owner: &Arc) -> Arc { + Arc::new(UtsNs { + ino: new_ino(), + owner: owner.clone(), + names: SpinLock::new(from.names()), + }) + } + + pub fn names(&self) -> UtsNames { + self.names.lock().clone() + } + + /// `sethostname` or `setdomainname` (`domain`) by a process of + /// `caller`: EPERM without privilege over the namespace's owner, + /// EINVAL for a name longer than 64 bytes (checked in that order, as + /// Linux does). + pub fn set(&self, domain: bool, name: &[u8], caller: &Arc) -> KResult<()> { + if !caller.is_ancestor_of(&self.owner) { + return Err(Errno::EPERM); + } + if name.len() > UTS_LEN { + return Err(Errno::EINVAL); + } + let mut n = self.names.lock(); + let field = if domain { + &mut n.domainname + } else { + &mut n.hostname + }; + *field = name.to_vec(); + Ok(()) + } +} + +/// The UTS namespace of the calling process. +pub fn current_uts() -> Arc { + crate::task::try_current() + .and_then(|t| t.user().map(|u| u.process.uts_ns.lock().clone())) + .unwrap_or_else(UtsNs::initial) +} + +/// An IPC namespace: its own System V IPC objects (shared memory +/// segments). Privilege over `owner` stands in for CAP_IPC_OWNER. +pub struct IpcNs { + pub ino: u64, + pub owner: Arc, + pub shm: crate::sync::Mutex, +} + +static INIT_IPC: SpinLock>> = SpinLock::new(None); + +impl IpcNs { + pub fn initial() -> Arc { + INIT_IPC + .lock() + .get_or_insert_with(|| { + Arc::new(IpcNs { + ino: IPC_INIT_INO, + owner: UserNs::initial(), + shm: crate::sync::Mutex::new(crate::ipc::ShmTable::new()), + }) + }) + .clone() + } + + /// A new, empty namespace owned by `owner`. + pub fn new(owner: &Arc) -> Arc { + Arc::new(IpcNs { + ino: new_ino(), + owner: owner.clone(), + shm: crate::sync::Mutex::new(crate::ipc::ShmTable::new()), + }) + } +} + /// Whether `a..a+n` and `b..b+m` share an id. fn ranges_meet(a: u32, n: u32, b: u32, m: u32) -> bool { (a as u64) < b as u64 + m as u64 && (b as u64) < a as u64 + n as u64 diff --git a/kernel/src/syscall/info.rs b/kernel/src/syscall/info.rs index 6bd7b58..0205f9b 100644 --- a/kernel/src/syscall/info.rs +++ b/kernel/src/syscall/info.rs @@ -10,6 +10,29 @@ fn put(field: &mut [u8; 65], s: &str) { field[..n].copy_from_slice(&s.as_bytes()[..n]); } +fn put_bytes(field: &mut [u8; 65], s: &[u8]) { + let n = s.len().min(64); + field[..n].copy_from_slice(&s[..n]); +} + +/// `sethostname` (or `setdomainname`, `domain`): the name of the caller's +/// UTS namespace, `len` bytes from `name`. +pub fn set_uts_name(ctx: &Ctx, domain: bool, name: u64, len: i64) -> KResult { + let p = ctx.process(); + let ns = p.uts_ns.lock().clone(); + let caller = p.user_ns.lock().clone(); + if !caller.is_ancestor_of(&ns.owner) { + return Err(Errno::EPERM); + } + if !(0..=crate::proc::ns::UTS_LEN as i64).contains(&len) { + return Err(Errno::EINVAL); + } + let mut buf = vec![0u8; len as usize]; + ctx.mm().copy_from(name, &mut buf)?; + ns.set(domain, &buf, &caller)?; + Ok(0) +} + /// What `uname` reports. Programs compare `sysname` with "Linux" and parse /// `release` for a minimum kernel version (glibc wants 3.2), so SegOS /// answers as the Linux version whose interface it targets, and says what @@ -23,8 +46,9 @@ pub fn uname(ctx: &Ctx, buf: u64) -> KResult { machine: [0; 65], domainname: [0; 65], }; + let names = ctx.process().uts_ns.lock().names(); put(&mut u.sysname, "Linux"); - put(&mut u.nodename, "segos"); + put_bytes(&mut u.nodename, &names.hostname); put( &mut u.release, concat!("6.6.0-segos-", env!("CARGO_PKG_VERSION")), @@ -34,7 +58,7 @@ pub fn uname(ctx: &Ctx, buf: u64) -> KResult { concat!("#1 SegOS ", env!("CARGO_PKG_VERSION")), ); put(&mut u.machine, "x86_64"); - put(&mut u.domainname, "(none)"); + put_bytes(&mut u.domainname, &names.domainname); let bytes = unsafe { core::slice::from_raw_parts(&u as *const Utsname as *const u8, size_of::()) }; diff --git a/kernel/src/syscall/ipc.rs b/kernel/src/syscall/ipc.rs new file mode 100644 index 0000000..c2d92cc --- /dev/null +++ b/kernel/src/syscall/ipc.rs @@ -0,0 +1,248 @@ +//! System V shared memory: `shmget`, `shmat`, `shmdt` and `shmctl`, in +//! the caller's IPC namespace (the segments themselves: `crate::ipc`). + +use super::Ctx; +use crate::abi::mman::{MAP_FIXED, MAP_SHARED, PROT_EXEC, PROT_READ, PROT_WRITE}; +use crate::abi::{Errno, KResult, open}; +use crate::ipc::{ + self, Caller, SHM_LOCKED, SHMALL, SHMMAX, SHMMIN, SHMMNI, ShmInfo, ShmInfo64, ShmidDs, +}; +use crate::mm::vm::{Kind, MMAP_MIN}; +use crate::proc::ns::Ids; +use alloc::sync::Arc; + +const PAGE: u64 = 4096; +/// `SHMLBA` on x86: attach addresses are page-aligned. +const SHMLBA: u64 = PAGE; + +const SHM_RDONLY: u32 = 0o10000; +const SHM_RND: u32 = 0o20000; +const SHM_REMAP: u32 = 0o40000; +const SHM_EXEC: u32 = 0o100000; + +const IPC_RMID: i32 = 0; +const IPC_SET: i32 = 1; +const IPC_STAT: i32 = 2; +const IPC_INFO: i32 = 3; +const SHM_LOCK: i32 = 11; +const SHM_UNLOCK: i32 = 12; +const SHM_STAT: i32 = 13; +const SHM_INFO: i32 = 14; +const SHM_STAT_ANY: i32 = 15; +/// Set by C libraries that ask for the 64-bit structures (the only kind +/// x86-64 has). +const IPC_64: i32 = 0x100; + +fn caller(ctx: &Ctx) -> Caller { + let p = ctx.process(); + Caller { + user_ns: p.user_ns.lock().clone(), + pid: p.pid, + } +} + +pub fn shmget(ctx: &Ctx, key: i32, size: u64, flags: u32) -> KResult { + let ns = ctx.process().ipc_ns.lock().clone(); + let id = ns.shm.lock().get(&ns, &caller(ctx), key, size, flags)?; + Ok(id as u64) +} + +pub fn shmat(ctx: &Ctx, id: i32, addr: u64, flags: u32) -> KResult { + let ns = ctx.process().ipc_ns.lock().clone(); + let who = caller(ctx); + let seg = ns.shm.lock().find(id)?; + let mut addr = addr; + if addr & (SHMLBA - 1) != 0 { + if flags & SHM_RND == 0 { + return Err(Errno::EINVAL); + } + addr &= !(SHMLBA - 1); + if addr == 0 && flags & SHM_REMAP != 0 { + return Err(Errno::EINVAL); + } + } else if addr == 0 && flags & SHM_REMAP != 0 { + return Err(Errno::EINVAL); + } + let readonly = flags & SHM_RDONLY != 0; + let want = if readonly { 4 } else { 6 }; + if !who.may(&ns, &seg.meta.lock(), want) { + return Err(Errno::EACCES); + } + let len = seg.size.next_multiple_of(PAGE); + let mut map_flags = MAP_SHARED; + if addr != 0 { + // As `mmap` with MAP_FIXED there. + if addr < MMAP_MIN { + return Err(Errno::EPERM); + } + let end = addr.checked_add(len).ok_or(Errno::EINVAL)?; + if flags & SHM_REMAP == 0 + && ctx + .mm() + .regions() + .iter() + .any(|v| v.start < end && addr < v.end) + { + return Err(Errno::EINVAL); + } + map_flags |= MAP_FIXED; + } + let prot = PROT_READ + | if readonly { 0 } else { PROT_WRITE } + | if flags & SHM_EXEC != 0 { PROT_EXEC } else { 0 }; + let file = crate::fs::File::new( + seg.inode.clone(), + if readonly { + open::O_RDONLY + } else { + open::O_RDWR + }, + ); + let key = seg.meta.lock().key; + file.set_path(&alloc::format!("/SYSV{key:08x} (deleted)")); + let at = super::mem::map_shared(ctx, addr, len, prot, map_flags, Some(&file), 0)?; + let mut m = seg.meta.lock(); + m.atime = ipc::now_secs(); + m.lpid = who.pid; + Ok(at) +} + +/// `shmdt(addr)`: detaches the segment attached at `addr` (the mappings +/// of it from there on, as `shmat` laid them out). +pub fn shmdt(ctx: &Ctx, addr: u64) -> KResult { + if addr & (PAGE - 1) != 0 { + return Err(Errno::EINVAL); + } + let mm = ctx.mm(); + let regions = mm.regions(); + let seg = regions + .iter() + .find(|v| v.start == addr && v.kind == Kind::Shared) + .and_then(|v| v.file.as_ref()) + .filter(|(_, off)| *off == 0) + .and_then(|(f, _)| ipc::segment_of(f)) + .ok_or(Errno::EINVAL)?; + let end = addr.saturating_add(seg.size.next_multiple_of(PAGE)); + for v in ®ions { + let ours = v.start >= addr + && v.start < end + && v.kind == Kind::Shared + && v.file.as_ref().is_some_and(|(f, off)| { + core::ptr::addr_eq(Arc::as_ptr(f), Arc::as_ptr(&seg.inode)) + && *off == v.start - addr + }); + if ours { + mm.unmap(v.start, v.end - v.start)?; + } + } + let mut m = seg.meta.lock(); + m.dtime = ipc::now_secs(); + m.lpid = ctx.process().pid; + Ok(0) +} + +pub fn shmctl(ctx: &Ctx, id: i32, cmd: i32, buf: u64) -> KResult { + if cmd < 0 { + return Err(Errno::EINVAL); + } + let cmd = cmd & !IPC_64; + let p = ctx.process(); + let ns = p.ipc_ns.lock().clone(); + let who = caller(ctx); + let mut table = ns.shm.lock(); + match cmd { + IPC_INFO => { + let info = ShmInfo64 { + shmmax: SHMMAX, + shmmin: SHMMIN, + shmmni: SHMMNI as u64, + shmseg: SHMMNI as u64, + shmall: SHMALL, + ..Default::default() + }; + let max = table.max_index(); + drop(table); + ctx.mm().write(buf, &info)?; + Ok(max as u64) + } + SHM_INFO => { + let (used, pages) = table.usage(); + let max = table.max_index(); + drop(table); + let info = ShmInfo { + used_ids: used as i32, + shm_tot: pages, + shm_rss: pages, + ..Default::default() + }; + ctx.mm().write(buf, &info)?; + Ok(max as u64) + } + SHM_STAT | SHM_STAT_ANY => { + if id < 0 { + return Err(Errno::EINVAL); + } + let seg = table.at_index(id as u32)?; + drop(table); + if cmd == SHM_STAT && !who.may(&ns, &seg.meta.lock(), 4) { + return Err(Errno::EACCES); + } + ctx.mm().write(buf, &ipc::stat(&seg, &who, &p.pid_ns))?; + Ok(seg.id as u64) + } + IPC_STAT => { + let seg = table.find(id)?; + drop(table); + if !who.may(&ns, &seg.meta.lock(), 4) { + return Err(Errno::EACCES); + } + ctx.mm().write(buf, &ipc::stat(&seg, &who, &p.pid_ns))?; + Ok(0) + } + IPC_SET => { + let new: ShmidDs = ctx.mm().read(buf)?; + let seg = table.find(id)?; + drop(table); + if !who.owns(&ns, &seg.meta.lock()) { + return Err(Errno::EPERM); + } + let uid = who + .user_ns + .to_kernel(Ids::Uid, new.perm.uid) + .ok_or(Errno::EINVAL)?; + let gid = who + .user_ns + .to_kernel(Ids::Gid, new.perm.gid) + .ok_or(Errno::EINVAL)?; + let mut m = seg.meta.lock(); + m.uid = uid; + m.gid = gid; + m.mode = (m.mode & !0o777) | (new.perm.mode & 0o777); + m.ctime = ipc::now_secs(); + Ok(0) + } + IPC_RMID => { + let seg = table.find(id)?; + if !who.owns(&ns, &seg.meta.lock()) { + return Err(Errno::EPERM); + } + table.remove(&seg); + Ok(0) + } + SHM_LOCK | SHM_UNLOCK => { + let seg = table.find(id)?; + drop(table); + if !who.owns(&ns, &seg.meta.lock()) { + return Err(Errno::EPERM); + } + let mut m = seg.meta.lock(); + if cmd == SHM_LOCK { + m.mode |= SHM_LOCKED; + } else { + m.mode &= !SHM_LOCKED; + } + Ok(0) + } + _ => Err(Errno::EINVAL), + } +} diff --git a/kernel/src/syscall/mem.rs b/kernel/src/syscall/mem.rs index 00d502a..9c7123f 100644 --- a/kernel/src/syscall/mem.rs +++ b/kernel/src/syscall/mem.rs @@ -93,7 +93,7 @@ pub fn mmap( /// `MAP_SHARED`: the file's page-cache pages, or (anonymous) fresh pages /// that `fork` shares rather than copies. -fn map_shared( +pub(super) fn map_shared( ctx: &Ctx, addr: u64, len: u64, diff --git a/kernel/src/syscall/mod.rs b/kernel/src/syscall/mod.rs index f7c8c32..45bea82 100644 --- a/kernel/src/syscall/mod.rs +++ b/kernel/src/syscall/mod.rs @@ -8,6 +8,7 @@ mod event; mod fs; mod info; +mod ipc; mod mem; mod net; mod process; @@ -234,6 +235,12 @@ fn dispatch(ctx: &Ctx, frame: &mut TrapFrame, nr: u64, a: [u64; 6]) -> KResult process::wait4(ctx, a[0] as i32, a[1], a[2] as u32, a[3]), 62 | 200 | 234 => process::kill(ctx, a, nr), 63 => info::uname(ctx, a[0]), + 29 => ipc::shmget(ctx, a[0] as i32, a[1], a[2] as u32), + 30 => ipc::shmat(ctx, a[0] as i32, a[1], a[2] as u32), + 31 => ipc::shmctl(ctx, a[0] as i32, a[1] as i32, a[2]), + 67 => ipc::shmdt(ctx, a[0]), + 170 => info::set_uts_name(ctx, false, a[0], a[1] as i32 as i64), + 171 => info::set_uts_name(ctx, true, a[0], a[1] as i32 as i64), 72 => fs::fcntl(ctx, fd, a[1] as u32, a[2]), 74 | 75 => fs::fsync(ctx, fd), 76 => fs::truncate(ctx, a[0], a[1] as i64), diff --git a/kernel/src/syscall/process.rs b/kernel/src/syscall/process.rs index a9feba3..a7a8c4f 100644 --- a/kernel/src/syscall/process.rs +++ b/kernel/src/syscall/process.rs @@ -277,18 +277,20 @@ pub fn sigaltstack(ctx: &Ctx, frame: &TrapFrame, new: u64, old: u64) -> KResult< Ok(0) } -/// `unshare(flags)`: a new user, mount or network namespace for the -/// caller, or a new PID namespace for its children; CLONE_FS stops +/// `unshare(flags)`: a new user, mount, network, UTS or IPC namespace for +/// the caller, or a new PID namespace for its children; CLONE_FS stops /// sharing the filesystem state; CLONE_FILES and CLONE_SYSVSEM change /// nothing (descriptor tables are never shared); CLONE_THREAD, /// CLONE_SIGHAND and CLONE_VM only for a single-threaded caller. pub fn unshare(ctx: &Ctx, flags: u64) -> KResult { use proc::clone_flags::*; - use proc::ns::{MntNs, PidNs, UserNs}; + use proc::ns::{IpcNs, MntNs, PidNs, UserNs, UtsNs}; let known = CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWNS + | CLONE_NEWUTS + | CLONE_NEWIPC | CLONE_FILES | CLONE_FS | CLONE_SYSVSEM @@ -338,6 +340,15 @@ pub fn unshare(ctx: &Ctx, flags: u64) -> KResult { }; *p.mnt_ns.lock() = own; } + // Owned by the caller's user namespace (the new one, if any). + let owner = p.user_ns.lock().clone(); + if flags & CLONE_NEWUTS != 0 { + let own = UtsNs::copy_of(&p.uts_ns.lock(), &owner); + *p.uts_ns.lock() = own; + } + if flags & CLONE_NEWIPC != 0 { + *p.ipc_ns.lock() = IpcNs::new(&owner); + } if let Some(n) = pid { *p.child_pid_ns.lock() = n; } diff --git a/userland/tests/sysvipc.c b/userland/tests/sysvipc.c new file mode 100644 index 0000000..435cc16 --- /dev/null +++ b/userland/tests/sysvipc.c @@ -0,0 +1,386 @@ +/* + * Phase 8 conformance test: UTS and IPC namespaces, and System V shared + * memory (what X's MIT-SHM, ALSA's dmix and container tools use). + * + * UTS: a new namespace starts with its parent's names; sethostname and + * setdomainname change only it (uname, /proc/sys/kernel/hostname), need + * privilege over the namespace's owner, and reject names over 64 bytes. + * IPC: a new namespace has no segments; inside one, shmget with keys and + * IPC_PRIVATE, IPC_CREAT/IPC_EXCL, shmat (anywhere, at an address, + * SHM_RND, read-only), sharing across fork, shmdt, the attach count, + * IPC_STAT/IPC_SET/IPC_INFO/SHM_INFO, IPC_RMID while attached, and the + * segment staying visible only in its own namespace. + * + * Everything happens inside new user namespaces (mapping the caller to + * root), so it prints the same on Linux as root or not, and on SegOS. + * `cargo xtask test` runs it on both; both must print exactly + * sysvipc.expected and exit with 0. It never prints an id that depends + * on the machine. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int failures; + +#define CHECK(cond) \ + do { \ + errno = 0; \ + if (cond) { \ + printf("ok %s\n", #cond); \ + } else { \ + printf("FAIL %s (line %d, errno %d)\n", #cond, \ + __LINE__, errno); \ + failures++; \ + } \ + fflush(stdout); \ + } while (0) + +static void section(const char *name) +{ + printf("# %s\n", name); +} + +static char buf[512]; + +static int write_file(const char *path, const char *text) +{ + int fd = open(path, O_WRONLY); + if (fd < 0) + return -1; + ssize_t n = write(fd, text, strlen(text)); + int e = errno; + close(fd); + errno = e; + return n == (ssize_t)strlen(text) ? 0 : -1; +} + +static int read_file(const char *path) +{ + int fd = open(path, O_RDONLY); + if (fd < 0) + return -1; + ssize_t n = read(fd, buf, sizeof buf - 1); + close(fd); + if (n < 0) + return -1; + buf[n] = 0; + return (int)n; +} + +static void ns_link(const char *name, char *out, size_t size) +{ + char path[64]; + snprintf(path, sizeof path, "/proc/self/ns/%s", name); + ssize_t n = readlink(path, out, size - 1); + out[n > 0 ? n : 0] = 0; +} + +static uid_t outer_uid; +static gid_t outer_gid; + +/* Enters a new user namespace (plus `more`) as its root. */ +static int become_root(int more) +{ + if (unshare(CLONE_NEWUSER | more) != 0) + return -1; + char line[64]; + snprintf(line, sizeof line, "0 %u 1", (unsigned)outer_uid); + if (write_file("/proc/self/uid_map", line) != 0) + return -1; + if (write_file("/proc/self/setgroups", "deny") != 0) + return -1; + snprintf(line, sizeof line, "0 %u 1", (unsigned)outer_gid); + return write_file("/proc/self/gid_map", line); +} + +static int in_child(void (*fn)(void)) +{ + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { + fn(); + fflush(stdout); + _exit(failures ? 1 : 0); + } + int status; + if (waitpid(pid, &status, 0) != pid) + return -1; + return status; +} + +static int child_ok(int status) +{ + return WIFEXITED(status) && WEXITSTATUS(status) == 0; +} + +static char outer_host[65]; + +static void uts_child(void) +{ + char before[64], after[64]; + struct utsname u; + ns_link("uts", before, sizeof before); + CHECK(strncmp(before, "uts:[", 5) == 0); + CHECK(unshare(CLONE_NEWUSER) == 0); + /* The UTS namespace still belongs to the initial user namespace. */ + CHECK(sethostname("x", 1) == -1 && errno == EPERM); + CHECK(unshare(CLONE_NEWUTS) == 0); + ns_link("uts", after, sizeof after); + CHECK(strncmp(after, "uts:[", 5) == 0 && strcmp(before, after) != 0); + CHECK(uname(&u) == 0 && strcmp(u.nodename, outer_host) == 0); + CHECK(sethostname("segos-uts", 9) == 0); + CHECK(uname(&u) == 0 && strcmp(u.nodename, "segos-uts") == 0); + CHECK(gethostname(buf, sizeof buf) == 0 && strcmp(buf, "segos-uts") == 0); + CHECK(read_file("/proc/sys/kernel/hostname") > 0 && + strcmp(buf, "segos-uts\n") == 0); + CHECK(setdomainname("example.org", 11) == 0); + CHECK(uname(&u) == 0 && strcmp(u.domainname, "example.org") == 0); + CHECK(read_file("/proc/sys/kernel/domainname") > 0 && + strcmp(buf, "example.org\n") == 0); + /* Exactly 64 bytes is the most. */ + char long_name[66]; + memset(long_name, 'h', sizeof long_name); + CHECK(sethostname(long_name, 65) == -1 && errno == EINVAL); + CHECK(sethostname(long_name, 64) == 0); + CHECK(uname(&u) == 0 && strlen(u.nodename) == 64); + CHECK(sethostname("short", 5) == 0); + CHECK(uname(&u) == 0 && strcmp(u.nodename, "short") == 0); + CHECK(read_file("/proc/sys/kernel/ostype") > 0 && + strcmp(buf, "Linux\n") == 0); + CHECK(uname(&u) == 0 && read_file("/proc/sys/kernel/osrelease") > 0 && + strncmp(buf, u.release, strlen(u.release)) == 0); +} + +static void uts(void) +{ + struct utsname u; + CHECK(uname(&u) == 0 && strlen(u.nodename) > 0); + strcpy(outer_host, u.nodename); + CHECK(child_ok(in_child(uts_child))); + /* The parent's names did not change. */ + CHECK(uname(&u) == 0 && strcmp(u.nodename, outer_host) == 0); +} + +static int in_child_ns(void); + +static sigjmp_buf jump; + +static void on_segv(int sig) +{ + (void)sig; + siglongjmp(jump, 1); +} + +static unsigned long nattch(int id) +{ + struct shmid_ds ds; + return shmctl(id, IPC_STAT, &ds) == 0 ? ds.shm_nattch : 999; +} + +static void shm_child(void) +{ + char before[64], after[64]; + ns_link("ipc", before, sizeof before); + CHECK(become_root(CLONE_NEWIPC) == 0); + ns_link("ipc", after, sizeof after); + CHECK(strncmp(after, "ipc:[", 5) == 0 && strcmp(before, after) != 0); + CHECK(syscall(SYS_clone, CLONE_NEWIPC | CLONE_SYSVSEM | SIGCHLD, 0, 0, + 0, 0) == -1 && + errno == EINVAL); + + /* A new namespace has no segments; ids start at 0. */ + struct shm_info info; + CHECK(shmctl(0, SHM_INFO, (struct shmid_ds *)&info) == 0 && + info.used_ids == 0); + CHECK(shmget(0x5e605, 4096, 0600) == -1 && errno == ENOENT); + CHECK(shmget(IPC_PRIVATE, 0, IPC_CREAT | 0600) == -1 && + errno == EINVAL); + int id = shmget(0x5e605, 10000, IPC_CREAT | 0600); + CHECK(id == 0); + CHECK(shmget(0x5e605, 4096, 0600) == id); + CHECK(shmget(0x5e605, 20000, 0600) == -1 && errno == EINVAL); + CHECK(shmget(0x5e605, 4096, IPC_CREAT | IPC_EXCL | 0600) == -1 && + errno == EEXIST); + int priv = shmget(IPC_PRIVATE, 4096, IPC_CREAT | 0640); + CHECK(priv == 1); + CHECK(shmget(IPC_PRIVATE, 4096, 0600) != priv); + + struct shmid_ds ds; + CHECK(shmctl(id, IPC_STAT, &ds) == 0 && ds.shm_segsz == 10000 && + ds.shm_perm.__key == 0x5e605 && (ds.shm_perm.mode & 0777) == 0600 && + ds.shm_perm.uid == 0 && ds.shm_perm.cuid == 0 && + ds.shm_nattch == 0 && ds.shm_cpid == getpid() && + ds.shm_lpid == 0 && ds.shm_atime == 0 && ds.shm_ctime > 0); + CHECK(shmctl(12345, IPC_STAT, &ds) == -1 && errno == EINVAL); + CHECK(shmctl(id, 999, &ds) == -1 && errno == EINVAL); + + /* Attach anywhere: zeroed memory, rounded up to pages. */ + char *p = shmat(id, NULL, 0); + CHECK(p != (void *)-1 && ((uintptr_t)p & 4095) == 0); + CHECK(p[0] == 0 && p[9999] == 0 && p[12287] == 0); + strcpy(p, "hello"); + CHECK(nattch(id) == 1); + CHECK(shmctl(id, IPC_STAT, &ds) == 0 && ds.shm_lpid == getpid() && + ds.shm_atime > 0); + + /* A second attach sees the same memory. */ + char *q = shmat(id, NULL, 0); + CHECK(q != (void *)-1 && q != p && strcmp(q, "hello") == 0); + q[0] = 'j'; + CHECK(strcmp(p, "jello") == 0 && nattch(id) == 2); + + /* /proc/self/maps names it as Linux does. */ + FILE *maps = fopen("/proc/self/maps", "r"); + int named = 0; + while (maps && fgets(buf, sizeof buf, maps)) + if (strstr(buf, "/SYSV0005e605 (deleted)")) + named++; + if (maps) + fclose(maps); + CHECK(named == 2); + CHECK(shmdt(q) == 0 && nattch(id) == 1); + CHECK(shmdt(q) == -1 && errno == EINVAL); + CHECK(shmdt(p + 4096) == -1 && errno == EINVAL); + + /* A fork shares the attachment (and adds to the count); its writes + * show in the parent; its exit takes its attach away. */ + int ready[2], go[2]; + CHECK(pipe(ready) == 0 && pipe(go) == 0); + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { + char c; + strcpy(p, "from the child"); + write(ready[1], "r", 1); + read(go[0], &c, 1); + _exit(0); + } + char c; + CHECK(read(ready[0], &c, 1) == 1 && strcmp(p, "from the child") == 0); + CHECK(nattch(id) == 2); + CHECK(write(go[1], "g", 1) == 1); + int status; + CHECK(waitpid(pid, &status, 0) == pid && WIFEXITED(status)); + CHECK(nattch(id) == 1); + CHECK(shmdt(p) == 0 && nattch(id) == 0); + CHECK(shmctl(id, IPC_STAT, &ds) == 0 && ds.shm_dtime > 0); + + /* At a given address: aligned, rounded with SHM_RND, never over + * another mapping unless SHM_REMAP. */ + char *area = mmap(NULL, 8 * 4096, PROT_NONE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + CHECK(area != MAP_FAILED && munmap(area, 8 * 4096) == 0); + CHECK(shmat(id, area + 1, 0) == (void *)-1 && errno == EINVAL); + CHECK(shmat(id, area + 1, SHM_RND) == area); + CHECK(strcmp(area, "from the child") == 0); + CHECK(shmat(id, area, 0) == (void *)-1 && errno == EINVAL); + CHECK(shmat(id, area, SHM_REMAP) == area && nattch(id) == 1); + CHECK(shmat(id, NULL, SHM_REMAP) == (void *)-1 && errno == EINVAL); + CHECK(shmdt(area) == 0); + + /* Read-only: a write is SIGSEGV. */ + char *ro = shmat(id, NULL, SHM_RDONLY); + CHECK(ro != (void *)-1 && strcmp(ro, "from the child") == 0); + signal(SIGSEGV, on_segv); + int faulted = 0; + if (sigsetjmp(jump, 1) == 0) + *(volatile char *)ro = 'x'; + else + faulted = 1; + signal(SIGSEGV, SIG_DFL); + CHECK(faulted == 1); + CHECK(shmdt(ro) == 0); + + /* IPC_SET changes the mode (and keeps the owner); IPC_INFO and + * SHM_INFO count what there is. */ + CHECK(shmctl(id, IPC_STAT, &ds) == 0); + ds.shm_perm.mode = 0644; + CHECK(shmctl(id, IPC_SET, &ds) == 0); + CHECK(shmctl(id, IPC_STAT, &ds) == 0 && + (ds.shm_perm.mode & 0777) == 0644); + ds.shm_perm.uid = 12345; /* not mapped here */ + CHECK(shmctl(id, IPC_SET, &ds) == -1 && errno == EINVAL); + struct shminfo limits; + CHECK(shmctl(0, IPC_INFO, (struct shmid_ds *)&limits) >= 1 && + limits.shmmni == 4096 && limits.shmmin == 1 && + limits.shmmax >= 0x7fffffff); + CHECK(shmctl(0, SHM_INFO, (struct shmid_ds *)&info) >= 1 && + info.used_ids == 3 && info.shm_tot >= 5); + CHECK(shmctl(1, SHM_STAT, &ds) == priv && + (ds.shm_perm.mode & 0777) == 0640); + + /* IPC_RMID while attached: the key is free at once, the memory + * stays until the last detach, then the id is gone. */ + p = shmat(id, NULL, 0); + CHECK(p != (void *)-1); + CHECK(shmctl(id, IPC_RMID, NULL) == 0); + CHECK(shmget(0x5e605, 4096, 0600) == -1 && errno == ENOENT); + CHECK(shmctl(id, IPC_STAT, &ds) == 0 && ds.shm_perm.__key == 0 && + (ds.shm_perm.mode & SHM_DEST) && ds.shm_nattch == 1); + CHECK(strcmp(p, "from the child") == 0); + CHECK(shmdt(p) == 0); + CHECK(shmctl(id, IPC_STAT, &ds) == -1 && errno == EINVAL); + int fresh = shmget(0x5e605, 4096, IPC_CREAT | IPC_EXCL | 0600); + /* Indexes are handed out cyclically: the next after the last. */ + CHECK(fresh == 3); + /* Removed and unattached: gone at once. */ + CHECK(shmctl(fresh, IPC_RMID, NULL) == 0); + CHECK(shmctl(fresh, IPC_STAT, &ds) == -1 && errno == EINVAL); + + /* A segment of a namespace is invisible outside it. */ + char line[64]; + snprintf(line, sizeof line, "%10d %10d %4o %21d", 0, priv, 0640, 4096); + CHECK(read_file("/proc/sysvipc/shm") > 0 && + strncmp(buf, " key shmid perms", 27) == 0 && + strstr(buf, line) != NULL); + CHECK(child_ok(in_child_ns())); +} + +/* In yet another IPC namespace: none of the parent's segments. */ +static void other_ns(void) +{ + struct shmid_ds ds; + struct shm_info info; + CHECK(unshare(CLONE_NEWIPC) == 0); + CHECK(shmctl(1, IPC_STAT, &ds) == -1 && errno == EINVAL); + CHECK(shmctl(0, SHM_INFO, (struct shmid_ds *)&info) == 0 && + info.used_ids == 0); + CHECK(shmget(IPC_PRIVATE, 4096, IPC_CREAT | 0600) == 0); +} + +static int in_child_ns(void) +{ + return in_child(other_ns); +} + +int main(void) +{ + setvbuf(stdout, NULL, _IONBF, 0); + outer_uid = getuid(); + outer_gid = getgid(); + section("uts namespace"); + uts(); + section("ipc namespace and shared memory"); + CHECK(child_ok(in_child(shm_child))); + if (failures) { + printf("FAILED (%d)\n", failures); + return 1; + } + printf("PASSED\n"); + return 0; +} diff --git a/userland/tests/sysvipc.expected b/userland/tests/sysvipc.expected new file mode 100644 index 0000000..92acf8c --- /dev/null +++ b/userland/tests/sysvipc.expected @@ -0,0 +1,94 @@ +# uts namespace +ok uname(&u) == 0 && strlen(u.nodename) > 0 +ok strncmp(before, "uts:[", 5) == 0 +ok unshare(CLONE_NEWUSER) == 0 +ok sethostname("x", 1) == -1 && errno == EPERM +ok unshare(CLONE_NEWUTS) == 0 +ok strncmp(after, "uts:[", 5) == 0 && strcmp(before, after) != 0 +ok uname(&u) == 0 && strcmp(u.nodename, outer_host) == 0 +ok sethostname("segos-uts", 9) == 0 +ok uname(&u) == 0 && strcmp(u.nodename, "segos-uts") == 0 +ok gethostname(buf, sizeof buf) == 0 && strcmp(buf, "segos-uts") == 0 +ok read_file("/proc/sys/kernel/hostname") > 0 && strcmp(buf, "segos-uts\n") == 0 +ok setdomainname("example.org", 11) == 0 +ok uname(&u) == 0 && strcmp(u.domainname, "example.org") == 0 +ok read_file("/proc/sys/kernel/domainname") > 0 && strcmp(buf, "example.org\n") == 0 +ok sethostname(long_name, 65) == -1 && errno == EINVAL +ok sethostname(long_name, 64) == 0 +ok uname(&u) == 0 && strlen(u.nodename) == 64 +ok sethostname("short", 5) == 0 +ok uname(&u) == 0 && strcmp(u.nodename, "short") == 0 +ok read_file("/proc/sys/kernel/ostype") > 0 && strcmp(buf, "Linux\n") == 0 +ok uname(&u) == 0 && read_file("/proc/sys/kernel/osrelease") > 0 && strncmp(buf, u.release, strlen(u.release)) == 0 +ok child_ok(in_child(uts_child)) +ok uname(&u) == 0 && strcmp(u.nodename, outer_host) == 0 +# ipc namespace and shared memory +ok become_root(CLONE_NEWIPC) == 0 +ok strncmp(after, "ipc:[", 5) == 0 && strcmp(before, after) != 0 +ok syscall(SYS_clone, CLONE_NEWIPC | CLONE_SYSVSEM | SIGCHLD, 0, 0, 0, 0) == -1 && errno == EINVAL +ok shmctl(0, SHM_INFO, (struct shmid_ds *)&info) == 0 && info.used_ids == 0 +ok shmget(0x5e605, 4096, 0600) == -1 && errno == ENOENT +ok shmget(IPC_PRIVATE, 0, IPC_CREAT | 0600) == -1 && errno == EINVAL +ok id == 0 +ok shmget(0x5e605, 4096, 0600) == id +ok shmget(0x5e605, 20000, 0600) == -1 && errno == EINVAL +ok shmget(0x5e605, 4096, IPC_CREAT | IPC_EXCL | 0600) == -1 && errno == EEXIST +ok priv == 1 +ok shmget(IPC_PRIVATE, 4096, 0600) != priv +ok shmctl(id, IPC_STAT, &ds) == 0 && ds.shm_segsz == 10000 && ds.shm_perm.__key == 0x5e605 && (ds.shm_perm.mode & 0777) == 0600 && ds.shm_perm.uid == 0 && ds.shm_perm.cuid == 0 && ds.shm_nattch == 0 && ds.shm_cpid == getpid() && ds.shm_lpid == 0 && ds.shm_atime == 0 && ds.shm_ctime > 0 +ok shmctl(12345, IPC_STAT, &ds) == -1 && errno == EINVAL +ok shmctl(id, 999, &ds) == -1 && errno == EINVAL +ok p != (void *)-1 && ((uintptr_t)p & 4095) == 0 +ok p[0] == 0 && p[9999] == 0 && p[12287] == 0 +ok nattch(id) == 1 +ok shmctl(id, IPC_STAT, &ds) == 0 && ds.shm_lpid == getpid() && ds.shm_atime > 0 +ok q != (void *)-1 && q != p && strcmp(q, "hello") == 0 +ok strcmp(p, "jello") == 0 && nattch(id) == 2 +ok named == 2 +ok shmdt(q) == 0 && nattch(id) == 1 +ok shmdt(q) == -1 && errno == EINVAL +ok shmdt(p + 4096) == -1 && errno == EINVAL +ok pipe(ready) == 0 && pipe(go) == 0 +ok read(ready[0], &c, 1) == 1 && strcmp(p, "from the child") == 0 +ok nattch(id) == 2 +ok write(go[1], "g", 1) == 1 +ok waitpid(pid, &status, 0) == pid && WIFEXITED(status) +ok nattch(id) == 1 +ok shmdt(p) == 0 && nattch(id) == 0 +ok shmctl(id, IPC_STAT, &ds) == 0 && ds.shm_dtime > 0 +ok area != MAP_FAILED && munmap(area, 8 * 4096) == 0 +ok shmat(id, area + 1, 0) == (void *)-1 && errno == EINVAL +ok shmat(id, area + 1, SHM_RND) == area +ok strcmp(area, "from the child") == 0 +ok shmat(id, area, 0) == (void *)-1 && errno == EINVAL +ok shmat(id, area, SHM_REMAP) == area && nattch(id) == 1 +ok shmat(id, NULL, SHM_REMAP) == (void *)-1 && errno == EINVAL +ok shmdt(area) == 0 +ok ro != (void *)-1 && strcmp(ro, "from the child") == 0 +ok faulted == 1 +ok shmdt(ro) == 0 +ok shmctl(id, IPC_STAT, &ds) == 0 +ok shmctl(id, IPC_SET, &ds) == 0 +ok shmctl(id, IPC_STAT, &ds) == 0 && (ds.shm_perm.mode & 0777) == 0644 +ok shmctl(id, IPC_SET, &ds) == -1 && errno == EINVAL +ok shmctl(0, IPC_INFO, (struct shmid_ds *)&limits) >= 1 && limits.shmmni == 4096 && limits.shmmin == 1 && limits.shmmax >= 0x7fffffff +ok shmctl(0, SHM_INFO, (struct shmid_ds *)&info) >= 1 && info.used_ids == 3 && info.shm_tot >= 5 +ok shmctl(1, SHM_STAT, &ds) == priv && (ds.shm_perm.mode & 0777) == 0640 +ok p != (void *)-1 +ok shmctl(id, IPC_RMID, NULL) == 0 +ok shmget(0x5e605, 4096, 0600) == -1 && errno == ENOENT +ok shmctl(id, IPC_STAT, &ds) == 0 && ds.shm_perm.__key == 0 && (ds.shm_perm.mode & SHM_DEST) && ds.shm_nattch == 1 +ok strcmp(p, "from the child") == 0 +ok shmdt(p) == 0 +ok shmctl(id, IPC_STAT, &ds) == -1 && errno == EINVAL +ok fresh == 3 +ok shmctl(fresh, IPC_RMID, NULL) == 0 +ok shmctl(fresh, IPC_STAT, &ds) == -1 && errno == EINVAL +ok read_file("/proc/sysvipc/shm") > 0 && strncmp(buf, " key shmid perms", 27) == 0 && strstr(buf, line) != NULL +ok unshare(CLONE_NEWIPC) == 0 +ok shmctl(1, IPC_STAT, &ds) == -1 && errno == EINVAL +ok shmctl(0, SHM_INFO, (struct shmid_ds *)&info) == 0 && info.used_ids == 0 +ok shmget(IPC_PRIVATE, 4096, IPC_CREAT | 0600) == 0 +ok child_ok(in_child_ns()) +ok child_ok(in_child(shm_child)) +PASSED diff --git a/xtask/src/main.rs b/xtask/src/main.rs index d52ddcf..4065527 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -663,7 +663,7 @@ fn shell_session(img: &Path) -> Result<(), String> { ("echo SEGOS-$((6 * 7))-OK", "SEGOS-42-OK"), ( "ls /tests | grep expected | wc -l | sed 's/^/COUNT=/'", - "COUNT=10", + "COUNT=11", ), ("hello | tr a-z A-Z", "HELLO, WORLD!"), ("cat /proc/self/comm | tr a-z A-Z", "CAT"), @@ -743,6 +743,19 @@ fn shell_session(img: &Path) -> Result<(), String> { "GCC-42", )); } + // Phase 8: a UTS namespace of its own (BusyBox's unshare and + // hostname: the name changes inside only), and System V shared memory + // through glibc (two attaches of one segment, from Python's ctypes). + steps.push(( + "echo \"UTS-$(unshare -r -u sh -c 'hostname inner; hostname')-$(hostname)\"", + "UTS-inner-segos", + )); + if rootfs.join("python3").exists() { + steps.push(( + "python3 -c \"import ctypes as c; l=c.CDLL(None); l.shmat.restype=c.c_void_p; i=l.shmget(0,4096,0o1600); p=l.shmat(i,None,0); c.memmove(p,b'SYSV-42',8); q=l.shmat(i,None,0); s=c.string_at(q).decode(); l.shmdt(c.c_void_p(p)); l.shmdt(c.c_void_p(q)); print(s+'-'+str(l.shmctl(i,0,None)))\"", + "SYSV-42-0", + )); + } // Phase 8: POSIX shared memory in /dev/shm, fontconfig, and a D-Bus // session bus answering a call. if rootfs.join("dbus-daemon").exists() {