axvisor 0.6.0

A lightweight type-1 hypervisor based on ArceOS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
// Copyright 2025 The Axvisor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::BTreeMap;
#[cfg(feature = "fs")]
use std::fs::{self, File, FileType};
#[cfg(all(feature = "fs", target_os = "none"))]
use std::fs::{FileTypeExt, PermissionsExt};
#[cfg(feature = "fs")]
use std::io::{self, Read, Write};
#[cfg(all(feature = "fs", unix))]
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
use std::string::{String, ToString};

use crate::shell::command::{CommandNode, FlagDef, ParsedCommand};
#[cfg(feature = "fs")]
use axvisor::shell_support::{
    CopyMode, RemoveOptions, collect_directory_entry_names, copy_operands, copy_path,
    move_file_or_dir, path_basename, remove_path, touch_file,
};

#[cfg(feature = "fs")]
macro_rules! print_err {
    ($cmd: literal, $msg: expr) => {
        println!("{}: {}", $cmd, $msg);
    };
    ($cmd: literal, $arg: expr, $err: expr) => {
        println!("{}: {}: {}", $cmd, $arg, $err);
    };
}

// Helper function: split whitespace
#[cfg(feature = "fs")]
fn split_whitespace(s: &str) -> (&str, &str) {
    let s = s.trim();
    if let Some(pos) = s.find(char::is_whitespace) {
        let (first, rest) = s.split_at(pos);
        (first, rest.trim())
    } else {
        (s, "")
    }
}

#[cfg(feature = "fs")]
fn show_ls_entry(path: &str, entry: &str, show_long: bool) -> io::Result<()> {
    if show_long {
        let metadata = fs::metadata(path)?;
        let rwx = file_perm_to_rwx(metadata.permissions().mode());
        let rwx = unsafe { core::str::from_utf8_unchecked(&rwx) };
        println!(
            "{}{} {:>8} {}",
            file_type_to_char(metadata.file_type()),
            rwx,
            metadata.len(),
            entry
        );
    } else {
        println!("{}", entry);
    }
    Ok(())
}

#[cfg(feature = "fs")]
fn list_one(name: &str, print_name: bool, show_long: bool, show_all: bool) -> io::Result<()> {
    if !fs::metadata(name)?.is_dir() {
        return show_ls_entry(name, name, show_long);
    }
    let entries = fs::read_dir(name)?;

    if print_name {
        println!("{}:", name);
    }

    let entries = collect_directory_entry_names(
        entries.map(|entry| entry.map(|entry| entry.file_name())),
        show_all,
    )?;

    for entry in entries {
        let entry = entry.to_string_lossy();
        let path = format!("{name}/{entry}");
        if let Err(e) = show_ls_entry(&path, &entry, show_long) {
            print_err!("ls", path, e);
        }
    }
    Ok(())
}

#[cfg(feature = "fs")]
fn do_ls(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;
    let show_long = cmd.flags.contains("long");
    let show_all = cmd.flags.contains("all");

    let targets = if args.is_empty() {
        vec![".".to_string()]
    } else {
        args.clone()
    };

    for (i, name) in targets.iter().enumerate() {
        if i > 0 {
            println!();
        }
        if let Err(e) = list_one(name, targets.len() > 1, show_long, show_all) {
            print_err!("ls", name, e);
        }
    }
}

#[cfg(feature = "fs")]
fn do_cat(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;

    if args.is_empty() {
        print_err!("cat", "no file specified");
        return;
    }

    fn cat_one(fname: &str) -> io::Result<()> {
        let mut buf = [0; 1024];
        let mut file = File::open(fname)?;
        loop {
            let n = file.read(&mut buf)?;
            if n > 0 {
                crate::guest_console::submit_host_bytes(&buf[..n]);
            } else {
                return Ok(());
            }
        }
    }

    for fname in args {
        if let Err(e) = cat_one(fname) {
            print_err!("cat", fname, e);
        }
    }
}

#[cfg(feature = "fs")]
fn do_echo(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;
    let no_newline = cmd.flags.contains("no-newline");

    let args_str = args.join(" ");

    fn echo_file(fname: &str, text_list: &[&str]) -> io::Result<()> {
        let mut file = File::create(fname)?;
        for text in text_list {
            file.write_all(text.as_bytes())?;
        }
        Ok(())
    }

    if let Some(pos) = args_str.rfind('>') {
        let text_before = args_str[..pos].trim();
        let (fname, text_after) = split_whitespace(&args_str[pos + 1..]);
        if fname.is_empty() {
            print_err!("echo", "no file specified");
            return;
        };

        let text_list = [
            text_before,
            if !text_after.is_empty() { " " } else { "" },
            text_after,
            if !no_newline { "\n" } else { "" },
        ];
        if let Err(e) = echo_file(fname, &text_list) {
            print_err!("echo", fname, e);
        }
    } else if no_newline {
        print!("{}", args_str);
    } else {
        println!("{}", args_str);
    }
}

#[cfg(feature = "fs")]
fn do_mkdir(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;
    let create_parents = cmd.flags.contains("parents");

    if args.is_empty() {
        print_err!("mkdir", "missing operand");
        return;
    }

    fn mkdir_one(path: &str, create_parents: bool) -> io::Result<()> {
        if create_parents {
            fs::create_dir_all(path)
        } else {
            fs::create_dir(path)
        }
    }

    for path in args {
        if let Err(e) = mkdir_one(path, create_parents) {
            print_err!("mkdir", format_args!("cannot create directory '{path}'"), e);
        }
    }
}

#[cfg(feature = "fs")]
fn do_rm(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;
    let rm_dir = cmd.flags.contains("dir");
    let recursive = cmd.flags.contains("recursive");
    let force = cmd.flags.contains("force");

    if args.is_empty() {
        print_err!("rm", "missing operand");
        return;
    }

    let options = RemoveOptions {
        directory: rm_dir,
        recursive,
        force,
    };
    for path in args {
        if let Err(e) = remove_path(path, options) {
            print_err!("rm", format_args!("cannot remove '{path}'"), e);
        }
    }
}

#[cfg(feature = "fs")]
fn do_cd(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;

    let target = if args.is_empty() {
        "/"
    } else if args.len() == 1 {
        &args[0]
    } else {
        print_err!("cd", "too many arguments");
        return;
    };

    if let Err(e) = std::env::set_current_dir(target) {
        print_err!("cd", target, e);
    }
}

#[cfg(feature = "fs")]
fn do_pwd(cmd: &ParsedCommand) {
    let _logical = cmd.flags.contains("logical");

    match std::env::current_dir() {
        Ok(pwd) => println!("{}", pwd.display()),
        Err(e) => {
            print_err!("pwd", e);
        }
    }
}

fn do_uname(cmd: &ParsedCommand) {
    let show_all = cmd.flags.contains("all");
    let show_kernel = cmd.flags.contains("kernel-name");
    let show_arch = cmd.flags.contains("machine");

    let arch = option_env!("AX_ARCH").unwrap_or("");
    let platform = option_env!("AX_PLATFORM").unwrap_or("");
    let smp = match option_env!("AX_SMP") {
        None | Some("1") => "",
        _ => " SMP",
    };
    let version = option_env!("CARGO_PKG_VERSION").unwrap_or("0.1.0");

    if show_all {
        println!(
            "ArceOS {ver}{smp} {arch} {plat}",
            ver = version,
            smp = smp,
            arch = arch,
            plat = platform,
        );
    } else if show_kernel {
        println!("ArceOS");
    } else if show_arch {
        println!("{}", arch);
    } else {
        println!(
            "ArceOS {ver}{smp} {arch} {plat}",
            ver = version,
            smp = smp,
            arch = arch,
            plat = platform,
        );
    }
}

fn do_exit(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;
    let exit_code = if args.is_empty() {
        0
    } else {
        args[0].parse::<i32>().unwrap_or(0)
    };

    println!("Bye~");
    super::shutdown(exit_code);
}

fn do_log(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;

    if args.is_empty() {
        println!("Current log level: {:?}", log::max_level());
        return;
    }

    match args[0].as_str() {
        "on" | "enable" => log::set_max_level(log::LevelFilter::Info),
        "off" | "disable" => log::set_max_level(log::LevelFilter::Off),
        "error" => log::set_max_level(log::LevelFilter::Error),
        "warn" => log::set_max_level(log::LevelFilter::Warn),
        "info" => log::set_max_level(log::LevelFilter::Info),
        "debug" => log::set_max_level(log::LevelFilter::Debug),
        "trace" => log::set_max_level(log::LevelFilter::Trace),
        level => {
            println!("Unknown log level: {}", level);
            println!("Available levels: off, error, warn, info, debug, trace");
            return;
        }
    }
    println!("Log level set to: {:?}", log::max_level());
}

#[cfg(feature = "fs")]
fn do_mv(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;

    if args.len() < 2 {
        print_err!("mv", "missing operand");
        return;
    }

    // If only two arguments, handle single file/dir move
    if args.len() == 2 {
        let source = &args[0];
        let dest = &args[1];

        // Check if destination exists and is a directory
        if let Ok(dest_meta) = fs::metadata(dest)
            && dest_meta.is_dir()
        {
            // Move source into destination directory
            let source_name = match path_basename(source) {
                Ok(source_name) => source_name,
                Err(e) => {
                    print_err!("mv", format_args!("cannot access '{source}'"), e);
                    return;
                }
            };
            let dest_path = format!("{dest}/{source_name}");
            if let Err(e) = move_file_or_dir(source, &dest_path) {
                print_err!(
                    "mv",
                    format_args!("cannot move '{source}' to '{dest_path}'"),
                    e
                );
            }
            return;
        }

        // Direct rename/move
        if let Err(e) = move_file_or_dir(source, dest) {
            print_err!("mv", format_args!("cannot move '{source}' to '{dest}'"), e);
        }
    } else {
        // Multiple sources - destination must be a directory
        let dest = &args[args.len() - 1];
        let sources = &args[..args.len() - 1];

        // Check if destination is a directory
        match fs::metadata(dest) {
            Ok(meta) if meta.is_dir() => {
                // Move each source into destination directory
                for source in sources {
                    let source_name = match path_basename(source) {
                        Ok(source_name) => source_name,
                        Err(e) => {
                            print_err!("mv", format_args!("cannot access '{source}'"), e);
                            continue;
                        }
                    };
                    let dest_path = format!("{dest}/{source_name}");
                    if let Err(e) = move_file_or_dir(source, &dest_path) {
                        print_err!(
                            "mv",
                            format_args!("cannot move '{source}' to '{dest_path}'"),
                            e
                        );
                    }
                }
            }
            Ok(_) => {
                print_err!("mv", format_args!("target '{dest}' is not a directory"));
            }
            Err(e) => {
                print_err!("mv", format_args!("cannot access '{dest}'"), e);
            }
        }
    }
}

#[cfg(feature = "fs")]
fn do_touch(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;

    if args.is_empty() {
        print_err!("touch", "missing operand");
        return;
    }

    for filename in args {
        if let Err(e) = touch_file(filename) {
            print_err!("touch", filename, e);
        }
    }
}

#[cfg(feature = "fs")]
fn do_cp(cmd: &ParsedCommand) {
    let args = &cmd.positional_args;
    let recursive = cmd.flags.contains("recursive");

    let (source, dest) = match copy_operands(args) {
        Ok(operands) => operands,
        Err(e) => {
            print_err!("cp", e);
            return;
        }
    };
    let mode = if recursive {
        CopyMode::Recursive
    } else {
        CopyMode::File
    };

    if let Err(e) = copy_path(source, dest, mode) {
        print_err!("cp", format_args!("cannot copy '{source}' to '{dest}'"), e);
    }
}

#[cfg(feature = "fs")]
fn file_type_to_char(ty: FileType) -> char {
    if ty.is_char_device() {
        'c'
    } else if ty.is_block_device() {
        'b'
    } else if ty.is_socket() {
        's'
    } else if ty.is_fifo() {
        'p'
    } else if ty.is_symlink() {
        'l'
    } else if ty.is_dir() {
        'd'
    } else if ty.is_file() {
        '-'
    } else {
        '?'
    }
}

#[rustfmt::skip]
#[cfg(feature = "fs")]
const fn file_perm_to_rwx(mode: u32) -> [u8; 9] {
    let mut perm = [b'-'; 9];
    macro_rules! set {
        ($bit:literal, $rwx:literal) => {
            if mode & (1 << $bit) != 0 {
                perm[8 - $bit] = $rwx
            }
        };
    }

    set!(2, b'r'); set!(1, b'w'); set!(0, b'x');
    set!(5, b'r'); set!(4, b'w'); set!(3, b'x');
    set!(8, b'r'); set!(7, b'w'); set!(6, b'x');
    perm
}

pub fn build_base_cmd(tree: &mut BTreeMap<String, CommandNode>) {
    // ls Command
    #[cfg(feature = "fs")]
    tree.insert(
        "ls".to_string(),
        CommandNode::new("List directory contents")
            .with_handler(do_ls)
            .with_usage("ls [OPTIONS] [DIRECTORY...]")
            .with_flag(
                FlagDef::new("long", "Use long listing format")
                    .with_short('l')
                    .with_long("long"),
            )
            .with_flag(
                FlagDef::new("all", "Show hidden files")
                    .with_short('a')
                    .with_long("all"),
            ),
    );

    // cat Command
    #[cfg(feature = "fs")]
    tree.insert(
        "cat".to_string(),
        CommandNode::new("Display file contents")
            .with_handler(do_cat)
            .with_usage("cat <FILE1> [FILE2...]"),
    );

    // echo Command
    #[cfg(feature = "fs")]
    tree.insert(
        "echo".to_string(),
        CommandNode::new("Display text")
            .with_handler(do_echo)
            .with_usage("echo [OPTIONS] [TEXT...]")
            .with_flag(
                FlagDef::new("no-newline", "Do not output trailing newline")
                    .with_short('n')
                    .with_long("no-newline"),
            ),
    );

    // mkdir Command
    #[cfg(feature = "fs")]
    tree.insert(
        "mkdir".to_string(),
        CommandNode::new("Create directories")
            .with_handler(do_mkdir)
            .with_usage("mkdir [OPTIONS] <DIRECTORY1> [DIRECTORY2...]")
            .with_flag(
                FlagDef::new("parents", "Create parent directories as needed")
                    .with_short('p')
                    .with_long("parents"),
            ),
    );

    // rm Command
    #[cfg(feature = "fs")]
    tree.insert(
        "rm".to_string(),
        CommandNode::new("Remove files and directories")
            .with_handler(do_rm)
            .with_usage("rm [OPTIONS] <FILE1> [FILE2...]")
            .with_flag(
                FlagDef::new("dir", "Remove empty directories")
                    .with_short('d')
                    .with_long("dir"),
            )
            .with_flag(
                FlagDef::new("recursive", "Remove directories recursively")
                    .with_short('r')
                    .with_long("recursive"),
            )
            .with_flag(
                FlagDef::new("force", "Force removal, ignore nonexistent files")
                    .with_short('f')
                    .with_long("force"),
            ),
    );

    // cd Command
    #[cfg(feature = "fs")]
    tree.insert(
        "cd".to_string(),
        CommandNode::new("Change directory")
            .with_handler(do_cd)
            .with_usage("cd [DIRECTORY]"),
    );

    // pwd Command
    #[cfg(feature = "fs")]
    tree.insert(
        "pwd".to_string(),
        CommandNode::new("Print working directory")
            .with_handler(do_pwd)
            .with_usage("pwd [OPTIONS]")
            .with_flag(
                FlagDef::new("logical", "Use logical path")
                    .with_short('L')
                    .with_long("logical"),
            ),
    );

    // uname Command
    tree.insert(
        "uname".to_string(),
        CommandNode::new("System information")
            .with_handler(do_uname)
            .with_usage("uname [OPTIONS]")
            .with_flag(
                FlagDef::new("all", "Show all information")
                    .with_short('a')
                    .with_long("all"),
            )
            .with_flag(
                FlagDef::new("kernel-name", "Show kernel name")
                    .with_short('s')
                    .with_long("kernel-name"),
            )
            .with_flag(
                FlagDef::new("machine", "Show machine architecture")
                    .with_short('m')
                    .with_long("machine"),
            ),
    );

    // exit Command
    tree.insert(
        "exit".to_string(),
        CommandNode::new("Exit the shell")
            .with_handler(do_exit)
            .with_usage("exit [EXIT_CODE]"),
    );

    // log Command
    tree.insert(
        "log".to_string(),
        CommandNode::new("Change log level")
            .with_handler(do_log)
            .with_usage("log [LEVEL]"),
    );

    // touch Command
    #[cfg(feature = "fs")]
    tree.insert(
        "touch".to_string(),
        CommandNode::new("Create empty files")
            .with_handler(do_touch)
            .with_usage("touch <FILE1> [FILE2...]"),
    );

    // cp Command
    #[cfg(feature = "fs")]
    tree.insert(
        "cp".to_string(),
        CommandNode::new("Copy files")
            .with_handler(do_cp)
            .with_usage("cp [OPTIONS] <SOURCE> <DEST>")
            .with_flag(
                FlagDef::new("recursive", "Copy directories recursively")
                    .with_short('r')
                    .with_long("recursive"),
            ),
    );

    // mv Command
    #[cfg(feature = "fs")]
    tree.insert(
        "mv".to_string(),
        CommandNode::new("Move/rename files")
            .with_handler(do_mv)
            .with_usage("mv <SOURCE> <DEST> | mv <SOURCE1> [SOURCE2...] <DIRECTORY>"),
    );
}