ntoseye 0.32.0

WinDbg-like kernel debugger for Windows, from Linux and macOS
Documentation
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
use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use std::sync::OnceLock;

use linkme::distributed_slice;

use crate::error::Result;
use crate::repl::{CompletionStrategy, Flow, ReplState, error};

#[distributed_slice]
pub static COMMANDS: [CommandSpec];

pub struct CommandSpec {
    pub names: &'static [&'static str],
    pub usage: &'static str,
    pub summary: &'static str,
    pub details: Option<&'static str>,
    pub completion: CompletionSpec,
    pub run_state: Option<RunState>,
    pub run: RunEffect,
    pub style: CommandStyle,
    pub flow: Flow,
    pub handler: CommandHandler,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunState {
    Halted,
    Running,
}

/// What a command does to target execution, so dispatch contexts that must
/// not let a command move the target (breakpoint actions, exception
/// commands, a remote host with its own run-control) can refuse it by
/// metadata rather than by a name list that aliases can bypass.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunEffect {
    /// Leaves execution state alone (or only pauses it).
    None,
    /// Executes one instruction and returns promptly.
    Step,
    /// Resumes until the next stop; may block indefinitely.
    Run,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandStyle {
    StructuredArgs,
    RawTail,
    ExpressionTail,
}

#[derive(Clone, Copy)]
pub enum CompletionSpec {
    None,
    All(CompletionStrategy),
    PerArg(&'static [CompletionStrategy]),
}

impl CompletionSpec {
    pub fn strategy_for_arg(self, index: usize) -> CompletionStrategy {
        match self {
            Self::None => CompletionStrategy::None,
            Self::All(strategy) => strategy,
            Self::PerArg(strategies) => strategies
                .get(index)
                .copied()
                .unwrap_or(CompletionStrategy::None),
        }
    }
}

#[derive(Clone, Copy)]
pub enum CommandHandler {
    Args(fn(&mut ReplState<'_>, CommandInvocation<'_>) -> Result<()>),
    NoArgs(fn(&mut ReplState<'_>) -> Result<()>),
}

pub struct CommandInvocation<'a> {
    pub name: &'a str,
    pub argv: Vec<Cow<'a, str>>,
    pub raw_tail: &'a str,
}

impl<'a> CommandInvocation<'a> {
    pub fn arg(&self, index: usize) -> Option<&str> {
        self.argv.get(index).map(|arg| arg.as_ref())
    }

    pub fn join_args(&self, start: usize) -> String {
        self.argv
            .get(start..)
            .unwrap_or(&[])
            .iter()
            .map(|arg| arg.as_ref())
            .collect::<Vec<_>>()
            .join(" ")
    }
}

pub struct CommandRegistry {
    by_name: HashMap<&'static str, &'static CommandSpec>,
}

impl CommandRegistry {
    pub fn get(&self, name: &str) -> Option<&'static CommandSpec> {
        self.by_name.get(name).copied()
    }

    pub fn command_names(&self) -> Vec<(&'static str, &'static CommandSpec)> {
        let mut names: Vec<_> = self
            .by_name
            .iter()
            .map(|(name, spec)| (*name, *spec))
            .collect();
        names.sort_by_key(|(name, _)| *name);
        names
    }
}

pub fn command_registry() -> &'static CommandRegistry {
    static REGISTRY: OnceLock<CommandRegistry> = OnceLock::new();
    REGISTRY.get_or_init(|| {
        assert!(
            !COMMANDS.is_empty(),
            "REPL command registry is empty; command modules may have been dropped"
        );

        let mut by_name = HashMap::new();
        for spec in COMMANDS {
            assert!(!spec.names.is_empty(), "REPL command spec has no names");
            for &name in spec.names {
                let old = by_name.insert(name, spec);
                assert!(old.is_none(), "duplicate REPL command name: {name}");
            }
        }

        CommandRegistry { by_name }
    })
}

pub fn command_help(name: &str) -> String {
    let Some(spec) = command_registry().get(name) else {
        return "invalid usage".to_string();
    };

    let mut help = format!("{}\n(usage: {})", spec.summary, spec.usage);
    if let Some(detail) = spec.details {
        help.push('\n');
        help.push_str(detail);
    }
    help
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandParseError {
    span: Range<usize>,
    message: String,
}

impl CommandParseError {
    fn new(span: Range<usize>, message: impl Into<String>) -> Self {
        Self {
            span,
            message: message.into(),
        }
    }
}

pub struct ParsedCommand<'a> {
    pub name: &'a str,
    pub raw_tail: &'a str,
    args_start: usize,
}

impl<'a> ParsedCommand<'a> {
    pub fn invocation(
        &self,
        style: CommandStyle,
    ) -> std::result::Result<CommandInvocation<'a>, CommandParseError> {
        let argv = match style {
            CommandStyle::StructuredArgs => parse_args(self.raw_tail, self.args_start)?,
            CommandStyle::RawTail | CommandStyle::ExpressionTail => Vec::new(),
        };
        Ok(CommandInvocation {
            name: self.name,
            argv,
            raw_tail: self.raw_tail.trim(),
        })
    }
}

pub fn parse_command(
    line: &str,
) -> std::result::Result<Option<ParsedCommand<'_>>, CommandParseError> {
    let start = skip_ws(line, 0);
    if start >= line.len() {
        return Ok(None);
    }

    let name_end = line[start..]
        .find(char::is_whitespace)
        .map(|offset| start + offset)
        .unwrap_or(line.len());
    let args_start = skip_ws(line, name_end);
    Ok(Some(ParsedCommand {
        name: &line[start..name_end],
        raw_tail: &line[args_start..],
        args_start,
    }))
}

pub fn split_command_list(line: &str) -> std::result::Result<Vec<&str>, CommandParseError> {
    let mut commands = Vec::new();
    let mut start = 0;

    loop {
        start = skip_ws(line, start);
        if start >= line.len() {
            return Ok(commands);
        }

        if command_style_at(&line[start..]) == Some(CommandStyle::RawTail) {
            commands.push(line[start..].trim());
            return Ok(commands);
        }

        let mut depth = 0usize;
        let mut quote = None;
        let mut quote_start = 0;
        let mut escaped = false;
        let mut split = None;

        for (offset, ch) in line[start..].char_indices() {
            let idx = start + offset;
            if let Some(active_quote) = quote {
                if escaped {
                    escaped = false;
                } else if ch == '\\' {
                    escaped = true;
                } else if ch == active_quote {
                    quote = None;
                }
                continue;
            }

            match ch {
                '"' | '\'' => {
                    quote = Some(ch);
                    quote_start = idx;
                }
                '(' | '[' | '{' => depth += 1,
                ')' | ']' | '}' => depth = depth.saturating_sub(1),
                ';' if depth == 0 => {
                    split = Some(idx);
                    break;
                }
                _ => {}
            }
        }

        if quote.is_some() {
            return Err(CommandParseError::new(
                quote_start..quote_start + 1,
                "unterminated quoted argument",
            ));
        }

        let end = split.unwrap_or(line.len());
        let command = line[start..end].trim();
        if !command.is_empty() {
            commands.push(command);
        }

        let Some(split) = split else {
            return Ok(commands);
        };
        start = split + 1;
    }
}

fn command_style_at(line: &str) -> Option<CommandStyle> {
    let start = skip_ws(line, 0);
    if start >= line.len() {
        return None;
    }
    let end = line[start..]
        .find(char::is_whitespace)
        .map(|offset| start + offset)
        .unwrap_or(line.len());
    command_registry()
        .get(&line[start..end])
        .map(|spec| spec.style)
}

fn parse_args(
    line: &str,
    base: usize,
) -> std::result::Result<Vec<Cow<'_, str>>, CommandParseError> {
    let mut args = Vec::new();
    let mut pos = 0;
    while pos < line.len() {
        pos = skip_ws(line, pos);
        if pos >= line.len() {
            break;
        }

        let start = pos;
        let Some(quote) = line[pos..]
            .chars()
            .next()
            .filter(|ch| *ch == '"' || *ch == '\'')
        else {
            let end = line[pos..]
                .find(char::is_whitespace)
                .map(|offset| pos + offset)
                .unwrap_or(line.len());
            args.push(Cow::Borrowed(&line[start..end]));
            pos = end;
            continue;
        };

        pos += quote.len_utf8();
        let mut text = String::new();
        let mut escaped = false;
        let mut closed = false;
        while let Some(ch) = line[pos..].chars().next() {
            pos += ch.len_utf8();
            if escaped {
                // A backslash only escapes a quote or another backslash.
                // Every other sequence is passed through intact, because the
                // command that receives it owns its own escapes: `.printf`
                // needs to see `\n`, and a Windows path keeps its
                // separators.
                if ch != quote && ch != '\\' {
                    text.push('\\');
                }
                text.push(ch);
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
            } else if ch == quote {
                closed = true;
                break;
            } else {
                text.push(ch);
            }
        }
        if !closed {
            return Err(CommandParseError::new(
                base + start..base + start + quote.len_utf8(),
                "unterminated quoted argument",
            ));
        }
        args.push(Cow::Owned(text));
    }
    Ok(args)
}

fn skip_ws(s: &str, pos: usize) -> usize {
    s[pos..]
        .char_indices()
        .find_map(|(offset, ch)| (!ch.is_whitespace()).then_some(pos + offset))
        .unwrap_or(s.len())
}

pub fn report_command_parse_error(line: &str, err: CommandParseError) {
    let start = err.span.start.min(line.len());
    let end = err.span.end.min(line.len()).max(start + 1);
    outln!("{line}");
    outln!(
        "{}{} {}",
        " ".repeat(start),
        "^".repeat(end - start),
        err.message
    );
}

pub fn check_run_state(state: &ReplState<'_>, spec: &CommandSpec) -> bool {
    match spec.run_state {
        Some(RunState::Halted) if state.ctx.backend.is_running() => {
            error!("VM is running");
            return false;
        }
        Some(RunState::Running) if !state.ctx.backend.is_running() => {
            error!("VM is already paused");
            return false;
        }
        _ => {}
    }

    true
}

#[macro_export]
macro_rules! repl_command {
    (
        $method:ident();
        $($body:tt)*
    ) => {
        $crate::repl_command! {
            @register
            $crate::repl::CommandHandler::NoArgs(|state| state.$method());
            $($body)*
        }
    };

    (
        $method:ident;
        $($body:tt)*
    ) => {
        $crate::repl_command! {
            @register
            $crate::repl::CommandHandler::Args(|state, invocation| state.$method(invocation));
            $($body)*
        }
    };

    (
        names: [$($name:expr),+ $(,)?],
        usage: $usage:expr,
        summary: $summary:expr
        $(, details: $details:expr)?
        $(, completion: $completion:tt)?
        $(, run_state: $run_state:ident)?
        $(, run: $run:ident)?
        $(, style: $style:ident)?
        , flow: $flow:ident
        $(,)?
    ) => {
        $crate::repl_command! {
            @register
            $crate::repl::CommandHandler::NoArgs(|_state| Ok(()));
            names: [$($name),+],
            usage: $usage,
            summary: $summary
            $(, details: $details)?
            $(, completion: $completion)?
            $(, run_state: $run_state)?
            $(, run: $run)?
            $(, style: $style)?
            , flow: $flow,
        }
    };

    (
        @register
        $handler:expr;
        names: [$($name:expr),+ $(,)?],
        usage: $usage:expr,
        summary: $summary:expr
        $(, details: $details:expr)?
        $(, completion: $completion:tt)?
        $(, run_state: $run_state:ident)?
        $(, run: $run:ident)?
        $(, style: $style:ident)?
        $(, flow: $flow:ident)?
        $(,)?
    ) => {
        const _: () = {
            #[linkme::distributed_slice($crate::repl::COMMANDS)]
            static COMMAND: $crate::repl::CommandSpec = $crate::repl::CommandSpec {
                names: &[$($name),+],
                usage: $usage,
                summary: $summary,
                details: $crate::repl_command!(@details $($details)?),
                completion: $crate::repl_command!(@completion $($completion)?),
                run_state: $crate::repl_command!(@run_state $($run_state)?),
                run: $crate::repl_command!(@run $($run)?),
                style: $crate::repl_command!(@style $($style)?),
                flow: $crate::repl_command!(@flow $($flow)?),
                handler: $handler,
            };
        };
    };

    (@completion) => { $crate::repl::CompletionSpec::None };
    (@completion None) => { $crate::repl::CompletionSpec::None };
    (@completion [$($completion:ident),+ $(,)?]) => {
        $crate::repl::CompletionSpec::PerArg(&[
            $($crate::repl_command!(@completion_strategy $completion)),+
        ])
    };
    (@completion $completion:ident) => {
        $crate::repl::CompletionSpec::All($crate::repl_command!(@completion_strategy $completion))
    };

    (@completion_strategy None) => { $crate::repl::CompletionStrategy::None };
    (@completion_strategy Symbol) => { $crate::repl::CompletionStrategy::Symbol };
    (@completion_strategy Expression) => { $crate::repl::CompletionStrategy::Expression };
    (@completion_strategy Type) => { $crate::repl::CompletionStrategy::Type };
    (@completion_strategy Process) => { $crate::repl::CompletionStrategy::Process };
    (@completion_strategy Thread) => { $crate::repl::CompletionStrategy::Thread };
    (@completion_strategy Vcpu) => { $crate::repl::CompletionStrategy::Vcpu };
    (@completion_strategy Breakpoint) => { $crate::repl::CompletionStrategy::Breakpoint };
    (@completion_strategy Driver) => { $crate::repl::CompletionStrategy::Driver };
    (@completion_strategy Alias) => { $crate::repl::CompletionStrategy::Alias };

    (@details) => { None };
    (@details $details:expr) => { Some($details) };

    (@run_state) => { None };
    (@run_state Halted) => { Some($crate::repl::RunState::Halted) };
    (@run_state Running) => { Some($crate::repl::RunState::Running) };

    (@run) => { $crate::repl::RunEffect::None };
    (@run Step) => { $crate::repl::RunEffect::Step };
    (@run Run) => { $crate::repl::RunEffect::Run };

    (@style) => { $crate::repl::CommandStyle::StructuredArgs };
    (@style StructuredArgs) => { $crate::repl::CommandStyle::StructuredArgs };
    (@style RawTail) => { $crate::repl::CommandStyle::RawTail };
    (@style ExpressionTail) => { $crate::repl::CommandStyle::ExpressionTail };

    (@flow) => { $crate::repl::Flow::Continue };
    (@flow Continue) => { $crate::repl::Flow::Continue };
    (@flow Quit) => { $crate::repl::Flow::Quit };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_quoted_arguments() {
        let parsed = parse_command(r#"x "nt!Ke Bug" plain"#).unwrap().unwrap();
        let invocation = parsed.invocation(CommandStyle::StructuredArgs).unwrap();
        assert_eq!(invocation.name, "x");
        assert_eq!(invocation.argv[0].as_ref(), "nt!Ke Bug");
        assert_eq!(invocation.argv[1].as_ref(), "plain");
    }

    #[test]
    fn splits_semicolons_outside_quotes_and_grouping() {
        assert_eq!(
            split_command_list(r#"bp "a;b"; ev poi(rax;rbx); g"#).unwrap(),
            vec![r#"bp "a;b""#, "ev poi(rax;rbx)", "g"]
        );
    }

    #[test]
    fn raw_tail_command_keeps_semicolons() {
        assert_eq!(
            split_command_list("alias ubp bp ${1}; g").unwrap(),
            vec!["alias ubp bp ${1}; g"]
        );
    }

    #[test]
    fn expression_tail_keeps_unsplit_expression() {
        let parsed = parse_command("? rax + rbx").unwrap().unwrap();
        let invocation = parsed.invocation(CommandStyle::ExpressionTail).unwrap();
        assert_eq!(invocation.name, "?");
        assert!(invocation.argv.is_empty());
        assert_eq!(invocation.raw_tail, "rax + rbx");
    }
}