starry-kernel 0.6.3

A Linux-compatible OS kernel built on ArceOS unikernel
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
use alloc::{sync::Arc, vec::Vec};
use core::{
    ptr::NonNull,
    sync::atomic::{AtomicBool, Ordering},
};

use ax_task::IrqNotify;
use axpoll::{IoEvents, PollSet};
use spin::LazyLock;

use super::{
    Tty,
    terminal::ldisc::{ProcessMode, TtyConfig, TtyRead, TtyWrite},
};

pub type NTtyDriver = Tty<ConsoleReader, Console>;

#[derive(Clone, Copy)]
pub struct Console;

#[derive(Default)]
pub struct ConsoleReader {
    mouse_filter: MouseEscapeFilter,
}

impl TtyRead for ConsoleReader {
    fn read(&mut self, buf: &mut [u8]) -> usize {
        let mut written = 0;
        let mut raw = [0; 64];
        while written < buf.len() {
            let free = buf.len() - written;
            let pending = self.mouse_filter.pending_len();
            let read_cap = if pending < free {
                (free - pending).min(raw.len())
            } else {
                0
            };

            if read_cap == 0 {
                written += self.mouse_filter.flush_pending(&mut buf[written..]);
                break;
            }

            let read = ax_runtime::hal::console::read_bytes(&mut raw[..read_cap]);
            if read == 0 {
                written += self.mouse_filter.flush_pending(&mut buf[written..]);
                break;
            }

            written += self.mouse_filter.feed(&raw[..read], &mut buf[written..]);
            if written > 0 {
                break;
            }
        }
        written
    }
}

impl TtyWrite for Console {
    fn write(&self, buf: &[u8]) {
        ax_runtime::hal::console::write_bytes(buf);
    }
}

#[derive(Default)]
struct MouseEscapeFilter {
    pending: Vec<u8>,
}

enum MouseParse {
    Mouse(usize),
    NonMouse(usize),
    NeedMore,
}

enum NumberParse {
    Complete(u32),
    Invalid(usize),
    NeedMore,
}

impl MouseEscapeFilter {
    fn pending_len(&self) -> usize {
        self.pending.len()
    }

    fn feed(&mut self, input: &[u8], out: &mut [u8]) -> usize {
        self.filter(input, out, false)
    }

    #[cfg(test)]
    fn filter_chunk(&mut self, input: &[u8], out: &mut [u8]) -> usize {
        self.filter(input, out, true)
    }

    fn filter(&mut self, input: &[u8], out: &mut [u8], flush_incomplete: bool) -> usize {
        self.pending.extend_from_slice(input);

        let mut read = 0;
        let mut written = 0;
        while read < self.pending.len() {
            match parse_mouse_escape(&self.pending[read..]) {
                MouseParse::Mouse(len) => {
                    read += len;
                }
                MouseParse::NonMouse(len) => {
                    let end = read + len;
                    out[written..written + len].copy_from_slice(&self.pending[read..end]);
                    read = end;
                    written += len;
                }
                MouseParse::NeedMore => break,
            }
        }

        if read > 0 {
            self.pending.drain(..read);
        }

        if flush_incomplete {
            written += self.flush_pending(&mut out[written..]);
        }
        written
    }

    fn flush_pending(&mut self, out: &mut [u8]) -> usize {
        let len = self.pending.len().min(out.len());
        out[..len].copy_from_slice(&self.pending[..len]);
        self.pending.drain(..len);
        len
    }
}

fn parse_mouse_escape(input: &[u8]) -> MouseParse {
    if input[0] != b'\x1b' {
        return MouseParse::NonMouse(1);
    }
    if input.len() == 1 {
        return MouseParse::NeedMore;
    }
    if input[1] != b'[' {
        return MouseParse::NonMouse(2);
    }
    if input.len() == 2 {
        return MouseParse::NeedMore;
    }

    match input[2] {
        b'M' => {
            if input.len() < 6 {
                MouseParse::NeedMore
            } else {
                MouseParse::Mouse(6)
            }
        }
        b'<' => parse_sgr_mouse(input),
        b'0'..=b'9' => parse_urxvt_mouse(input),
        _ => MouseParse::NonMouse(3),
    }
}

fn parse_sgr_mouse(input: &[u8]) -> MouseParse {
    let mut pos = 3;
    for _ in 0..2 {
        match parse_number(input, pos) {
            NumberParse::Complete(_) => {}
            NumberParse::Invalid(len) => return MouseParse::NonMouse(len),
            NumberParse::NeedMore => return MouseParse::NeedMore,
        }
        while pos < input.len() && input[pos].is_ascii_digit() {
            pos += 1;
        }
        if pos == input.len() {
            return MouseParse::NeedMore;
        }
        if input[pos] != b';' {
            return MouseParse::NonMouse(pos + 1);
        }
        pos += 1;
    }

    match parse_number(input, pos) {
        NumberParse::Complete(_) => {}
        NumberParse::Invalid(len) => return MouseParse::NonMouse(len),
        NumberParse::NeedMore => return MouseParse::NeedMore,
    }
    while pos < input.len() && input[pos].is_ascii_digit() {
        pos += 1;
    }
    if pos == input.len() {
        return MouseParse::NeedMore;
    }
    match input[pos] {
        b'M' | b'm' => MouseParse::Mouse(pos + 1),
        _ => MouseParse::NonMouse(pos + 1),
    }
}

fn parse_urxvt_mouse(input: &[u8]) -> MouseParse {
    let mut pos = 2;
    let button = match parse_number(input, pos) {
        NumberParse::Complete(value) => value,
        NumberParse::Invalid(len) => return MouseParse::NonMouse(len),
        NumberParse::NeedMore => return MouseParse::NeedMore,
    };
    for _ in 0..2 {
        while pos < input.len() && input[pos].is_ascii_digit() {
            pos += 1;
        }
        if pos == input.len() {
            return MouseParse::NeedMore;
        }
        if input[pos] != b';' {
            return MouseParse::NonMouse(pos + 1);
        }
        pos += 1;
        match parse_number(input, pos) {
            NumberParse::Complete(_) => {}
            NumberParse::Invalid(len) => return MouseParse::NonMouse(len),
            NumberParse::NeedMore => return MouseParse::NeedMore,
        }
    }
    while pos < input.len() && input[pos].is_ascii_digit() {
        pos += 1;
    }
    if pos == input.len() {
        return MouseParse::NeedMore;
    }
    if input[pos] == b'M' && button >= 32 {
        MouseParse::Mouse(pos + 1)
    } else {
        MouseParse::NonMouse(pos + 1)
    }
}

fn parse_number(input: &[u8], start: usize) -> NumberParse {
    if start == input.len() {
        return NumberParse::NeedMore;
    }
    if !input[start].is_ascii_digit() {
        return NumberParse::Invalid(start + 1);
    }

    let mut value = 0u32;
    let mut pos = start;
    while pos < input.len() && input[pos].is_ascii_digit() {
        value = value
            .saturating_mul(10)
            .saturating_add((input[pos] - b'0') as u32);
        pos += 1;
    }
    NumberParse::Complete(value)
}

/// The default TTY device.
pub static N_TTY: LazyLock<Arc<NTtyDriver>> = LazyLock::new(new_n_tty);
static CONSOLE_INPUT_SOURCE: LazyLock<Arc<PollSet>> = LazyLock::new(|| Arc::new(PollSet::new()));
static CONSOLE_INPUT_NOTIFY: LazyLock<Arc<IrqNotify>> =
    LazyLock::new(|| Arc::new(IrqNotify::new()));
static CONSOLE_NOTIFY_WORKER: AtomicBool = AtomicBool::new(false);

fn handle_console_input_irq(_irq_num: usize) {
    let events = ax_runtime::hal::console::handle_irq();
    if events.intersects(
        ax_runtime::hal::console::ConsoleIrqEvent::RX_READY
            | ax_runtime::hal::console::ConsoleIrqEvent::RX_ERROR
            | ax_runtime::hal::console::ConsoleIrqEvent::OVERRUN,
    ) {
        CONSOLE_INPUT_NOTIFY.notify_irq();
    }
}

unsafe fn handle_console_input_raw_irq(
    ctx: ax_runtime::hal::irq::IrqContext,
    _data: NonNull<()>,
) -> ax_runtime::hal::irq::IrqReturn {
    handle_console_input_irq(ctx.irq.0);
    ax_runtime::hal::irq::IrqReturn::Handled
}

fn new_n_tty() -> Arc<NTtyDriver> {
    let terminal = {
        let t = super::terminal::Terminal::default();

        // Synchronously querying the connected terminal only works when the
        // firmware/serial path can reliably supply a cursor-position response.
        // Dynamic-platform QEMU tests run under ostool pipes, so keep the
        // default 24x80 fallback there instead of stalling early Starry boot.
        #[cfg(not(feature = "plat-dyn"))]
        if let Some((rows, cols)) = query_console_size() {
            *t.window_size.lock() = super::terminal::WindowSize {
                ws_row: rows,
                ws_col: cols,
                ws_xpixel: 0,
                ws_ypixel: 0,
            };
        }
        Arc::new(t)
    };

    Tty::new(
        terminal,
        TtyConfig {
            reader: ConsoleReader::default(),
            writer: Console,
            process_mode: console_irq_mode().unwrap_or(ProcessMode::Manual),
        },
    )
}

fn start_console_notify_worker() {
    if CONSOLE_NOTIFY_WORKER.swap(true, Ordering::AcqRel) {
        return;
    }
    ax_task::spawn_with_name(
        || loop {
            CONSOLE_INPUT_NOTIFY.wait();
            // Console RX readiness has been published by the IRQ handler.
            unsafe { CONSOLE_INPUT_SOURCE.wake(IoEvents::IN) };
        },
        "console-notify".into(),
    );
}

/// Probe the connected terminal for its current size using the
/// standard cursor-position-report sequence.
///
/// Sequence: save cursor (DECSC) -> move to (9999, 9999) -> request
/// cursor position (CPR) -> restore cursor (DECRC).  The terminal
/// clamps the move to its actual bottom-right corner before reporting
/// back, so the reply `\x1b[rows;colsR` reflects the real geometry.
/// Spin-waits up to roughly 100 ms for the reply and returns `None`
/// on timeout or parse failure.
///
/// Called once during NTTY initialisation, before the polling reader
/// task is spawned, so there is no concurrent consumer racing on the
/// UART receive FIFO.
#[cfg(not(feature = "plat-dyn"))]
fn query_console_size() -> Option<(u16, u16)> {
    ax_runtime::hal::console::write_bytes(b"\x1b7\x1b[9999;9999H\x1b[6n\x1b8");

    let mut buf = [0u8; 32];
    let mut len = 0usize;

    // Spin up to ~100 ms (in wall time, polled via ax_runtime::hal::time::wall_time)
    // for the `R` terminator.  Hosts that ignore CPR (jcode running under
    // a non-interactive serial, automated CI runners) will time out and
    // we fall back to the 24x80 default without blocking boot further.
    let deadline = ax_runtime::hal::time::wall_time() + core::time::Duration::from_millis(100);
    'collect: while ax_runtime::hal::time::wall_time() < deadline {
        let mut tmp = [0u8; 1];
        if ax_runtime::hal::console::read_bytes(&mut tmp) > 0 {
            if len < buf.len() {
                buf[len] = tmp[0];
                len += 1;
            } else {
                // Buffer full without seeing 'R'; give up rather than
                // spinning until the deadline on a misbehaving terminal.
                break 'collect;
            }
            if tmp[0] == b'R' {
                break 'collect;
            }
        }
        core::hint::spin_loop();
    }

    parse_console_size_response(&buf[..len])
}

#[cfg(any(test, not(feature = "plat-dyn")))]
fn parse_console_size_response(buf: &[u8]) -> Option<(u16, u16)> {
    let r_pos = buf.iter().rposition(|&b| b == b'R')?;
    let escape_pos = buf[..r_pos].windows(2).rposition(|w| w == b"\x1b[")?;
    let inner = core::str::from_utf8(&buf[escape_pos + 2..r_pos]).ok()?;
    let mut parts = inner.splitn(2, ';');
    let rows: u16 = parts.next()?.parse().ok()?;
    let cols: u16 = parts.next()?.parse().ok()?;
    if rows == 0 || cols == 0 {
        return None;
    }
    Some((rows, cols))
}

fn console_irq_mode() -> Option<ProcessMode> {
    let irq = ax_runtime::hal::console::irq_num()?;
    if ax_runtime::hal::irq::request_shared_irq(
        irq,
        handle_console_input_raw_irq,
        NonNull::dangling(),
    )
    .is_err()
    {
        warn!("Failed to register console IRQ handler for irq {irq}, falling back to polling mode");
        return None;
    }

    ax_runtime::hal::console::set_input_irq_enabled(true);
    start_console_notify_worker();
    Some(ProcessMode::InterruptDriven(CONSOLE_INPUT_SOURCE.clone()))
}

#[cfg(test)]
mod tests {
    use super::{MouseEscapeFilter, parse_console_size_response};

    #[test]
    fn parses_cursor_position_response() {
        assert_eq!(
            parse_console_size_response(b"\x1b7\x1b[24;80R\x1b8"),
            Some((24, 80))
        );
    }

    fn filter(input: &[u8]) -> alloc::vec::Vec<u8> {
        let mut filter = MouseEscapeFilter::default();
        let mut out = alloc::vec![0; input.len()];
        let len = filter.filter_chunk(input, &mut out);
        out.truncate(len);
        out
    }

    #[test]
    fn mouse_filter_drops_sgr_click_wheel_and_side_button_reports() {
        assert_eq!(filter(b"\x1b[<0;10;20M"), b"");
        assert_eq!(filter(b"\x1b[<0;10;20m"), b"");
        assert_eq!(filter(b"\x1b[<64;10;20M"), b"");
        assert_eq!(filter(b"\x1b[<128;10;20M"), b"");
    }

    #[test]
    fn mouse_filter_drops_x10_report() {
        assert_eq!(filter(b"\x1b[M !!"), b"");
    }

    #[test]
    fn mouse_filter_drops_urxvt_style_report() {
        assert_eq!(filter(b"\x1b[35;10;20M"), b"");
        assert_eq!(filter(b"\x1b[96;10;20M"), b"");
    }

    #[test]
    fn mouse_filter_preserves_keyboard_and_terminal_control_sequences() {
        assert_eq!(filter(b"\x1b[A"), b"\x1b[A");
        assert_eq!(filter(b"\x1b[6n"), b"\x1b[6n");
        assert_eq!(filter(b"\x1b[1;1R"), b"\x1b[1;1R");
        assert_eq!(filter(b"\x1ba"), b"\x1ba");
    }

    #[test]
    fn mouse_filter_preserves_incomplete_or_non_mouse_sequences() {
        assert_eq!(filter(b"\x1b["), b"\x1b[");
        assert_eq!(filter(b"\x1b[M!"), b"\x1b[M!");
        assert_eq!(filter(b"\x1b[1;2;3R"), b"\x1b[1;2;3R");
        assert_eq!(filter(b"\x1b[1;2;3M"), b"\x1b[1;2;3M");
    }

    #[test]
    fn mouse_filter_removes_mouse_reports_from_mixed_stream() {
        assert_eq!(filter(b"abc \x1b[<64;10;20Mdef\n"), b"abc def\n");
    }
}