summaryrefslogtreecommitdiffstats
path: root/shell/src/lib.rs
blob: bdd79c699dd17da7ee3d54c4a3f100fb384a2822 (plain) (blame)
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
#![no_std]

extern crate alloc;

/// Minimal command shell — reads from PS/2 keyboard, writes to GOP + serial.
use rsnix::ps2::{self, KeyEvent};
use rsnix::{gop_print, gop_println, serial_print, serial_println};

/// Maximum input line length.
const LINE_BUF_SIZE: usize = 256;

/// Run the shell forever.
pub fn run() -> ! {
    gop_println!(
        "rs-dos v{} — type 'help' for commands",
        env!("CARGO_PKG_VERSION")
    );
    serial_println!(
        "========== rs-dos v{} ==========",
        env!("CARGO_PKG_VERSION")
    );

    loop {
        // Print prompt
        gop_print!("> ");
        serial_print!("> ");

        // Read one line from keyboard
        let line = read_line();

        // Parse and execute
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        let (cmd, args) = split_first_word(trimmed);

        match cmd {
            "help" => cmd_help(),
            "echo" => cmd_echo(args),
            "clear" => cmd_clear(),
            "halt" | "poweroff" | "exit" => cmd_halt(),
            "hello" => {
                gop_println!("World!");
                serial_println!("World!");
            }
            "info" => cmd_info(),
            "mem" => cmd_mem(),
            _ => {
                gop_println!("unknown command: {}", cmd);
                serial_println!("unknown command: {}", cmd);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Line input (PS/2 keyboard, no heap)
// ---------------------------------------------------------------------------
fn read_line() -> heapless_str::String<LINE_BUF_SIZE> {
    let mut buf = heapless_str::String::<LINE_BUF_SIZE>::new();
    loop {
        match ps2::poll_key() {
            KeyEvent::Enter => {
                rsnix::gop::put_char('\n');
                rsnix::serial::write_str("\r\n");
                return buf;
            }
            KeyEvent::Char(c) if c.is_ascii_graphic() || c == ' ' => {
                if buf.push(c).is_ok() {
                    rsnix::gop::put_char(c);
                    // Echo to serial too
                    let mut s = [0u8; 4];
                    let s = c.encode_utf8(&mut s);
                    rsnix::serial::write_str(s);
                }
            }
            KeyEvent::Backspace => {
                if buf.pop().is_some() {
                    // GOP backspace: move cursor back and erase
                    rsnix::gop::put_char('\x08');
                    // Serial backspace: send BS SP BS (standard terminal protocol)
                    rsnix::serial::write_str("\x08 \x08");
                }
            }
            KeyEvent::Tab => {
                for _ in 0..4 {
                    if buf.push(' ').is_ok() {
                        rsnix::gop::put_char(' ');
                        rsnix::serial::write_str(" ");
                    }
                }
            }
            _ => {}
        }
    }
}

/// Split a command line into the first word and the rest.
fn split_first_word(s: &str) -> (&str, &str) {
    let s = s.trim_start();
    if let Some(i) = s.find(char::is_whitespace) {
        (&s[..i], s[i..].trim_start())
    } else {
        (s, "")
    }
}

// ---------------------------------------------------------------------------
// Built-in commands
// ---------------------------------------------------------------------------

fn cmd_help() {
    gop_println!("available commands:");
    gop_println!("  help     — show this message");
    gop_println!("  echo     — echo arguments");
    gop_println!("  clear    — clear screen");
    gop_println!("  hello    — print 'World!'");
    gop_println!("  info     — show system info");
    gop_println!("  mem      — show memory info");
    gop_println!("  halt     — halt the system");
    gop_println!("  exit     — alias for halt");
    serial_println!("available commands:");
    serial_println!("  help, echo, clear, hello, info, mem, halt, exit");
}

fn cmd_echo(args: &str) {
    gop_println!("{}", args);
}

fn cmd_clear() {
    rsnix::gop::clear_screen();
}

fn cmd_info() {
    // Test that the global allocator works: build a String on the heap
    let mut s = alloc::string::String::from("rs-dos v");
    s.push_str(env!("CARGO_PKG_VERSION"));
    s.push_str(" — rsnix kernel");
    gop_println!("{}", s);
    gop_println!("arch: x86_64, freestanding, no userspace");
    serial_println!("{}", s);
    serial_println!("arch: x86_64, freestanding, no userspace");
    // String is freed (dropped) when this scope ends — tests dealloc too
}

fn cmd_mem() {
    let (map, key) = rsnix::memory::get_map();

    let mut total_kb = 0u64;
    let mut conventional_kb = 0u64;
    let mut loader_kb = 0u64;
    let mut boot_code_kb = 0u64;
    let mut boot_data_kb = 0u64;
    let mut reserved_kb = 0u64;
    let mut acpi_kb = 0u64;
    let mut mmio_kb = 0u64;

    for desc in map {
        let pages = desc.number_of_pages;
        let bytes_4k = pages * 4;
        total_kb += bytes_4k;
        match desc.kind {
            1 => reserved_kb += bytes_4k,
            3 => boot_code_kb += bytes_4k,
            4 => boot_data_kb += bytes_4k,
            5 | 10 => acpi_kb += bytes_4k,
            6 => loader_kb += bytes_4k,
            7 => conventional_kb += bytes_4k,
            11 | 12 => mmio_kb += bytes_4k,
            _ => reserved_kb += bytes_4k,
        }
    }

    // Build a big heap string with format! to test the allocator
    let mut out = alloc::string::String::new();
    use alloc::fmt::Write;
    let _ = writeln!(out, "memory map (key=0x{:x}, {} entries)", key, map.len());
    let _ = writeln!(
        out,
        "  usable    {:4} MB   Conventional",
        conventional_kb / 1024
    );
    let _ = writeln!(
        out,
        "  boot code {:4} MB   BootServicesCode",
        boot_code_kb / 1024
    );
    let _ = writeln!(
        out,
        "  boot data {:4} MB   BootServicesData",
        boot_data_kb / 1024
    );
    let _ = writeln!(out, "  loader    {:4} MB   LoaderData", loader_kb / 1024);
    let _ = writeln!(out, "  ACPI      {:4} MB", acpi_kb / 1024);
    let _ = writeln!(out, "  MMIO      {:4} MB", mmio_kb / 1024);
    let _ = writeln!(out, "  reserved  {:4} MB", reserved_kb / 1024);
    let _ = writeln!(
        out,
        "  raw total {:4} MB   (incl. PCIe MMIO)",
        total_kb / 1024
    );

    gop_print!("{}", out);
    serial_print!("{}", out);
}

fn cmd_halt() -> ! {
    gop_println!("halting...");
    serial_println!("halting...");
    loop {
        unsafe {
            core::arch::asm!("cli; hlt");
        }
    }
}

// ---------------------------------------------------------------------------
// Minimal fixed-capacity string for no-stack use (avoids alloc dependency)
// ---------------------------------------------------------------------------
mod heapless_str {
    use core::fmt;

    /// A fixed-capacity string allocated entirely on the stack.
    pub struct String<const N: usize> {
        buf: [u8; N],
        len: usize,
    }

    impl<const N: usize> String<N> {
        pub const fn new() -> Self {
            String {
                buf: [0u8; N],
                len: 0,
            }
        }

        pub fn as_str(&self) -> &str {
            // SAFETY: we only write valid ASCII bytes.
            unsafe { core::str::from_utf8_unchecked(&self.buf[..self.len]) }
        }

        pub fn push(&mut self, c: char) -> Result<(), ()> {
            if self.len >= N {
                return Err(());
            }
            self.buf[self.len] = c as u8;
            self.len += 1;
            Ok(())
        }

        pub fn pop(&mut self) -> Option<char> {
            if self.len == 0 {
                return None;
            }
            self.len -= 1;
            Some(self.buf[self.len] as char)
        }

        pub fn is_empty(&self) -> bool {
            self.len == 0
        }

        pub fn clear(&mut self) {
            self.len = 0;
        }

        pub fn trim(&self) -> &str {
            self.as_str().trim()
        }
    }

    impl<const N: usize> fmt::Display for String<N> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.as_str())
        }
    }

    impl<const N: usize> fmt::Debug for String<N> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{:?}", self.as_str())
        }
    }
}