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
99 changes: 71 additions & 28 deletions crates/kernel/src/fork_dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@
//! immediately. Writes the exit code (shifted left 8) to the user `*wstatus`
//! pointer if non-null.
//!
//! * `sys_execve` — path-validated in-kernel exec. Only `"/bin/sh"` is
//! recognized. A new [`UserAddressSpace`] is allocated, the embedded shell
//! ELF is loaded into it, the calling thread's previous address space is
//! released, and the SYSCALL epilogue is redirected to the new entry point.
//! * `sys_execve` — path-validated in-kernel exec. VFS is consulted first,
//! with an embedded compatibility fallback only when the path is absent. A
//! new [`UserAddressSpace`] is allocated, the ELF is loaded, the previous
//! address space is released, and the SYSCALL epilogue is redirected to the
//! new entry point.
//! argv/envp are read from user space and laid out on the System V AMD64
//! initial stack at user VA 0x5FF000.
//!
Expand All @@ -45,10 +46,12 @@

use oncrix_hal::arch::uart::{COM1, Uart16550};
use oncrix_hal::serial::SerialPort;
use oncrix_lib::Error;
use oncrix_process::pid::{Pid, alloc_pid};
use oncrix_process::process::Process;
use oncrix_process::signal::Signal;
use oncrix_process::table::{ExitStatus, ProcessEntry, ProcessTable};
use oncrix_vfs::cred_check::VfsCred;

use crate::arch::clone::ForkSnapshot;
use crate::arch::sched_glue::read_cr3;
Expand Down Expand Up @@ -596,6 +599,8 @@ const MAX_ARGV: usize = 64;
/// Maximum bytes copied per argv/envp string.
const MAX_ARG_STR: usize = 256;

const BIN_PREFIX_LEN: usize = 5;

/// Kernel handler for `SYS_EXECVE`.
///
/// POSIX.1-2024 `execve(3p)` semantics:
Expand All @@ -604,13 +609,14 @@ const MAX_ARG_STR: usize = 256;
/// overwriting the saved user RIP / RSP / RFLAGS atomics.
/// - On failure: returns a negative errno; the caller continues normally.
///
/// # Phase 13 implementation
/// # Phase 24 implementation
///
/// Only `"/bin/sh"` is recognized. A fresh [`UserAddressSpace`] is
/// allocated via [`crate::frame_alloc`], the embedded `/bin/sh` ELF is
/// loaded into it, the calling thread's previous address space is
/// `release`d (so its frames return to the global pool), and the new
/// UAS is installed both on the thread and at `PD_0_1G[2]`. argv and
/// The executable image is read from VFS first, with an embedded compatibility
/// fallback only when the path is absent. A fresh [`UserAddressSpace`] is
/// allocated via [`crate::frame_alloc`], the ELF is loaded into it, and the
/// calling thread's previous address space is `release`d so its frames return
/// to the global pool. The new UAS is installed both on the thread and at
/// `PD_0_1G[2]`. argv and
/// envp are read from user space and written to the System V AMD64
/// initial stack at the top 4 KiB of the user region (user VA 0x5FF000).
/// The SYSCALL epilogue is redirected to the new entry point with
Expand All @@ -635,20 +641,48 @@ pub unsafe fn sys_execve(pathname_ptr: u64, argv_ptr: u64, envp_ptr: u64) -> i64
Some(s) => s,
None => return -22, // EINVAL — too long or non-ASCII
};
if path.is_empty() {
return -2;
}

// Resolve `path` against the embedded binary set. Phase 23
// recognises `/bin/{sh,echo,cat,true,false}` plus the matching
// bare names (a primitive `$PATH=/bin` shortcut).
let elf_bytes = match crate::arch::init_embed::embedded_lookup(path) {
Some(bytes) => bytes,
None => {
let _ = serial.write_str("[exec] path not in embedded set: ");
for &b in path {
let _ = serial.write_byte(b);
let mut path_buf = [0u8; MAX_PATHNAME + BIN_PREFIX_LEN];
let vfs_path = if path.contains(&b'/') {
path
} else {
path_buf[..BIN_PREFIX_LEN].copy_from_slice(b"/bin/");
path_buf[BIN_PREFIX_LEN..BIN_PREFIX_LEN + path.len()].copy_from_slice(path);
&path_buf[..BIN_PREFIX_LEN + path.len()]
};
let vfs_image = match crate::state::with_global(|state| {
state.vfs.read_executable_bytes(
vfs_path,
&VfsCred::root(),
oncrix_mm::address_space::USER_REGION_SIZE,
)
}) {
Some(Ok(image)) => Some(image),
Some(Err(Error::NotFound)) => None,
Some(Err(Error::PermissionDenied)) => return -13,
Some(Err(Error::OutOfMemory)) => return -12,
Some(Err(Error::InvalidArgument)) => return -22,
Some(Err(Error::Busy)) => return -16,
Some(Err(Error::WouldBlock)) => return -11,
Some(Err(Error::Interrupted)) => return -4,
Some(Err(Error::NotImplemented)) => return -38,
Some(Err(Error::AlreadyExists)) => return -17,
Some(Err(Error::IoError)) | None => return -5,
};
let elf_bytes = match vfs_image.as_deref() {
Some(image) => image,
None => match crate::arch::init_embed::embedded_lookup(path) {
Some(bytes) => bytes,
None => {
let _ = serial.write_str("[exec] path not found: ");
write_exec_path(&mut serial, path);
let _ = serial.write_str("\n");
return -2;
}
let _ = serial.write_str("\n");
return -2; // ENOENT
}
},
};

// Snapshot argv/envp from the CALLING process's address space
Expand Down Expand Up @@ -699,9 +733,7 @@ pub unsafe fn sys_execve(pathname_ptr: u64, argv_ptr: u64, envp_ptr: u64) -> i64
match new_uas.map_elf_segments(elf_bytes) {
Ok(e) => {
let _ = serial.write_str("[exec] loaded ");
for &b in path {
let _ = serial.write_byte(b);
}
write_exec_path(&mut serial, path);
let _ = serial.write_str(" at entry=0x");
write_hex(&mut serial, e);
let _ = serial.write_str("\n");
Expand Down Expand Up @@ -737,9 +769,7 @@ pub unsafe fn sys_execve(pathname_ptr: u64, argv_ptr: u64, envp_ptr: u64) -> i64
}
Err(_) => {
let _ = serial.write_str("[exec] ELF parse/load failed for ");
for &b in path {
let _ = serial.write_byte(b);
}
write_exec_path(&mut serial, path);
let _ = serial.write_str("\n");
new_uas.release(alloc);
return -8; // ENOEXEC
Expand Down Expand Up @@ -856,6 +886,12 @@ pub unsafe fn sys_execve(pathname_ptr: u64, argv_ptr: u64, envp_ptr: u64) -> i64
set_saved_user_rsp(0x5FF000);
set_saved_user_rflags(DEFAULT_USER_RFLAGS);

if vfs_image.is_some() {
let _ = serial.write_str("[exec] loaded VFS image ");
write_exec_path(&mut serial, vfs_path);
let _ = serial.write_str("\n");
}

// Return 0 — the SYSCALL epilogue will sysretq into sh's _start.
0
}
Expand Down Expand Up @@ -905,6 +941,13 @@ unsafe fn collect_user_argv(
count
}

fn write_exec_path(serial: &mut Uart16550, path: &[u8]) {
for &b in path {
let out = if b < 0x20 || b == 0x7F { b'?' } else { b };
let _ = serial.write_byte(out);
}
}

/// Write a 64-bit value as `0x`-prefixed hex to the serial console.
fn write_hex(serial: &mut Uart16550, value: u64) {
let mut buf = [0u8; 16];
Expand Down
9 changes: 8 additions & 1 deletion crates/kernel/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl KernelState {
/// directories.
///
/// Creates a ramfs root and populates it with `/dev`, `/proc`,
/// `/tmp`, `/sbin`, and `/etc` (which contains `/etc/motd`).
/// `/tmp`, `/bin`, `/sbin`, and `/etc` (which contains `/etc/motd`).
pub fn init_rootfs(&mut self) -> oncrix_lib::Result<()> {
let root_ino = self.vfs.ramfs.root_inode();
let root_sb = Superblock::new(FsType::Ramfs, root_ino);
Expand All @@ -150,8 +150,15 @@ impl KernelState {

let _ = self.vfs.ramfs.mkdir(&root, "proc", FileMode::DIR_DEFAULT);
let _ = self.vfs.ramfs.mkdir(&root, "tmp", FileMode::DIR_DEFAULT);
let bin = self.vfs.ramfs.mkdir(&root, "bin", FileMode::DIR_DEFAULT)?;
let _ = self.vfs.ramfs.mkdir(&root, "sbin", FileMode::DIR_DEFAULT);

if let Some(shell) = crate::arch::init_embed::embedded_lookup(b"/bin/sh") {
self.vfs
.ramfs
.create_static_file(&bin, "sh", FileMode(0o555), shell)?;
}

// /etc and /etc/motd
let etc = self.vfs.ramfs.mkdir(&root, "etc", FileMode::DIR_DEFAULT)?;
let motd_content = b"Welcome to ONCRIX (Phase 15)\n";
Expand Down
52 changes: 46 additions & 6 deletions crates/mm/src/address_space/elf_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,18 @@ pub fn load_elf_into(elf_bytes: &[u8], dst: &mut [u8]) -> Result<ElfLoadInfo> {
if header.e_type != ET_EXEC && header.e_type != ET_DYN {
return Err(Error::InvalidArgument);
}
if header.e_ident[6] != 1 || header.e_version != 1 {
return Err(Error::InvalidArgument);
}
if usize::from(header.e_ehsize) != core::mem::size_of::<Elf64Header>()
|| usize::from(header.e_phentsize) != core::mem::size_of::<Elf64Phdr>()
{
return Err(Error::InvalidArgument);
}

let ph_offset = header.e_phoff as usize;
let ph_size = header.e_phentsize as usize;
let ph_count = header.e_phnum as usize;
let ph_offset = usize::try_from(header.e_phoff).map_err(|_| Error::InvalidArgument)?;
let ph_size = usize::from(header.e_phentsize);
let ph_count = usize::from(header.e_phnum);

let ph_end = ph_size
.checked_mul(ph_count)
Expand Down Expand Up @@ -294,10 +302,42 @@ fn read_phdr(elf_bytes: &[u8], ph_offset: usize, ph_size: usize, i: usize) -> Re
let offset = ph_offset
.checked_add(i.checked_mul(ph_size).ok_or(Error::InvalidArgument)?)
.ok_or(Error::InvalidArgument)?;
if offset.checked_add(ph_size).ok_or(Error::InvalidArgument)? > elf_bytes.len() {
let read_end = offset
.checked_add(core::mem::size_of::<Elf64Phdr>())
.ok_or(Error::InvalidArgument)?;
if read_end > elf_bytes.len() {
return Err(Error::InvalidArgument);
}
// SAFETY: Bounds checked above (offset + ph_size <= elf_bytes.len()).
// `read_unaligned` handles potentially unaligned input.
// SAFETY: Bounds checked above: offset + size_of::<Elf64Phdr>() <=
// elf_bytes.len(). `read_unaligned` handles potentially unaligned input.
Ok(unsafe { core::ptr::read_unaligned(elf_bytes.as_ptr().add(offset) as *const Elf64Phdr) })
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn malformed_short_program_header_entry_returns_invalid_argument() {
// Given
let mut elf = [0u8; 64];
elf[..4].copy_from_slice(&ELF_MAGIC);
elf[4] = ELFCLASS64;
elf[5] = ELFDATA2LSB;
elf[6] = 1;
elf[16..18].copy_from_slice(&ET_EXEC.to_le_bytes());
elf[18..20].copy_from_slice(&EM_X86_64.to_le_bytes());
elf[20..24].copy_from_slice(&1u32.to_le_bytes());
elf[32..40].copy_from_slice(&63u64.to_le_bytes());
elf[52..54].copy_from_slice(&64u16.to_le_bytes());
elf[54..56].copy_from_slice(&1u16.to_le_bytes());
elf[56..58].copy_from_slice(&1u16.to_le_bytes());
let mut dst = [0u8; 1];

// When
let result = load_elf_into(&elf, &mut dst);

// Then
assert!(matches!(result, Err(Error::InvalidArgument)));
}
}
40 changes: 40 additions & 0 deletions crates/vfs/src/kernel_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ extern crate alloc;
use alloc::vec;
use alloc::vec::Vec;

use crate::cred_check::{AccessResult, VfsCred, check_exec_access};
use crate::dentry::{Dentry, DentryCache, DentryName};
use crate::file::OpenFlags;
use crate::inode::{FileMode, FileType, Inode, InodeNumber, InodeOps};
Expand Down Expand Up @@ -561,6 +562,45 @@ impl KernelVfs {
Ok(buf)
}

/// Read a bounded regular executable file into owned memory.
///
/// The inode must be regular, executable by `cred`, and no larger than
/// `max_bytes`. Short reads are rejected rather than returning a partial
/// executable image.
pub fn read_executable_bytes(
&self,
path: &[u8],
cred: &VfsCred,
max_bytes: usize,
) -> Result<Vec<u8>> {
let inode = self.lookup_path(path)?;
if inode.file_type != FileType::Regular
|| check_exec_access(cred, inode.uid, inode.gid, inode.mode.0) != AccessResult::Granted
{
return Err(Error::PermissionDenied);
}
let size = usize::try_from(inode.size).map_err(|_| Error::OutOfMemory)?;
if size > max_bytes {
return Err(Error::OutOfMemory);
}
let mut image = Vec::new();
image
.try_reserve_exact(size)
.map_err(|_| Error::OutOfMemory)?;
image.resize(size, 0);
let mut offset = 0;
while offset < size {
let count = self
.ramfs
.read(&inode, offset as u64, &mut image[offset..])?;
if count == 0 {
return Err(Error::IoError);
}
offset += count;
}
Ok(image)
}

/// Read a `/proc/<name>` virtual file by name.
///
/// Resolves the name against the procfs entry table, generates
Expand Down
Loading