1use crate::fs::file::File;
9use crate::fs::pipe;
10use crate::fs::vfs;
11use crate::process;
12use crate::process::ProcessId;
13use crate::serial_print;
14use crate::serial_println;
15use alloc::string::String;
16use alloc::vec::Vec;
17use spin::Mutex;
18
19fn console_getchar() -> Option<u8> {
22 let ret: isize;
23 unsafe {
24 core::arch::asm!(
25 "li a7, 2",
26 "ecall",
27 "mv {}, a0",
28 out(reg) ret,
29 options(nostack)
30 );
31 }
32 if ret >= 0 {
33 Some(ret as u8)
34 } else {
35 None
36 }
37}
38
39fn read_line() -> String {
42 let mut buf = String::new();
43 loop {
44 let mut ch = console_getchar();
46 if ch.is_none() {
49 ch = crate::task::keyboard::try_pop_char();
50 }
51 if let Some(c) = ch {
52 match c {
53 b'\r' | b'\n' => {
54 serial_println!();
55 return buf;
56 }
57 0x08 | 0x7f => {
58 if !buf.is_empty() {
59 buf.pop();
60 serial_print!("\x08 \x08");
61 }
62 }
63 0x20..=0x7e => {
64 buf.push(c as char);
65 serial_print!("{}", c as char);
66 }
67 _ => {}
68 }
69 } else {
70 riscv::asm::wfi();
72 }
73 }
74}
75
76fn tokenize(line: &str) -> Vec<&str> {
79 line.split_whitespace().collect()
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83struct Redirect<'a> {
84 path: &'a str,
85 append: bool,
86}
87
88#[derive(Debug, PartialEq, Eq)]
89struct CommandPlan<'a> {
90 argv: Vec<&'a str>,
91 stdin: Option<&'a str>,
92 stdout: Option<Redirect<'a>>,
93 background: bool,
94}
95
96fn parse_command_plan<'a>(tokens: &[&'a str]) -> Result<CommandPlan<'a>, &'static str> {
97 let mut argv = Vec::new();
98 let mut stdin = None;
99 let mut stdout = None;
100 let mut background = false;
101 let mut i = 0usize;
102
103 while i < tokens.len() {
104 match tokens[i] {
105 "<" => {
106 i += 1;
107 if i >= tokens.len() {
108 return Err("missing input redirection target");
109 }
110 stdin = Some(tokens[i]);
111 }
112 ">" | ">>" => {
113 let append = tokens[i] == ">>";
114 i += 1;
115 if i >= tokens.len() {
116 return Err("missing output redirection target");
117 }
118 stdout = Some(Redirect {
119 path: tokens[i],
120 append,
121 });
122 }
123 "&" => {
124 if i + 1 != tokens.len() {
125 return Err("background marker must be last");
126 }
127 background = true;
128 }
129 token => argv.push(token),
130 }
131 i += 1;
132 }
133
134 if argv.is_empty() {
135 return Err("empty command");
136 }
137
138 Ok(CommandPlan {
139 argv,
140 stdin,
141 stdout,
142 background,
143 })
144}
145
146enum ShellOutput<'a> {
147 Console,
148 File(&'a mut dyn File),
149}
150
151fn shell_write(output: &mut ShellOutput<'_>, bytes: &[u8]) -> Result<(), &'static str> {
152 match output {
153 ShellOutput::Console => {
154 crate::serial::write_bytes(bytes);
155 Ok(())
156 }
157 ShellOutput::File(file) => file.write(bytes).map(|_| ()).map_err(|_| "write failed"),
158 }
159}
160
161fn shell_writeln(output: &mut ShellOutput<'_>, text: &str) -> Result<(), &'static str> {
162 shell_write(output, text.as_bytes())?;
163 shell_write(output, b"\n")
164}
165
166fn open_redirect_target(
167 path: &str,
168 append: bool,
169) -> Result<alloc::sync::Arc<Mutex<dyn File>>, &'static str> {
170 let abs_path = resolve_path(path);
171 if !append {
172 let _ = vfs::remove_file(&abs_path);
173 }
174 match vfs::open_file(&abs_path) {
175 Ok(file) => Ok(file),
176 Err(_) => vfs::create_file(&abs_path).map_err(|_| "cannot create redirection target"),
177 }
178}
179
180static CWD: Mutex<Option<String>> = Mutex::new(None);
183
184fn get_cwd() -> String {
185 let mut guard = CWD.lock();
186 if guard.is_none() {
187 *guard = Some(String::from("/"));
188 }
189 guard.clone().unwrap()
190}
191
192fn set_cwd(path: String) {
193 *CWD.lock() = Some(path);
194}
195
196fn resolve_path(raw: &str) -> String {
200 if raw.is_empty() {
201 return get_cwd();
202 }
203 if raw.starts_with('/') {
204 String::from(raw)
205 } else {
206 let cwd = get_cwd();
207 if cwd == "/" {
208 alloc::format!("/{}", raw)
209 } else {
210 alloc::format!("{}/{}", cwd, raw)
211 }
212 }
213}
214
215fn list_dir(abs_path: &str) -> Result<Vec<String>, &'static str> {
217 vfs::readdir_path(abs_path).map_err(|_| "cannot access directory")
218}
219
220fn is_directory(abs_path: &str) -> bool {
222 match vfs::stat_path(abs_path) {
223 Ok(meta) => meta.file_type == crate::fs::FileType::Directory,
224 Err(_) => false,
225 }
226}
227
228fn cmd_echo(args: &[&str], output: &mut ShellOutput<'_>) {
231 for (i, arg) in args.iter().enumerate() {
232 if i > 0 {
233 let _ = shell_write(output, b" ");
234 }
235 let _ = shell_write(output, arg.as_bytes());
236 }
237 let _ = shell_write(output, b"\n");
238}
239
240fn cmd_pwd(output: &mut ShellOutput<'_>) {
241 let _ = shell_writeln(output, &get_cwd());
242}
243
244fn cmd_cd(args: &[&str]) {
245 let target = if args.is_empty() { "/" } else { args[0] };
246 let abs_path = resolve_path(target);
247 if is_directory(&abs_path) {
248 set_cwd(abs_path);
249 } else {
250 serial_println!("cd: {}: not a directory", target);
251 }
252}
253
254fn cmd_ls(args: &[&str], output: &mut ShellOutput<'_>) {
255 let target = if args.is_empty() { "." } else { args[0] };
256 let abs_path = resolve_path(target);
257 match list_dir(&abs_path) {
258 Ok(entries) => {
259 for name in &entries {
260 let _ = shell_writeln(output, name);
261 }
262 }
263 Err(e) => {
264 serial_println!("ls: {}: {}", target, e);
265 }
266 }
267}
268
269fn cmd_cat(args: &[&str], output: &mut ShellOutput<'_>) {
270 if args.is_empty() {
271 serial_println!("cat: missing file operand");
272 return;
273 }
274 for &arg in args {
275 let abs_path = resolve_path(arg);
276 match vfs::open_file(&abs_path) {
277 Ok(file_handle) => {
278 let mut buf = [0u8; 512];
279 loop {
280 match file_handle.lock().read(&mut buf) {
281 Ok(0) => break,
282 Ok(n) => {
283 let _ = shell_write(output, &buf[..n]);
284 }
285 Err(_) => break,
286 }
287 }
288 }
289 Err(_) => {
290 serial_println!("cat: {}: no such file", arg);
291 }
292 }
293 }
294}
295
296fn cmd_exit() -> ! {
297 serial_println!("Shell exiting.");
298 crate::hlt_loop();
300}
301
302fn cmd_mkdir(args: &[&str]) {
303 if args.is_empty() {
304 crate::println!("mkdir: missing operand");
305 return;
306 }
307 for &arg in args {
308 let abs_path = resolve_path(arg);
309 match vfs::create_dir(&abs_path) {
310 Ok(()) => crate::println!("mkdir: created '{}'", abs_path),
311 Err(e) => crate::println!("mkdir: {}: {}", arg, e),
312 }
313 }
314}
315
316fn cmd_rm(args: &[&str]) {
317 if args.is_empty() {
318 crate::println!("rm: missing operand");
319 return;
320 }
321 for &arg in args {
322 let abs_path = resolve_path(arg);
323 match crate::fs::remove_file(&abs_path) {
324 Ok(()) => crate::println!("rm: removed '{}'", abs_path),
325 Err(e) => crate::println!("rm: {}: {}", arg, e),
326 }
327 }
328}
329
330fn cmd_touch(args: &[&str]) {
331 if args.is_empty() {
332 crate::println!("touch: missing file operand");
333 return;
334 }
335 for &arg in args {
336 let abs_path = resolve_path(arg);
337 match vfs::open_file(&abs_path) {
338 Ok(_) => {}
339 Err(_) => match vfs::create_file(&abs_path) {
340 Ok(_) => crate::println!("touch: created '{}'", abs_path),
341 Err(e) => crate::println!("touch: {}: {}", arg, e),
342 },
343 }
344 }
345}
346
347fn cmd_ps() {
348 let sched = crate::process::SCHEDULER.lock();
349 serial_println!(" PID NAME STATE");
350 serial_println!(" ─── ────────── ─────");
351 for pcb in sched.all_processes() {
352 serial_println!(
353 " {:>3} {:<10} {:?}",
354 pcb.pid().as_usize(),
355 pcb.name(),
356 pcb.state(),
357 );
358 }
359 serial_println!(" ─── ────────── ─────");
360}
361
362fn cmd_jobs() {
363 serial_println!("jobs: full POSIX job control is not implemented");
364 serial_println!("jobs: external commands are queued as AhRightOS tasks; use ps to inspect them");
365 serial_println!("jobs: signals/fg/bg remain documented future work");
366}
367
368fn cmd_help(output: &mut ShellOutput<'_>) {
369 let _ = shell_writeln(output, "AhRightOS Shell — built-in commands:");
370 let _ = shell_writeln(output, " echo <text> Print text");
371 let _ = shell_writeln(output, " pwd Print working directory");
372 let _ = shell_writeln(output, " cd <path> Change directory");
373 let _ = shell_writeln(output, " ls [path] List directory");
374 let _ = shell_writeln(output, " cat <file> Print file contents");
375 let _ = shell_writeln(output, " mkdir <dir> Create directory");
376 let _ = shell_writeln(output, " rm <file> Remove file");
377 let _ = shell_writeln(output, " touch <file> Create empty file");
378 let _ = shell_writeln(output, " ps List processes");
379 let _ = shell_writeln(output, " jobs Show job-control limitation");
380 let _ = shell_writeln(output, " exit Halt the system");
381 let _ = shell_writeln(output, " help Show this message");
382 let _ = shell_writeln(
383 output,
384 "Redirection: >, >>, and cat < file are supported for teaching built-ins.",
385 );
386}
387
388fn cmd_external(name: &str, _args: &[&str]) {
389 let abs_path = resolve_path(name);
391
392 match vfs::open_file(&abs_path) {
394 Ok(file_handle) => {
395 let mut elf_data = alloc::vec![0u8; 65536];
397 let n = match file_handle.lock().read(&mut elf_data) {
398 Ok(n) => n,
399 Err(_) => {
400 serial_println!("{}: read error", name);
401 return;
402 }
403 };
404 if n == 0 {
405 serial_println!("{}: empty file", name);
406 return;
407 }
408 elf_data.truncate(n);
409
410 let elf = match process::elf::Elf::parse(&elf_data) {
411 Ok(e) => e,
412 Err(_) => {
413 serial_println!("{}: not an ELF executable", name);
414 return;
415 }
416 };
417
418 let kernel_paddr = match process::kernel_page_table_paddr() {
420 Some(paddr) => paddr,
421 None => {
422 serial_println!("{}: kernel page table root is not registered", name);
423 return;
424 }
425 };
426
427 let result = process::with_frame_allocator(|allocator| {
428 let addr_space = match process::user::create_user_address_space(
429 &elf,
430 &elf_data,
431 allocator,
432 kernel_paddr,
433 ) {
434 Ok(a) => a,
435 Err(_) => return -1isize,
436 };
437
438 let new_satp = {
439 let ppn = addr_space.page_table_paddr().as_usize() >> 12;
440 (8usize << 60) | ppn
441 };
442
443 let user_stack_top = 0x7FFF_F000usize;
444 let name_static: &'static str = alloc::string::String::from(name).leak();
445 let user_task = process::user::create_user_task(
446 ProcessId::new(),
447 name_static,
448 elf.entry,
449 user_stack_top,
450 new_satp,
451 );
452
453 let mut sched = process::SCHEDULER.lock();
454 if sched.add_process(user_task).is_err() {
455 return -1isize;
456 }
457 0isize
458 });
459
460 if result < 0 {
461 serial_println!("{}: failed to create process", name);
462 }
463 }
464 Err(_) => {
465 serial_println!("{}: command not found", name);
466 }
467 }
468}
469
470fn run_pipe(left_tokens: &[&str], right_tokens: &[&str]) {
475 let (read_end, write_end) = pipe::make_pipe();
476 let mut write_file = write_end;
477 let left_cmd = left_tokens[0];
478 let left_args = &left_tokens[1..];
479
480 match left_cmd {
481 "echo" => {
482 for (i, arg) in left_args.iter().enumerate() {
483 if i > 0 {
484 let _ = write_file.write(b" ");
485 }
486 let _ = write_file.write(arg.as_bytes());
487 }
488 let _ = write_file.write(b"\n");
489 }
490 "ls" => {
491 let target = if left_args.is_empty() {
492 "."
493 } else {
494 left_args[0]
495 };
496 let abs_path = resolve_path(target);
497 if let Ok(entries) = list_dir(&abs_path) {
498 for name in &entries {
499 let _ = write_file.write(name.as_bytes());
500 let _ = write_file.write(b"\n");
501 }
502 }
503 }
504 "cat" => {
505 for &arg in left_args {
506 let abs_path = resolve_path(arg);
507 if let Ok(fh) = vfs::open_file(&abs_path) {
508 let mut buf = [0u8; 512];
509 loop {
510 match fh.lock().read(&mut buf) {
511 Ok(0) => break,
512 Ok(n) => {
513 let _ = write_file.write(&buf[..n]);
514 }
515 Err(_) => break,
516 }
517 }
518 }
519 }
520 }
521 "pwd" => {
522 let _ = write_file.write(get_cwd().as_bytes());
523 let _ = write_file.write(b"\n");
524 }
525 _ => {
526 serial_println!("{}: unsupported in pipe", left_cmd);
527 return;
528 }
529 }
530 drop(write_file); let mut read_file = read_end;
534 let right_cmd = right_tokens[0];
535 let _right_args = &right_tokens[1..];
536
537 match right_cmd {
538 "cat" => {
539 let mut buf = [0u8; 512];
540 loop {
541 match read_file.read(&mut buf) {
542 Ok(0) => break,
543 Ok(n) => crate::serial::write_bytes(&buf[..n]),
544 Err(_) => break,
545 }
546 }
547 }
548 _ => {
549 serial_println!("{}: unsupported in pipe", right_cmd);
550 }
551 }
552}
553
554fn run_output_builtin(cmd: &str, args: &[&str], output: &mut ShellOutput<'_>) -> bool {
555 match cmd {
556 "echo" => cmd_echo(args, output),
557 "pwd" => cmd_pwd(output),
558 "ls" => cmd_ls(args, output),
559 "cat" => cmd_cat(args, output),
560 "help" => cmd_help(output),
561 _ => return false,
562 }
563 true
564}
565
566fn supports_output_redirection(cmd: &str) -> bool {
567 matches!(cmd, "echo" | "pwd" | "ls" | "cat" | "help")
568}
569
570fn run_command_plan(plan: &CommandPlan<'_>) {
571 let cmd = plan.argv[0];
572 let mut args = &plan.argv[1..];
573 let stdin_arg;
574
575 if let Some(input) = plan.stdin {
576 if cmd == "cat" && args.is_empty() {
577 stdin_arg = [input];
578 args = &stdin_arg;
579 } else {
580 serial_println!("shell: input redirection is currently supported only by cat");
581 return;
582 }
583 }
584
585 if plan.background && supports_output_redirection(cmd) {
586 serial_println!(
587 "shell: background marker ignored for built-in command '{}'",
588 cmd
589 );
590 }
591
592 if let Some(redirect) = plan.stdout {
593 if !supports_output_redirection(cmd) {
594 serial_println!("shell: redirection is unsupported for '{}'", cmd);
595 return;
596 }
597 let file_handle = match open_redirect_target(redirect.path, redirect.append) {
598 Ok(file) => file,
599 Err(e) => {
600 serial_println!("shell: {}: {}", redirect.path, e);
601 return;
602 }
603 };
604 let mut guard = file_handle.lock();
605 if redirect.append {
606 let _ = guard.seek(crate::fs::SeekFrom::End(0));
607 }
608 let mut output = ShellOutput::File(&mut *guard);
609 if run_output_builtin(cmd, args, &mut output) {
610 return;
611 }
612 unreachable!("redirect-supported command must be an output builtin");
613 }
614
615 let mut output = ShellOutput::Console;
616 if run_output_builtin(cmd, args, &mut output) {
617 return;
618 }
619
620 match cmd {
621 "cd" => cmd_cd(args),
622 "mkdir" => cmd_mkdir(args),
623 "rm" => cmd_rm(args),
624 "touch" => cmd_touch(args),
625 "ps" => cmd_ps(),
626 "jobs" => cmd_jobs(),
627 "exit" => cmd_exit(),
628 _ => cmd_external(cmd, args),
629 }
630}
631
632pub fn shell_main() -> ! {
636 serial_println!();
637 serial_println!(" ╔══════════════════════════════╗");
638 serial_println!(" ║ AhRightOS Shell v0.1 ║");
639 serial_println!(" ╚══════════════════════════════╝");
640 serial_println!();
641 serial_println!("Type 'help' for available commands.");
642 serial_println!();
643
644 loop {
645 serial_print!("{} $ ", get_cwd());
646
647 let line = read_line();
648 let tokens = tokenize(&line);
649
650 if tokens.is_empty() {
651 continue;
652 }
653
654 if let Some(pipe_pos) = tokens.iter().position(|&t| t == "|") {
656 let left = &tokens[..pipe_pos];
657 let right = &tokens[pipe_pos + 1..];
658 if left.is_empty() || right.is_empty() {
659 serial_println!("shell: invalid pipe syntax");
660 continue;
661 }
662 run_pipe(left, right);
663 continue;
664 }
665
666 match parse_command_plan(&tokens) {
667 Ok(plan) => run_command_plan(&plan),
668 Err(e) => {
669 serial_println!("shell: {}", e);
670 }
671 }
672 }
673}
674
675#[cfg(test)]
676mod tests {
677 use super::*;
678
679 #[test_case]
680 fn command_plan_parses_output_append_input_and_background() {
681 let tokens = tokenize("cat < in.txt >> out.txt &");
682 let plan = parse_command_plan(&tokens).expect("parse command plan");
683 assert_eq!(plan.argv, alloc::vec!["cat"]);
684 assert_eq!(plan.stdin, Some("in.txt"));
685 assert_eq!(
686 plan.stdout,
687 Some(Redirect {
688 path: "out.txt",
689 append: true
690 })
691 );
692 assert!(plan.background);
693 }
694
695 #[test_case]
696 fn command_plan_rejects_malformed_redirection() {
697 let tokens = tokenize("echo hi >");
698 assert_eq!(
699 parse_command_plan(&tokens),
700 Err("missing output redirection target")
701 );
702
703 let tokens = tokenize("echo & hi");
704 assert_eq!(
705 parse_command_plan(&tokens),
706 Err("background marker must be last")
707 );
708 }
709
710 #[test_case]
711 fn output_redirection_support_is_checked_before_opening_target() {
712 assert!(supports_output_redirection("echo"));
713 assert!(supports_output_redirection("cat"));
714 assert!(!supports_output_redirection("unknown"));
715 assert!(!supports_output_redirection("cd"));
716 }
717
718 #[test_case]
719 fn unsupported_output_redirection_does_not_clobber_target_file() {
720 crate::fs::init_filesystem();
721 let path = "/shell-no-clobber.txt";
722 let _ = vfs::remove_file(path);
723 let file = vfs::create_file(path).expect("create target");
724 file.lock().write(b"kept").expect("seed target");
725
726 let tokens = tokenize("cd > /shell-no-clobber.txt");
727 let plan = parse_command_plan(&tokens).expect("parse unsupported redirection");
728 run_command_plan(&plan);
729
730 let file = vfs::open_file(path).expect("target should still exist");
731 let mut buf = [0u8; 8];
732 let n = file.lock().read(&mut buf).expect("read target");
733 assert_eq!(&buf[..n], b"kept");
734 }
735
736 #[test_case]
737 fn single_greater_output_redirection_overwrites_existing_file() {
738 crate::fs::init_filesystem();
739 let path = "/shell-truncate.txt";
740 let _ = vfs::remove_file(path);
741 let file = vfs::create_file(path).expect("create target");
742 file.lock()
743 .write(b"old-longer-content\n")
744 .expect("seed target");
745
746 let tokens = tokenize("echo ok > /shell-truncate.txt");
747 let plan = parse_command_plan(&tokens).expect("parse overwrite redirection");
748 run_command_plan(&plan);
749
750 let file = vfs::open_file(path).expect("target should exist");
751 let mut buf = [0u8; 32];
752 let n = file.lock().read(&mut buf).expect("read target");
753 assert_eq!(&buf[..n], b"ok\n");
754 }
755}