use crate::fs::file::File;
use crate::fs::pipe;
use crate::fs::vfs;
use crate::process;
use crate::process::ProcessId;
use crate::serial_print;
use crate::serial_println;
use alloc::string::String;
use alloc::vec::Vec;
use spin::Mutex;
fn console_getchar() -> Option<u8> {
let ret: isize;
unsafe {
core::arch::asm!(
"li a7, 2",
"ecall",
"mv {}, a0",
out(reg) ret,
options(nostack)
);
}
if ret >= 0 {
Some(ret as u8)
} else {
None
}
}
fn read_line() -> String {
let mut buf = String::new();
loop {
let mut ch = console_getchar();
if ch.is_none() {
ch = crate::task::keyboard::try_pop_char();
}
if let Some(c) = ch {
match c {
b'\r' | b'\n' => {
serial_println!();
return buf;
}
0x08 | 0x7f => {
if !buf.is_empty() {
buf.pop();
serial_print!("\x08 \x08");
}
}
0x20..=0x7e => {
buf.push(c as char);
serial_print!("{}", c as char);
}
_ => {}
}
} else {
riscv::asm::wfi();
}
}
}
fn tokenize(line: &str) -> Vec<&str> {
line.split_whitespace().collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Redirect<'a> {
path: &'a str,
append: bool,
}
#[derive(Debug, PartialEq, Eq)]
struct CommandPlan<'a> {
argv: Vec<&'a str>,
stdin: Option<&'a str>,
stdout: Option<Redirect<'a>>,
background: bool,
}
fn parse_command_plan<'a>(tokens: &[&'a str]) -> Result<CommandPlan<'a>, &'static str> {
let mut argv = Vec::new();
let mut stdin = None;
let mut stdout = None;
let mut background = false;
let mut i = 0usize;
while i < tokens.len() {
match tokens[i] {
"<" => {
i += 1;
if i >= tokens.len() {
return Err("missing input redirection target");
}
stdin = Some(tokens[i]);
}
">" | ">>" => {
let append = tokens[i] == ">>";
i += 1;
if i >= tokens.len() {
return Err("missing output redirection target");
}
stdout = Some(Redirect {
path: tokens[i],
append,
});
}
"&" => {
if i + 1 != tokens.len() {
return Err("background marker must be last");
}
background = true;
}
token => argv.push(token),
}
i += 1;
}
if argv.is_empty() {
return Err("empty command");
}
Ok(CommandPlan {
argv,
stdin,
stdout,
background,
})
}
enum ShellOutput<'a> {
Console,
File(&'a mut dyn File),
}
fn shell_write(output: &mut ShellOutput<'_>, bytes: &[u8]) -> Result<(), &'static str> {
match output {
ShellOutput::Console => {
crate::serial::write_bytes(bytes);
Ok(())
}
ShellOutput::File(file) => file.write(bytes).map(|_| ()).map_err(|_| "write failed"),
}
}
fn shell_writeln(output: &mut ShellOutput<'_>, text: &str) -> Result<(), &'static str> {
shell_write(output, text.as_bytes())?;
shell_write(output, b"\n")
}
fn open_redirect_target(
path: &str,
append: bool,
) -> Result<alloc::sync::Arc<Mutex<dyn File>>, &'static str> {
let abs_path = resolve_path(path);
if !append {
let _ = vfs::remove_file(&abs_path);
}
match vfs::open_file(&abs_path) {
Ok(file) => Ok(file),
Err(_) => vfs::create_file(&abs_path).map_err(|_| "cannot create redirection target"),
}
}
static CWD: Mutex<Option<String>> = Mutex::new(None);
fn get_cwd() -> String {
let mut guard = CWD.lock();
if guard.is_none() {
*guard = Some(String::from("/"));
}
guard.clone().unwrap()
}
fn set_cwd(path: String) {
*CWD.lock() = Some(path);
}
fn resolve_path(raw: &str) -> String {
if raw.is_empty() {
return get_cwd();
}
if raw.starts_with('/') {
String::from(raw)
} else {
let cwd = get_cwd();
if cwd == "/" {
alloc::format!("/{}", raw)
} else {
alloc::format!("{}/{}", cwd, raw)
}
}
}
fn list_dir(abs_path: &str) -> Result<Vec<String>, &'static str> {
vfs::readdir_path(abs_path).map_err(|_| "cannot access directory")
}
fn is_directory(abs_path: &str) -> bool {
match vfs::stat_path(abs_path) {
Ok(meta) => meta.file_type == crate::fs::FileType::Directory,
Err(_) => false,
}
}
fn cmd_echo(args: &[&str], output: &mut ShellOutput<'_>) {
for (i, arg) in args.iter().enumerate() {
if i > 0 {
let _ = shell_write(output, b" ");
}
let _ = shell_write(output, arg.as_bytes());
}
let _ = shell_write(output, b"\n");
}
fn cmd_pwd(output: &mut ShellOutput<'_>) {
let _ = shell_writeln(output, &get_cwd());
}
fn cmd_cd(args: &[&str]) {
let target = if args.is_empty() { "/" } else { args[0] };
let abs_path = resolve_path(target);
if is_directory(&abs_path) {
set_cwd(abs_path);
} else {
serial_println!("cd: {}: not a directory", target);
}
}
fn cmd_ls(args: &[&str], output: &mut ShellOutput<'_>) {
let target = if args.is_empty() { "." } else { args[0] };
let abs_path = resolve_path(target);
match list_dir(&abs_path) {
Ok(entries) => {
for name in &entries {
let _ = shell_writeln(output, name);
}
}
Err(e) => {
serial_println!("ls: {}: {}", target, e);
}
}
}
fn cmd_cat(args: &[&str], output: &mut ShellOutput<'_>) {
if args.is_empty() {
serial_println!("cat: missing file operand");
return;
}
for &arg in args {
let abs_path = resolve_path(arg);
match vfs::open_file(&abs_path) {
Ok(file_handle) => {
let mut buf = [0u8; 512];
loop {
match file_handle.lock().read(&mut buf) {
Ok(0) => break,
Ok(n) => {
let _ = shell_write(output, &buf[..n]);
}
Err(_) => break,
}
}
}
Err(_) => {
serial_println!("cat: {}: no such file", arg);
}
}
}
}
fn cmd_exit() -> ! {
serial_println!("Shell exiting.");
crate::hlt_loop();
}
fn cmd_mkdir(args: &[&str]) {
if args.is_empty() {
crate::println!("mkdir: missing operand");
return;
}
for &arg in args {
let abs_path = resolve_path(arg);
match vfs::create_dir(&abs_path) {
Ok(()) => crate::println!("mkdir: created '{}'", abs_path),
Err(e) => crate::println!("mkdir: {}: {}", arg, e),
}
}
}
fn cmd_rm(args: &[&str]) {
if args.is_empty() {
crate::println!("rm: missing operand");
return;
}
for &arg in args {
let abs_path = resolve_path(arg);
match crate::fs::remove_file(&abs_path) {
Ok(()) => crate::println!("rm: removed '{}'", abs_path),
Err(e) => crate::println!("rm: {}: {}", arg, e),
}
}
}
fn cmd_touch(args: &[&str]) {
if args.is_empty() {
crate::println!("touch: missing file operand");
return;
}
for &arg in args {
let abs_path = resolve_path(arg);
match vfs::open_file(&abs_path) {
Ok(_) => {}
Err(_) => match vfs::create_file(&abs_path) {
Ok(_) => crate::println!("touch: created '{}'", abs_path),
Err(e) => crate::println!("touch: {}: {}", arg, e),
},
}
}
}
fn cmd_ps() {
let sched = crate::process::SCHEDULER.lock();
serial_println!(" PID NAME STATE");
serial_println!(" ─── ────────── ─────");
for pcb in sched.all_processes() {
serial_println!(
" {:>3} {:<10} {:?}",
pcb.pid().as_usize(),
pcb.name(),
pcb.state(),
);
}
serial_println!(" ─── ────────── ─────");
}
fn cmd_jobs() {
serial_println!("jobs: full POSIX job control is not implemented");
serial_println!("jobs: external commands are queued as AhRightOS tasks; use ps to inspect them");
serial_println!("jobs: signals/fg/bg remain documented future work");
}
fn cmd_help(output: &mut ShellOutput<'_>) {
let _ = shell_writeln(output, "AhRightOS Shell — built-in commands:");
let _ = shell_writeln(output, " echo <text> Print text");
let _ = shell_writeln(output, " pwd Print working directory");
let _ = shell_writeln(output, " cd <path> Change directory");
let _ = shell_writeln(output, " ls [path] List directory");
let _ = shell_writeln(output, " cat <file> Print file contents");
let _ = shell_writeln(output, " mkdir <dir> Create directory");
let _ = shell_writeln(output, " rm <file> Remove file");
let _ = shell_writeln(output, " touch <file> Create empty file");
let _ = shell_writeln(output, " ps List processes");
let _ = shell_writeln(output, " jobs Show job-control limitation");
let _ = shell_writeln(output, " exit Halt the system");
let _ = shell_writeln(output, " help Show this message");
let _ = shell_writeln(
output,
"Redirection: >, >>, and cat < file are supported for teaching built-ins.",
);
}
fn cmd_external(name: &str, _args: &[&str]) {
let abs_path = resolve_path(name);
match vfs::open_file(&abs_path) {
Ok(file_handle) => {
let mut elf_data = alloc::vec![0u8; 65536];
let n = match file_handle.lock().read(&mut elf_data) {
Ok(n) => n,
Err(_) => {
serial_println!("{}: read error", name);
return;
}
};
if n == 0 {
serial_println!("{}: empty file", name);
return;
}
elf_data.truncate(n);
let elf = match process::elf::Elf::parse(&elf_data) {
Ok(e) => e,
Err(_) => {
serial_println!("{}: not an ELF executable", name);
return;
}
};
let kernel_paddr = match process::kernel_page_table_paddr() {
Some(paddr) => paddr,
None => {
serial_println!("{}: kernel page table root is not registered", name);
return;
}
};
let result = process::with_frame_allocator(|allocator| {
let addr_space = match process::user::create_user_address_space(
&elf,
&elf_data,
allocator,
kernel_paddr,
) {
Ok(a) => a,
Err(_) => return -1isize,
};
let new_satp = {
let ppn = addr_space.page_table_paddr().as_usize() >> 12;
(8usize << 60) | ppn
};
let user_stack_top = 0x7FFF_F000usize;
let name_static: &'static str = alloc::string::String::from(name).leak();
let user_task = process::user::create_user_task(
ProcessId::new(),
name_static,
elf.entry,
user_stack_top,
new_satp,
);
let mut sched = process::SCHEDULER.lock();
if sched.add_process(user_task).is_err() {
return -1isize;
}
0isize
});
if result < 0 {
serial_println!("{}: failed to create process", name);
}
}
Err(_) => {
serial_println!("{}: command not found", name);
}
}
}
fn run_pipe(left_tokens: &[&str], right_tokens: &[&str]) {
let (read_end, write_end) = pipe::make_pipe();
let mut write_file = write_end;
let left_cmd = left_tokens[0];
let left_args = &left_tokens[1..];
match left_cmd {
"echo" => {
for (i, arg) in left_args.iter().enumerate() {
if i > 0 {
let _ = write_file.write(b" ");
}
let _ = write_file.write(arg.as_bytes());
}
let _ = write_file.write(b"\n");
}
"ls" => {
let target = if left_args.is_empty() {
"."
} else {
left_args[0]
};
let abs_path = resolve_path(target);
if let Ok(entries) = list_dir(&abs_path) {
for name in &entries {
let _ = write_file.write(name.as_bytes());
let _ = write_file.write(b"\n");
}
}
}
"cat" => {
for &arg in left_args {
let abs_path = resolve_path(arg);
if let Ok(fh) = vfs::open_file(&abs_path) {
let mut buf = [0u8; 512];
loop {
match fh.lock().read(&mut buf) {
Ok(0) => break,
Ok(n) => {
let _ = write_file.write(&buf[..n]);
}
Err(_) => break,
}
}
}
}
}
"pwd" => {
let _ = write_file.write(get_cwd().as_bytes());
let _ = write_file.write(b"\n");
}
_ => {
serial_println!("{}: unsupported in pipe", left_cmd);
return;
}
}
drop(write_file);
let mut read_file = read_end;
let right_cmd = right_tokens[0];
let _right_args = &right_tokens[1..];
match right_cmd {
"cat" => {
let mut buf = [0u8; 512];
loop {
match read_file.read(&mut buf) {
Ok(0) => break,
Ok(n) => crate::serial::write_bytes(&buf[..n]),
Err(_) => break,
}
}
}
_ => {
serial_println!("{}: unsupported in pipe", right_cmd);
}
}
}
fn run_output_builtin(cmd: &str, args: &[&str], output: &mut ShellOutput<'_>) -> bool {
match cmd {
"echo" => cmd_echo(args, output),
"pwd" => cmd_pwd(output),
"ls" => cmd_ls(args, output),
"cat" => cmd_cat(args, output),
"help" => cmd_help(output),
_ => return false,
}
true
}
fn supports_output_redirection(cmd: &str) -> bool {
matches!(cmd, "echo" | "pwd" | "ls" | "cat" | "help")
}
fn run_command_plan(plan: &CommandPlan<'_>) {
let cmd = plan.argv[0];
let mut args = &plan.argv[1..];
let stdin_arg;
if let Some(input) = plan.stdin {
if cmd == "cat" && args.is_empty() {
stdin_arg = [input];
args = &stdin_arg;
} else {
serial_println!("shell: input redirection is currently supported only by cat");
return;
}
}
if plan.background && supports_output_redirection(cmd) {
serial_println!(
"shell: background marker ignored for built-in command '{}'",
cmd
);
}
if let Some(redirect) = plan.stdout {
if !supports_output_redirection(cmd) {
serial_println!("shell: redirection is unsupported for '{}'", cmd);
return;
}
let file_handle = match open_redirect_target(redirect.path, redirect.append) {
Ok(file) => file,
Err(e) => {
serial_println!("shell: {}: {}", redirect.path, e);
return;
}
};
let mut guard = file_handle.lock();
if redirect.append {
let _ = guard.seek(crate::fs::SeekFrom::End(0));
}
let mut output = ShellOutput::File(&mut *guard);
if run_output_builtin(cmd, args, &mut output) {
return;
}
unreachable!("redirect-supported command must be an output builtin");
}
let mut output = ShellOutput::Console;
if run_output_builtin(cmd, args, &mut output) {
return;
}
match cmd {
"cd" => cmd_cd(args),
"mkdir" => cmd_mkdir(args),
"rm" => cmd_rm(args),
"touch" => cmd_touch(args),
"ps" => cmd_ps(),
"jobs" => cmd_jobs(),
"exit" => cmd_exit(),
_ => cmd_external(cmd, args),
}
}
pub fn shell_main() -> ! {
serial_println!();
serial_println!(" ╔══════════════════════════════╗");
serial_println!(" ║ AhRightOS Shell v0.1 ║");
serial_println!(" ╚══════════════════════════════╝");
serial_println!();
serial_println!("Type 'help' for available commands.");
serial_println!();
loop {
serial_print!("{} $ ", get_cwd());
let line = read_line();
let tokens = tokenize(&line);
if tokens.is_empty() {
continue;
}
if let Some(pipe_pos) = tokens.iter().position(|&t| t == "|") {
let left = &tokens[..pipe_pos];
let right = &tokens[pipe_pos + 1..];
if left.is_empty() || right.is_empty() {
serial_println!("shell: invalid pipe syntax");
continue;
}
run_pipe(left, right);
continue;
}
match parse_command_plan(&tokens) {
Ok(plan) => run_command_plan(&plan),
Err(e) => {
serial_println!("shell: {}", e);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test_case]
fn command_plan_parses_output_append_input_and_background() {
let tokens = tokenize("cat < in.txt >> out.txt &");
let plan = parse_command_plan(&tokens).expect("parse command plan");
assert_eq!(plan.argv, alloc::vec!["cat"]);
assert_eq!(plan.stdin, Some("in.txt"));
assert_eq!(
plan.stdout,
Some(Redirect {
path: "out.txt",
append: true
})
);
assert!(plan.background);
}
#[test_case]
fn command_plan_rejects_malformed_redirection() {
let tokens = tokenize("echo hi >");
assert_eq!(
parse_command_plan(&tokens),
Err("missing output redirection target")
);
let tokens = tokenize("echo & hi");
assert_eq!(
parse_command_plan(&tokens),
Err("background marker must be last")
);
}
#[test_case]
fn output_redirection_support_is_checked_before_opening_target() {
assert!(supports_output_redirection("echo"));
assert!(supports_output_redirection("cat"));
assert!(!supports_output_redirection("unknown"));
assert!(!supports_output_redirection("cd"));
}
#[test_case]
fn unsupported_output_redirection_does_not_clobber_target_file() {
crate::fs::init_filesystem();
let path = "/shell-no-clobber.txt";
let _ = vfs::remove_file(path);
let file = vfs::create_file(path).expect("create target");
file.lock().write(b"kept").expect("seed target");
let tokens = tokenize("cd > /shell-no-clobber.txt");
let plan = parse_command_plan(&tokens).expect("parse unsupported redirection");
run_command_plan(&plan);
let file = vfs::open_file(path).expect("target should still exist");
let mut buf = [0u8; 8];
let n = file.lock().read(&mut buf).expect("read target");
assert_eq!(&buf[..n], b"kept");
}
#[test_case]
fn single_greater_output_redirection_overwrites_existing_file() {
crate::fs::init_filesystem();
let path = "/shell-truncate.txt";
let _ = vfs::remove_file(path);
let file = vfs::create_file(path).expect("create target");
file.lock()
.write(b"old-longer-content\n")
.expect("seed target");
let tokens = tokenize("echo ok > /shell-truncate.txt");
let plan = parse_command_plan(&tokens).expect("parse overwrite redirection");
run_command_plan(&plan);
let file = vfs::open_file(path).expect("target should exist");
let mut buf = [0u8; 32];
let n = file.lock().read(&mut buf).expect("read target");
assert_eq!(&buf[..n], b"ok\n");
}
}