ntoseye 0.33.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
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
use std::collections::HashSet;
use std::path::{Path, PathBuf};

use crate::error::Result;
use crate::expr::{Expr, ExprValue};
use crate::symbols::{
    FieldInfo, ModuleSymbolStatus, SourceLocation, format_symbol_with_offset, parse_source_paths,
    parse_symbol_sources,
};
use crate::target::UserVar;
use crate::types::VirtAddr;
use crate::typeview::{TypeView, nested_layout_name};
use crate::ui;

use crate::repl::*;

repl_command! {
    cmd_x;
    names: ["x"],
    usage: "x <query>  or  x <module>!<query>",
    summary: "Fuzzy-search symbols by name.",
    details: "operators: ^prefix  suffix$  'exact  !negate  (space = AND)",
    completion: Symbol,
}

repl_command! {
    cmd_ln;
    names: ["ln"],
    usage: "ln <address>",
    summary: "List the nearest symbol to an address.",
    completion: Expression,
}

repl_command! {
    cmd_ev;
    names: ["?", "ev"],
    usage: "? <expression>",
    summary: "Evaluate an expression.",
    details: "memory reads: by() 1  wo() 2  dwo() 4  qwo()/poi() 8;  &expr is storage, ->/. are values",
    completion: Expression,
    style: ExpressionTail,
}

repl_command! {
    cmd_set;
    names: ["set"],
    usage: "set $<name> <expression>",
    summary: "Define a convenience variable usable in expressions as $<name>.",
    completion: [None, Expression],
}

repl_command! {
    cmd_vars();
    names: ["vars"],
    usage: "vars",
    summary: "List defined convenience variables and result slots.",
}

repl_command! {
    cmd_unset;
    names: ["unset"],
    usage: "unset $<name>",
    summary: "Remove a convenience variable.",
}

repl_command! {
    cmd_sympath;
    names: [".sympath"],
    usage: ".sympath [<directory|http-server> ...]",
    summary: "Display or replace the ordered symbol source path.",
}

repl_command! {
    cmd_sympath_append;
    names: [".sympath+"],
    usage: ".sympath+ <directory|http-server> ...",
    summary: "Append entries to the ordered symbol source path.",
}

repl_command! {
    cmd_symfix();
    names: [".symfix"],
    usage: ".symfix",
    summary: "Restore the ntoseye cache and Microsoft symbol server defaults.",
}

repl_command! {
    cmd_srcpath;
    names: [".srcpath"],
    usage: ".srcpath [<local-root|recorded-prefix=local-root> ...]",
    summary: "Display or replace ordered local source path mappings.",
}

repl_command! {
    cmd_srcpath_append;
    names: [".srcpath+"],
    usage: ".srcpath+ <local-root|recorded-prefix=local-root> ...",
    summary: "Append local source path mappings.",
}

repl_command! {
    cmd_ls;
    names: ["ls"],
    usage: "ls [.] [first][,count]",
    summary: "List source lines of the current scope's file.",
    details: "With no arguments, continues after the lines the previous ls or lsa listed; `.` restarts at the current line. `first` is a line number; `count` defaults to 10. The file is the one the current scope IP maps to, found through .srcpath.",
}

repl_command! {
    cmd_lsa;
    names: ["lsa"],
    usage: "lsa [address][,first][,count]",
    summary: "List source lines around an address.",
    details: "Defaults to the current scope IP, five lines before it, and twelve lines in all. `first` is an offset from the address's line (negative for lines before it). The line at the address is marked `>`.",
    completion: Expression,
}

repl_command! {
    cmd_dv;
    names: ["dv"],
    usage: "dv [address]",
    summary: "Display procedure locals and parameters at an address.",
    completion: Expression,
}

repl_command! {
    cmd_reload_symbols;
    names: [".reload"],
    usage: ".reload [module]",
    summary: "Reload symbols for one module or every module in the current scope.",
}

repl_command! {
    cmd_ld;
    names: ["ld"],
    usage: "ld <module>",
    summary: "Force symbol source selection and indexing for one module.",
}

repl_command! {
    cmd_lmv;
    names: ["lmv"],
    usage: "lmv [module]",
    summary: "Display detailed per-module symbol status and PDB identity.",
}

impl ReplState<'_> {
    fn cmd_x(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        let Some(query) = invocation.arg(0) else {
            outln!("{}\n", command_help("x"));
            return Ok(());
        };
        // bounded purely for terminal-output sanity (resolution
        // is O(1) now); a huge match set just floods the screen
        const X_LIMIT: usize = 4096;
        let dtb = self.ctx.target.current_dtb();
        // `module!query` scopes the search to one module; a bare query
        // fuzzy-matches the cached merged index, whose names are already
        // module-qualified.
        let names: Vec<String> = match query.split_once('!') {
            Some((module, q)) => self
                .ctx
                .target
                .symbols
                .search_symbols_in_module(dtb, module, q, X_LIMIT)
                .into_iter()
                .map(|name| format!("{module}!{name}"))
                .collect(),
            None => self.caches.symbols.read().unwrap().search(query, X_LIMIT),
        };
        let truncated = names.len() >= X_LIMIT;
        let mut hits: Vec<u64> = Vec::new();
        for name in &names {
            let bare = name
                .rsplit_once('!')
                .map_or(name.as_str(), |(_, bare)| bare);
            let mut seen = HashSet::new();
            for candidate in self.ctx.target.symbols.find_symbol_candidates(dtb, name) {
                if !seen.insert((candidate.module.to_ascii_lowercase(), candidate.address.0)) {
                    continue;
                }
                outln!(
                    "{}  {}",
                    ui::addr(candidate.address.0),
                    ui::symbol(&format!("{}!{}", candidate.module, bare))
                );
                hits.push(candidate.address.0);
            }
        }
        if hits.is_empty() {
            outln!("no symbols match '{}'", query);
        } else {
            outln!(
                "\n{} {}{} (in $0..${})",
                hits.len(),
                if hits.len() == 1 { "symbol" } else { "symbols" },
                if truncated {
                    ", truncated; refine query"
                } else {
                    ""
                },
                hits.len() - 1
            );
        }
        self.ctx.target.set_results(hits, self.line.clone());
        outln!();

        Ok(())
    }

    fn cmd_ln(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        let Some(arg) = invocation.arg(0) else {
            outln!("{}\n", command_help("ln"));
            return Ok(());
        };
        let addr = match Expr::eval_with_radix(arg, &self.ctx.target, self.radix) {
            Ok(a) => a,
            Err(e) => {
                error!("{}", e);
                return Ok(());
            }
        };
        match self
            .ctx
            .target
            .symbols
            .find_closest_symbol_for_address(self.ctx.target.current_dtb(), addr)
        {
            Some((module, sym, offset)) => {
                let label = format_symbol_with_offset(&module, &sym, offset);
                outln!("{}  {}\n", ui::addr(addr.0), ui::symbol(&label));
                // $0 = the symbol's base address (the resolved target)
                self.ctx
                    .target
                    .set_results(vec![(addr - offset as u64).0], self.line.clone());
            }
            None => {
                outln!("no symbol found for {}\n", ui::addr(addr.0));
            }
        }

        Ok(())
    }

    fn cmd_ev(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        let expr_str = invocation.raw_tail;
        if expr_str.is_empty() {
            outln!("{}\n", command_help("ev"));
            return Ok(());
        }

        let value = match Expr::parse_with_radix(expr_str, self.radix)
            .and_then(|expr| expr.evaluate(&self.ctx.target))
        {
            Ok(value) => value,
            Err(e) => {
                error!("{}", e);
                return Ok(());
            }
        };
        if let Err(e) = self.print_expr_value(&value) {
            error!("{}", e);
        }

        Ok(())
    }

    /// Render an evaluated expression. A raw expression is a u64 and prints as
    /// an address, the way every earlier release did. A typed expression
    /// prints its type and the same value text `dt` and the editor show, so
    /// `? index` on an `int` is not mistaken for an address.
    fn print_expr_value(&mut self, value: &ExprValue) -> Result<()> {
        let Some(type_data) = value.type_data() else {
            let raw = value.scalar(&self.ctx.target)?;
            self.ctx.target.set_results(vec![raw.0], self.line.clone());
            outln!("{}", ui::addr(raw.0));
            return Ok(());
        };

        let byte_size = value.byte_size();
        let type_name = type_data.to_string();
        let scalar = value.scalar(&self.ctx.target);
        let view = TypeView::new(self.ctx);
        if let Ok(scalar) = scalar {
            let text = view.scalar_text(scalar.0, type_data, byte_size);
            outln!("{} {}", ui::muted(&type_name), text);
            self.ctx
                .target
                .set_results(vec![scalar.0], self.line.clone());
            return Ok(());
        }

        // An aggregate has no scalar value. Where it lives in memory, render
        // what `dt` would render for it and name the command that expands it;
        // the result slot holds its address so `$0` stays useful.
        let address = match value.address() {
            Ok(address) => address,
            // Report why the value has no number, not why it has no address:
            // an unavailable local must say it was optimized out.
            Err(_) => return Err(scalar.unwrap_err()),
        };
        let field = FieldInfo {
            offset: 0,
            size: byte_size.unwrap_or_default(),
            type_data: type_data.clone(),
        };
        let text = view.value_text(address, &field);
        if text.is_empty() {
            let expand = match nested_layout_name(type_data) {
                Some(layout) => format!("dt {layout} {:#x}", address.0),
                None => format!("db {:#x} L{:#x}", address.0, byte_size.unwrap_or(8)),
            };
            outln!(
                "{} at {}   {}",
                ui::muted(&type_name),
                ui::addr(address.0),
                ui::muted(&expand)
            );
        } else {
            outln!("{} {}", ui::muted(&type_name), text);
        }
        self.ctx
            .target
            .set_results(vec![address.0], self.line.clone());
        Ok(())
    }

    fn cmd_set(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        let rest = invocation.join_args(0);
        let Some((lhs, rhs)) = rest.split_once(char::is_whitespace) else {
            outln!("{}\n", command_help("set"));
            return Ok(());
        };
        let name = lhs.trim().strip_prefix('$').unwrap_or(lhs.trim()).trim();
        // names must start with a letter or '_'; this reserves
        // $<digits> (and digit-leading names) for the $0..$N
        // result slots, avoiding any collision
        let valid = name
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
            && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
        if !valid {
            error!(
                "invalid variable name '${}' (must start with a letter or '_'; $<digits> are reserved for result slots)",
                name
            );
            return Ok(());
        }
        let source = rhs.trim().to_string();
        match Expr::eval_with_radix(&source, &self.ctx.target, self.radix) {
            Ok(v) => {
                self.ctx
                    .target
                    .user_vars
                    .insert(name.to_string(), UserVar { value: v.0, source });
                outln!("${} = {}\n", name, ui::addr(v.0));
            }
            Err(e) => error!("{}", e),
        }

        Ok(())
    }

    fn cmd_vars(&mut self) -> Result<()> {
        let builtins = self.ctx.target.builtin_variables();
        if self.ctx.target.user_vars.is_empty()
            && self.ctx.target.results.is_empty()
            && builtins.is_empty()
        {
            outln!("no variables defined\n");
            return Ok(());
        }
        let mut names: Vec<&String> = self.ctx.target.user_vars.keys().collect();
        names.sort();
        if !names.is_empty() {
            outln!("{}", ui::label("user"));
            for name in names {
                let var = &self.ctx.target.user_vars[name];
                outln!(
                    "  ${:<16} {}   {}",
                    name,
                    ui::addr(var.value),
                    ui::muted(&var.source)
                );
            }
        }
        if !self.ctx.target.results.is_empty() {
            if !self.ctx.target.user_vars.is_empty() {
                outln!();
            }
            let origin = self
                .ctx
                .target
                .results_origin
                .as_deref()
                .map(|cmd| format!("from: {}", cmd))
                .unwrap_or_default();
            outln!(
                "  {}   {}",
                ui::muted(&format!("$0..${}", self.ctx.target.results.len() - 1)),
                ui::muted(&origin)
            );
        }
        if !builtins.is_empty() {
            if !self.ctx.target.user_vars.is_empty() || !self.ctx.target.results.is_empty() {
                outln!();
            }
            outln!("{}", ui::label("builtins"));
            for var in builtins {
                outln!(
                    "  ${:<16} {}   {}",
                    var.name,
                    ui::addr(var.value),
                    ui::muted(var.source)
                );
            }
        }
        outln!();

        Ok(())
    }

    fn cmd_unset(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        let Some(arg) = invocation.arg(0) else {
            outln!("{}\n", command_help("unset"));
            return Ok(());
        };
        let name = arg.strip_prefix('$').unwrap_or(arg);
        if self.ctx.target.user_vars.remove(name).is_some() {
            outln!("unset ${}\n", name);
        } else {
            error!("no such variable: ${}", name);
        }

        Ok(())
    }

    fn cmd_sympath(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        if invocation.argv.is_empty() {
            self.print_symbol_sources();
            return Ok(());
        }

        self.ctx
            .target
            .symbols
            .set_symbol_sources(parse_symbol_sources(&invocation.argv));
        self.print_symbol_sources();
        Ok(())
    }

    fn cmd_sympath_append(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        if invocation.argv.is_empty() {
            outln!("{}\n", command_help(".sympath+"));
            return Ok(());
        }

        for source in parse_symbol_sources(&invocation.argv) {
            self.ctx.target.symbols.append_symbol_source(source);
        }
        self.print_symbol_sources();
        Ok(())
    }

    fn cmd_symfix(&mut self) -> Result<()> {
        self.ctx.target.symbols.reset_symbol_sources();
        self.print_symbol_sources();
        Ok(())
    }

    fn print_symbol_sources(&self) {
        outln!("symbol sources:");
        for (index, source) in self.ctx.target.symbols.symbol_sources().iter().enumerate() {
            outln!("  {:>2}: {}", index, source);
        }
        outln!();
    }

    fn cmd_srcpath(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        if !invocation.argv.is_empty() {
            self.ctx
                .target
                .symbols
                .set_source_paths(parse_source_paths(&invocation.argv));
        }
        self.print_source_paths();
        Ok(())
    }

    fn cmd_srcpath_append(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        if invocation.argv.is_empty() {
            outln!("{}\n", command_help(".srcpath+"));
            return Ok(());
        }
        for mapping in parse_source_paths(&invocation.argv) {
            self.ctx.target.symbols.append_source_path(mapping);
        }
        self.print_source_paths();
        Ok(())
    }

    fn print_source_paths(&self) {
        let paths = self.ctx.target.symbols.source_paths();
        if paths.is_empty() {
            outln!("source paths: <empty>\n");
            return;
        }
        outln!("source paths:");
        for (index, path) in paths.iter().enumerate() {
            outln!("  {:>2}: {}", index, path);
        }
        outln!();
    }

    /// The selected frame's IP, else the live one.
    fn scope_ip(&self) -> Option<VirtAddr> {
        self.ctx
            .target
            .selected_frame
            .as_ref()
            .map(|frame| frame.ip)
            .or_else(|| {
                self.ctx
                    .target
                    .register_value(self.ctx.target.instruction_pointer_register())
            })
            .map(VirtAddr)
    }

    /// The source line `address` maps to, with its local file: the error
    /// names what is missing (line info, or the file `.srcpath` should map).
    fn source_file_at(
        &self,
        address: VirtAddr,
    ) -> std::result::Result<(PathBuf, SourceLocation), String> {
        let Some(location) = self.ctx.target.source_location(address) else {
            return Err(format!(
                "no source line information for {}",
                ui::addr(address.0)
            ));
        };
        match location
            .local_path
            .clone()
            .filter(|_| location.local_exists)
        {
            Some(path) => Ok((path, location)),
            None => Err(format!(
                "source file for {} is not available locally (recorded as {}); map it with .srcpath",
                ui::addr(address.0),
                location.file
            )),
        }
    }

    /// Print `count` lines of `path` from 1-based line `first`, marking
    /// `current` with `>`. Returns the line after the last one printed.
    fn list_source(&mut self, path: &Path, first: u32, count: u32, current: Option<u32>) -> u32 {
        let text = match std::fs::read_to_string(path) {
            Ok(text) => text,
            Err(error) => {
                error!("failed to read {}: {error}", path.display());
                return first;
            }
        };
        let lines: Vec<&str> = text.lines().collect();
        let first = first.max(1);
        if first as usize > lines.len() {
            outln!(
                "{}: line {first} is past the end ({} lines)\n",
                path.display(),
                lines.len()
            );
            return first;
        }
        let last = (first as usize + count as usize - 1).min(lines.len());
        outln!("{}:", path.display());
        for number in first as usize..=last {
            let mark = if Some(number as u32) == current {
                '>'
            } else {
                ' '
            };
            outln!("{mark}{number:>6}: {}", lines[number - 1]);
        }
        outln!();
        let next = last as u32 + 1;
        self.source_cursor = Some((path.to_path_buf(), next));
        next
    }

    fn cmd_ls(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        const DEFAULT_COUNT: u32 = 10;
        let Some(spec) = parse_ls_args(&invocation.argv) else {
            outln!("{}\n", command_help("ls"));
            return Ok(());
        };
        let count = spec.count.unwrap_or(DEFAULT_COUNT);
        let (path, first, current) = match (spec.first, spec.restart, &self.source_cursor) {
            (None, false, Some((path, next))) => (path.clone(), *next, None),
            _ => {
                let Some(ip) = self.scope_ip() else {
                    error!("ls requires a halted register context");
                    return Ok(());
                };
                let (path, location) = match self.source_file_at(ip) {
                    Ok(found) => found,
                    Err(message) => {
                        error!("{message}");
                        return Ok(());
                    }
                };
                (
                    path,
                    spec.first.unwrap_or(location.line),
                    Some(location.line),
                )
            }
        };
        self.list_source(&path, first, count, current);
        Ok(())
    }

    fn cmd_lsa(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        const DEFAULT_FIRST: i64 = -5;
        const DEFAULT_COUNT: u32 = 12;
        let Some(spec) = parse_lsa_args(&invocation.argv) else {
            outln!("{}\n", command_help("lsa"));
            return Ok(());
        };
        let address = match spec.address {
            Some(text) => match Expr::eval_with_radix(&text, &self.ctx.target, self.radix) {
                Ok(address) => address,
                Err(error) => {
                    error!("{error}");
                    return Ok(());
                }
            },
            None => match self.scope_ip() {
                Some(ip) => ip,
                None => {
                    error!("lsa requires an address or a halted register context");
                    return Ok(());
                }
            },
        };
        let (path, location) = match self.source_file_at(address) {
            Ok(found) => found,
            Err(message) => {
                error!("{message}");
                return Ok(());
            }
        };
        let first = (i64::from(location.line) + spec.first.unwrap_or(DEFAULT_FIRST)).max(1) as u32;
        self.list_source(
            &path,
            first,
            spec.count.unwrap_or(DEFAULT_COUNT),
            Some(location.line),
        );
        Ok(())
    }

    fn cmd_dv(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        let address = if let Some(arg) = invocation.arg(0) {
            match Expr::eval_with_radix(arg, &self.ctx.target, self.radix) {
                Ok(address) => address,
                Err(err) => {
                    error!("{}", err);
                    return Ok(());
                }
            }
        } else {
            let Some(rip) = self.scope_ip() else {
                error!("dv requires a halted register context or an explicit address");
                return Ok(());
            };
            rip
        };

        let Some(locals) = self.ctx.target.procedure_locals(address)? else {
            outln!("no procedure locals found at {}\n", ui::addr(address.0));
            return Ok(());
        };
        if locals.is_empty() {
            outln!("no locals in scope at {}\n", ui::addr(address.0));
            return Ok(());
        }

        for local in locals.iter() {
            let kind = if local.is_parameter { "param" } else { "local" };
            let location = local.location.describe();
            match self
                .ctx
                .target
                .resolve_procedure_local_value(address, local)
            {
                Some(value) => outln!(
                    "{:<20} {:<24} {:<7} {:<24} {:#x}",
                    local.name,
                    local.type_name,
                    kind,
                    location,
                    value
                ),
                None => outln!(
                    "{:<20} {:<24} {:<7} {}",
                    local.name,
                    local.type_name,
                    kind,
                    location
                ),
            }
        }
        outln!();
        Ok(())
    }

    fn cmd_reload_symbols(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        self.reload_symbols(invocation.arg(0));
        Ok(())
    }

    fn cmd_ld(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        let Some(module) = invocation.arg(0) else {
            outln!("{}\n", command_help("ld"));
            return Ok(());
        };
        self.reload_symbols(Some(module));
        Ok(())
    }

    fn reload_symbols(&mut self, module: Option<&str>) {
        match self.ctx.target.reload_module_symbols(module) {
            Ok(report) => {
                print_module_symbol_report(&report);
                *self.caches.symbols.write().unwrap() = self.ctx.target.current_symbol_index();
                *self.caches.types.write().unwrap() = self.ctx.target.current_types_index();
                if let Err(err) = self
                    .ctx
                    .breakpoints
                    .resolve_symbolic(&mut *self.ctx.backend, &self.ctx.target)
                {
                    error!("symbolic breakpoint re-resolution failed: {}", err);
                }
                self.caches.refresh_breakpoints(&self.ctx.breakpoints);
            }
            Err(err) => error!("symbol reload failed: {}", err),
        }
    }

    fn cmd_lmv(&mut self, invocation: CommandInvocation<'_>) -> Result<()> {
        let filter = invocation.arg(0);
        let dtb = self
            .ctx
            .target
            .current_process_info
            .as_ref()
            .map(|process| process.dtb)
            .unwrap_or_else(|| self.ctx.target.kernel_dtb());
        let modules = match self.ctx.target.modules() {
            Ok(modules) => modules,
            Err(err) => {
                error!("failed to enumerate modules: {}", err);
                return Ok(());
            }
        };
        let mut shown = 0;
        for module in modules {
            if filter.is_some_and(|filter| {
                !module.short_name.eq_ignore_ascii_case(filter)
                    && !module.name.eq_ignore_ascii_case(filter)
            }) {
                continue;
            }
            shown += 1;
            let status = self
                .ctx
                .target
                .symbols
                .module_symbol_status(dtb, module.base_address);
            let source = self
                .ctx
                .target
                .symbols
                .module_symbol_source(dtb, module.base_address);
            let identity = self
                .ctx
                .target
                .symbols
                .module_pdb_identity(dtb, module.base_address);
            outln!("{} ({})", module.name, module.short_name);
            outln!(
                "  range   : {} - {}",
                ui::addr(module.base_address.0),
                ui::addr(module.end_address().0)
            );
            outln!(
                "  symbols : {}",
                status
                    .as_ref()
                    .map(|status| status.label())
                    .unwrap_or("unknown")
            );
            outln!(
                "  source  : {}",
                source.as_ref().map(|source| source.label()).unwrap_or("-")
            );
            match identity {
                Some(identity) => {
                    outln!("  pdb guid: {:032X}", identity.guid);
                    outln!("  pdb age : {}", identity.age);
                }
                None => outln!("  pdb     : -"),
            }
            if let Some(ModuleSymbolStatus::Failed(reason)) = status {
                outln!("  error   : {}", reason);
            }
            outln!();
        }
        if shown == 0 {
            outln!("no matching modules\n");
        }
        Ok(())
    }
}

#[derive(Debug, Default, PartialEq, Eq)]
struct LsArgs {
    /// `.`: list from the current line rather than continuing.
    restart: bool,
    first: Option<u32>,
    count: Option<u32>,
}

#[derive(Debug, Default, PartialEq, Eq)]
struct LsaArgs {
    address: Option<String>,
    first: Option<i64>,
    count: Option<u32>,
}

/// WinDbg's `ls [.] [first][,count]`: the line and count are decimal, and
/// the comma may carry spaces around it (`ls 10, 5`, `ls ,20`).
fn parse_ls_args<S: AsRef<str>>(argv: &[S]) -> Option<LsArgs> {
    let mut spec = LsArgs::default();
    let joined = argv.iter().map(AsRef::as_ref).collect::<Vec<_>>().join(" ");
    let mut rest = joined.trim();
    if let Some(tail) = rest.strip_prefix('.') {
        spec.restart = true;
        rest = tail.trim_start();
    }
    if rest.is_empty() {
        return Some(spec);
    }
    let (first, count) = match rest.split_once(',') {
        Some((first, count)) => (first.trim(), Some(count.trim())),
        None => (rest, None),
    };
    if !first.is_empty() {
        spec.first = Some(first.parse().ok().filter(|line| *line > 0)?);
    }
    if let Some(count) = count {
        spec.count = Some(count.parse().ok().filter(|count| *count > 0)?);
    }
    Some(spec)
}

/// WinDbg's `lsa [address][,first][,count]`: the address is an expression
/// (so it may contain spaces), the offset is a signed decimal, the count a
/// positive decimal.
fn parse_lsa_args<S: AsRef<str>>(argv: &[S]) -> Option<LsaArgs> {
    let joined = argv.iter().map(AsRef::as_ref).collect::<Vec<_>>().join(" ");
    let mut parts = joined.split(',').map(str::trim);
    let mut spec = LsaArgs {
        address: parts
            .next()
            .filter(|text| !text.is_empty())
            .map(str::to_string),
        ..LsaArgs::default()
    };
    if let Some(first) = parts.next().filter(|text| !text.is_empty()) {
        spec.first = Some(first.parse().ok()?);
    }
    if let Some(count) = parts.next().filter(|text| !text.is_empty()) {
        spec.count = Some(count.parse().ok().filter(|count| *count > 0)?);
    }
    if parts.next().is_some() {
        return None;
    }
    Some(spec)
}

#[cfg(test)]
mod tests {
    use super::{LsArgs, LsaArgs, parse_ls_args, parse_lsa_args};
    use crate::output::capture;
    use crate::repl::{CommandStyle, ReplState, parse_command};
    use crate::session::session_over_memory;
    use crate::symbols::{FieldInfo, ParsedType, TypeInfo, parse_source_paths};
    use crate::types::VirtAddr;

    #[test]
    fn source_listing_arguments_follow_windbg() {
        let ls = |argv: &[&str]| parse_ls_args(argv);
        assert_eq!(ls(&[]), Some(LsArgs::default()));
        assert_eq!(
            ls(&["."]),
            Some(LsArgs {
                restart: true,
                ..LsArgs::default()
            })
        );
        assert_eq!(
            ls(&["120,", "5"]),
            Some(LsArgs {
                restart: false,
                first: Some(120),
                count: Some(5),
            })
        );
        assert_eq!(
            ls(&[",20"]),
            Some(LsArgs {
                count: Some(20),
                ..LsArgs::default()
            })
        );
        assert_eq!(ls(&["0"]), None);
        assert_eq!(ls(&["12,0"]), None);

        let lsa = |argv: &[&str]| parse_lsa_args(argv);
        assert_eq!(lsa(&[]), Some(LsaArgs::default()));
        assert_eq!(
            lsa(&["nt!KeBugCheckEx", "+", "0x10,-2,4"]),
            Some(LsaArgs {
                address: Some("nt!KeBugCheckEx + 0x10".to_string()),
                first: Some(-2),
                count: Some(4),
            })
        );
        assert_eq!(
            lsa(&[",,3"]),
            Some(LsaArgs {
                count: Some(3),
                ..LsaArgs::default()
            })
        );
        assert_eq!(lsa(&["1000,1,2,3"]), None);
    }

    /// `lsa` lists around the address's line and marks it; a following bare
    /// `ls` picks up after the listed window.
    #[test]
    fn lsa_marks_the_line_and_ls_continues_after_it() {
        let dir = std::env::temp_dir().join(format!("ntoseye-ls-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let source = dir.join("driver.c");
        let text: String = (1..=30).map(|n| format!("line {n}\n")).collect();
        std::fs::write(&source, text).unwrap();

        let mut session = session_over_memory(0x1000, &[0x90; 0x100]);
        let dtb = session.target.current_dtb();
        session.target.symbols.inject_source_lines_for_test(
            7,
            dtb,
            VirtAddr(0x1000),
            0x100,
            "D:\\src\\driver.c",
            &[(0x0, Some(0x10), 12), (0x10, Some(0x10), 20)],
        );
        session
            .target
            .symbols
            .set_source_paths(parse_source_paths(&[format!("D:\\src={}", dir.display())]));
        let mut state = ReplState::for_oneshot(&mut session);

        let (result, text) = capture(|| state.dispatch_line("lsa 0x1014,-1,3"));
        result.unwrap();
        let listed: Vec<&str> = text.lines().skip(1).take(3).collect();
        assert_eq!(
            listed,
            ["     19: line 19", ">    20: line 20", "     21: line 21"],
            "{text}"
        );

        let (result, text) = capture(|| state.dispatch_line("ls ,2"));
        result.unwrap();
        let listed: Vec<&str> = text.lines().skip(1).take(2).collect();
        assert_eq!(listed, ["     22: line 22", "     23: line 23"], "{text}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

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

    #[test]
    fn ev_reads_each_masm_width() {
        let memory = [0x78, 0x56, 0x34, 0x12, 0xaa, 0xbb, 0xcc, 0xdd];
        let mut session = session_over_memory(0x1000, &memory);
        let mut state = ReplState::for_oneshot(&mut session);
        for (line, expected) in [
            ("? by(1000)", "0000000000000078"),
            ("? wo(1000)", "0000000000005678"),
            ("? dwo(1000)", "0000000012345678"),
            ("? qwo(1000)", "ddccbbaa12345678"),
            ("? poi(1000)", "ddccbbaa12345678"),
        ] {
            let (result, text) = capture(|| state.dispatch_line(line));
            result.unwrap();
            assert!(text.contains(expected), "{line} printed {text:?}");
        }
    }

    #[test]
    fn ev_renders_typed_values_with_their_type() {
        let mut memory = [0u8; 0x20];
        memory[..4].copy_from_slice(&0x12345678u32.to_le_bytes());
        memory[8..16].copy_from_slice(&0x1000u64.to_le_bytes());
        let mut session = session_over_memory(0x1000, &memory);
        let dtb = session.target.current_dtb();
        session.target.symbols.set_kernel(Some(1), dtb);
        session.target.symbols.inject_module_for_test(
            1,
            vec![TypeInfo {
                name: "_NODE".to_string(),
                pointer_size: 8,
                size: 0x10,
                fields: [(
                    "Value".to_string(),
                    FieldInfo {
                        offset: 0,
                        size: 4,
                        type_data: ParsedType::Primitive("ULONG".to_string()),
                    },
                )]
                .into_iter()
                .collect(),
            }],
            &[],
        );
        let mut state = ReplState::for_oneshot(&mut session);

        let (result, text) = capture(|| state.dispatch_line("? ((_NODE*)1000)->Value"));
        result.unwrap();
        assert!(text.contains("ULONG 0x12345678"), "field value: {text:?}");

        let (result, text) = capture(|| state.dispatch_line("? &((_NODE*)1000)->Value"));
        result.unwrap();
        assert!(text.contains("ULONG* 0x1000"), "field address: {text:?}");

        let (result, text) = capture(|| state.dispatch_line("? *((_NODE*)1000)"));
        result.unwrap();
        assert!(
            text.contains("_NODE at 0000000000001000") && text.contains("dt _NODE 0x1000"),
            "aggregate: {text:?}"
        );
    }
}