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
use owo_colors::OwoColorize;

use crate::backend::MemoryOps;
use crate::error::Error;
use crate::gdb::{BreakpointManager, RegisterMap};
use crate::symbols::SourceLocation;
use crate::target::Target;
use crate::types::{Arch, VirtAddr};
use crate::ui;
use crate::unwind::{
    FrameSource, StackTrace, ThreadTraceContext, build_stacktrace, format_symbol,
    preferred_code_dtb,
};

pub fn print_section(title: &str) {
    outln!("\n{}", ui::label(title));
}

/// Begin a stop block: a blank line.
pub fn print_stop_separator() {
    outln!();
}

/// Print the detail lines attached to an event banner: muted `├─` for middle
/// children, `╰─` for the last. `indent` is 1 space below a badge banner,
/// 4 spaces for a nested level; it is never derived from the badge width.
///
/// Children may contain `\n` (see [`wrap_prose`]): continuation lines get a
/// `│` gutter while the branch continues, bare spaces after the last child.
pub fn print_event_children(indent: &str, children: &[String]) {
    for (idx, child) in children.iter().enumerate() {
        let last = idx + 1 == children.len();
        let glyph = if last { "╰─" } else { "├─" };
        let mut lines = child.lines();
        if let Some(first) = lines.next() {
            outln!("{indent}{} {}", ui::muted(glyph), first);
        }
        for continuation in lines {
            if last {
                outln!("{indent}   {continuation}");
            } else {
                outln!("{indent}{}  {continuation}", ui::muted(""));
            }
        }
    }
}

/// Wrap plain prose for display starting at terminal column `col`, capped at
/// 100 columns of prose. Returns a single line when stdout is not a terminal
/// (piped output wants one line per field) or the terminal is too narrow.
/// Wrap before styling; width math over ANSI escapes miscounts.
pub fn wrap_prose(text: &str, col: usize) -> Vec<String> {
    let Some((terminal_size::Width(w), _)) = terminal_size::terminal_size() else {
        return vec![text.to_string()];
    };
    let width = (w as usize).saturating_sub(col).min(100);
    if width < 20 {
        return vec![text.to_string()];
    }
    textwrap::wrap(text, width)
        .into_iter()
        .map(|line| line.into_owned())
        .collect()
}

pub fn format_rflags(flags: u64) -> String {
    const FLAGS: &[(u64, &str)] = &[
        (0, "CF"),
        (2, "PF"),
        (4, "AF"),
        (6, "ZF"),
        (7, "SF"),
        (8, "TF"),
        (9, "IF"),
        (10, "DF"),
        (11, "OF"),
        (14, "NT"),
        (16, "RF"),
        (17, "VM"),
        (18, "AC"),
        (19, "VIF"),
        (20, "VIP"),
        (21, "ID"),
    ];

    let mut names = FLAGS
        .iter()
        .filter_map(|(bit, name)| ((flags & (1u64 << bit)) != 0).then_some(*name))
        .collect::<Vec<_>>();

    let iopl = (flags >> 12) & 0x3;
    if iopl != 0 {
        names.push(match iopl {
            1 => "IOPL1",
            2 => "IOPL2",
            _ => "IOPL3",
        });
    }

    if names.is_empty() {
        String::new()
    } else {
        format!(" [{}]", names.join(" "))
    }
}

/// AArch64 condition-flag summary aligned beneath the 16-hex-digit `cpsr`
/// value: each flag letter sits under the hex digit that contains its bit
/// (NZCV under the digit for bits 31-28, DAIF under the digits for bits 11-8
/// and 7-4). Multiple flags in one digit are joined in bit order, pushing any
/// later column right.
fn format_cpsr(flags: u64) -> String {
    const FLAGS: &[(u32, &str)] = &[
        (31, "N"),
        (30, "Z"),
        (29, "C"),
        (28, "V"),
        (9, "D"),
        (8, "A"),
        (7, "I"),
        (6, "F"),
    ];
    // Per hex-digit columns; digit 0 covers bits 63-60, digit 15 bits 3-0.
    let mut columns: [Vec<&str>; 16] = std::array::from_fn(|_| Vec::new());
    for (bit, name) in FLAGS {
        if flags & (1u64 << bit) != 0 {
            columns[15 - (bit / 4) as usize].push(name);
        }
    }
    let mut line = vec![' '; 16];
    for (idx, names) in columns.iter().enumerate() {
        if names.is_empty() {
            continue;
        }
        let text: String = names.concat();
        let len = text.len();
        if idx + len > line.len() {
            continue;
        }
        for i in (idx..line.len() - len).rev() {
            line[i + len] = line[i];
        }
        for (i, ch) in text.chars().enumerate() {
            line[idx + i] = ch;
        }
    }
    line.into_iter().collect()
}

/// Print the general-purpose register grid. `embedded` is true inside the
/// break/status dump (`registers` section header, 2-space indent); standalone
/// `registers` passes false so it reads flush-left with no header, matching
/// `disasm`. The row layout follows the register map's architecture.
pub fn print_registers(register_map: &RegisterMap, regs: &[u8], embedded: bool) {
    let read_reg_value = |name: &str| register_map.read_u64(name, regs);
    let styled_value = |name: &str| -> String {
        match read_reg_value(name) {
            Ok(value) => ui::addr(value),
            Err(_) => ui::muted(&format!("{:<16}", "N/A")),
        }
    };
    let cell = |name: &str| {
        format!(
            "{} {}",
            ui::muted(&format!("{name:<3}")),
            styled_value(name)
        )
    };

    let indent = if embedded { "  " } else { "" };
    if embedded {
        print_section("registers");
    }

    // ARM64 register map: x0-x30 grid plus fp/lr/sp/pc and cpsr flags.
    if read_reg_value("pc").is_ok() {
        for row in [
            ["x0", "x1", "x2", "x3"],
            ["x4", "x5", "x6", "x7"],
            ["x8", "x9", "x10", "x11"],
            ["x12", "x13", "x14", "x15"],
            ["x16", "x17", "x18", "x19"],
            ["x20", "x21", "x22", "x23"],
            ["x24", "x25", "x26", "x27"],
        ] {
            outln!(
                "{indent}{}   {}   {}   {}",
                cell(row[0]),
                cell(row[1]),
                cell(row[2]),
                cell(row[3])
            );
        }
        outln!(
            "{indent}{}   {}   {}   {}",
            cell("x28"),
            cell("fp"),
            cell("lr"),
            cell("sp")
        );
        let cpsr = read_reg_value("cpsr").unwrap_or(0);
        outln!(
            "{indent}{}   {} {}",
            cell("pc"),
            ui::muted("cpsr"),
            styled_value("cpsr")
        );
        let flags = format_cpsr(cpsr);
        if !flags.is_empty() {
            // Align under the cpsr hex value: cell("pc") (4 + 16 chars) +
            // the "   cpsr " label, i.e. 28 columns.
            outln!("{indent}                            {flags}");
        }
        return;
    }

    let rflags = read_reg_value("eflags").unwrap_or(0);
    for row in [
        ["rax", "rbx", "rcx"],
        ["rdx", "rsi", "rdi"],
        ["rsp", "rbp", "rip"],
        ["r8", "r9", "r10"],
        ["r11", "r12", "r13"],
    ] {
        outln!(
            "{indent}{}   {}   {}",
            cell(row[0]),
            cell(row[1]),
            cell(row[2])
        );
    }
    outln!(
        "{indent}{}   {}   {} {}{}",
        cell("r14"),
        cell("r15"),
        ui::muted("rfl"),
        styled_value("eflags"),
        format_rflags(rflags)
    );
}

// Decoding lives in core; the REPL owns the *rendering*
// (`format_disasm_line`/`render_rows` below).
pub use crate::disasm::{
    AsmToken, DisasmRow, decode_preceding, decode_rows, decode_rows_arm64, disasm_formatter,
    max_instruction_bytes,
};

/// Width of the byte column for a listing: the longest hex string among the
/// rows about to be printed, so the asm column always aligns and never gets
/// pushed right by a long (up to 15-byte) instruction.
pub fn hex_column_width<'a>(hexes: impl Iterator<Item = &'a str>) -> usize {
    hexes.map(str::len).max().unwrap_or(0)
}

/// Render one disassembly line: yellow `>` cursor on the current
/// instruction, dim bytes, dim `;` comment with symbol. The single source of
/// truth for a disassembled instruction, shared by both call sites.
///
/// `hex_width` is the byte column width, computed per listing via
/// [`hex_column_width`] so the asm column stays aligned without overfilling.
pub fn format_disasm_line(
    ip: u64,
    hex: &str,
    tokens: &[AsmToken],
    comment: Option<&str>,
    marker: Option<bool>,
    hex_width: usize,
) -> String {
    // `marker` is None for a plain listing (no cursor column); Some(current) for
    // the break/status view, where the current instruction gets a yellow `>`
    let prefix = match marker {
        Some(true) => format!(" {} ", ">".yellow().bold()),
        Some(false) => "   ".to_string(),
        None => String::new(),
    };
    let bytes = format!("{hex:<hex_width$}").bright_black().to_string();
    let asm = ui::disasm_asm(tokens);
    let comment = comment
        .map(|sym| format!(" {} {}", ui::muted(";"), ui::symbol(sym)))
        .unwrap_or_default();
    format!("{}{}  {}  {}{}", prefix, ui::addr(ip), bytes, asm, comment)
}

/// Print decoded rows in the house style, sizing the byte column once across
/// all rows so the asm column aligns. `marker_for` gives each row its cursor
/// state: `None` for a plain listing (`disasm`), `Some(current)` for the
/// break/status view where the current instruction gets a `>`.
pub fn render_rows(rows: &[DisasmRow], marker_for: impl Fn(u64) -> Option<bool>) {
    let width = hex_column_width(rows.iter().map(|row| row.hex.as_str()));
    for row in rows {
        outln!(
            "{}",
            format_disasm_line(
                row.ip,
                &row.hex,
                &row.tokens,
                row.comment.as_deref(),
                marker_for(row.ip),
                width,
            )
        );
    }
}

const DISASM_CONTEXT_BYTES: usize = 64;
const DISASM_CONTEXT_INSTRUCTIONS: usize = 7;

/// Why the instruction at `pc` could not be read, in the terms the user can
/// act on.
///
/// A page that is not resident is the normal outcome of an execute breakpoint
/// on code nothing has run yet: a code breakpoint fault outranks the code page
/// fault of the instruction fetch (Intel SDM, "Priority Among Concurrent
/// Events": code breakpoint fault is priority 7, faults from fetching the next
/// instruction priority 8), so the trap is delivered before the page is
/// faulted in. The bytes appear once the instruction is actually fetched, so a
/// single step reveals them.
pub fn non_resident_note(pc: u64, error: &Error) -> String {
    match error {
        Error::BadVirtualAddress(_) | Error::AddressNotInDump(_) | Error::PartialRead(0) => {
            format!(
                "  (the page holding {pc:#x} is not resident, so there is nothing to decode yet; \
                 an execute breakpoint traps before the fetch that pages it in, and `t` \
                 single-steps through the fetch)"
            )
        }
        error => format!("  (could not read memory at {pc:#x}: {error})"),
    }
}

fn decode_disasm_context(
    bytes_at_rip: &[u8],
    rip: u64,
    arm64: bool,
    bitness: u32,
    resolve: impl Fn(u64) -> String,
) -> Vec<DisasmRow> {
    if arm64 {
        return decode_rows_arm64(
            bytes_at_rip,
            rip,
            Some(DISASM_CONTEXT_INSTRUCTIONS),
            resolve,
        );
    }
    let mut formatter = disasm_formatter();
    decode_rows(
        bytes_at_rip,
        rip,
        Some(DISASM_CONTEXT_INSTRUCTIONS),
        bitness,
        &mut formatter,
        resolve,
    )
}

pub fn print_disasm_context(
    debugger: &Target,
    breakpoints: &BreakpointManager,
    trace: &ThreadTraceContext,
    rip: u64,
) {
    print_section("disasm");

    let active_memory = debugger.address_space(trace.active_dtb);
    let code_dtb = preferred_code_dtb(trace, rip);
    let code_memory = debugger.address_space(code_dtb);
    let mut bytes = [0u8; DISASM_CONTEXT_BYTES];

    let read = match active_memory.read_bytes(VirtAddr(rip), &mut bytes) {
        Ok(()) => Ok(()),
        Err(active_error) if code_dtb == trace.active_dtb => Err(active_error),
        Err(_) => code_memory.read_bytes(VirtAddr(rip), &mut bytes),
    };
    if let Err(error) = read {
        outln!("{}", ui::muted(&non_resident_note(rip, &error)));
        return;
    }

    breakpoints.mask_breakpoint_bytes(VirtAddr(rip), &mut bytes, trace.active_dtb);

    let resolve = |target: u64| format_symbol(debugger, trace, target);
    let rows = decode_disasm_context(
        &bytes,
        rip,
        debugger.arch() == Arch::Arm64,
        debugger.code_bitness(VirtAddr(rip)),
        resolve,
    );
    render_rows(&rows, |ip| Some(ip == rip));
}

/// Print the stack frames. `embedded` is true inside the break/status dump:
/// bold `stack` header, 2-space indent, and no child-SP column (the return
/// address is the token you act on). Standalone `k` passes false:
/// flush-left, full child-SP + retaddr columns.
pub fn print_stacktrace(
    debugger: &Target,
    register_map: &RegisterMap,
    regs: &[u8],
    build_limit: usize,
    display_limit: usize,
    embedded: bool,
) {
    let stacktrace = build_stacktrace(debugger, register_map, regs, build_limit);
    print_stacktrace_data(&stacktrace, display_limit, embedded);
}

/// Render an already-collected stack trace in the same layout as [`print_stacktrace`].
pub fn print_stacktrace_data(stacktrace: &StackTrace, display_limit: usize, embedded: bool) {
    print_stacktrace_data_impl(stacktrace, display_limit, embedded, false);
}

pub fn print_stacktrace_data_with_provenance(
    stacktrace: &StackTrace,
    display_limit: usize,
    embedded: bool,
) {
    print_stacktrace_data_impl(stacktrace, display_limit, embedded, true);
}

fn format_source_location(location: &SourceLocation) -> String {
    let (label, path) = match location.local_path.as_ref() {
        Some(path) if location.local_exists => ("local", path.display().to_string()),
        Some(path) => ("mapped", path.display().to_string()),
        None => ("recorded", location.file.clone()),
    };
    match location.column {
        Some(column) => format!("[{label} {path}:{}:{column}]", location.line),
        None => format!("[{label} {path}:{}]", location.line),
    }
}

fn print_stacktrace_data_impl(
    stacktrace: &StackTrace,
    display_limit: usize,
    embedded: bool,
    show_provenance: bool,
) {
    let indent = if embedded { "  " } else { "" };
    if embedded {
        print_section("stack");
    }

    let shown = stacktrace.frames.len().min(display_limit);

    for (num, frame) in stacktrace.frames.iter().take(shown).enumerate() {
        let mut annotations = Vec::new();
        if !frame.symbol.starts_with("0x") {
            annotations.push(ui::symbol(&frame.symbol));
        }
        if show_provenance {
            annotations.push(
                format!("[{}]", frame.source.as_str())
                    .bright_black()
                    .to_string(),
            );
        } else if frame.source == FrameSource::Scan {
            annotations.push("[scan]".bright_black().to_string());
        }
        if let Some(location) = frame.source_location.as_ref() {
            annotations.push(format_source_location(location).bright_black().to_string());
        }
        let annotation = if annotations.is_empty() {
            String::new()
        } else {
            format!("  {}", annotations.join(" "))
        };
        if embedded {
            outln!(
                "{indent}{} {}{}",
                ui::muted(&format!("#{num:<2}")),
                ui::addr(frame.ip),
                annotation
            );
        } else {
            outln!(
                "{indent}{} {}  {}{}",
                ui::muted(&format!("#{num:<2}")),
                ui::addr(frame.sp),
                ui::addr(frame.ip),
                annotation
            );
        }
    }

    let hidden = stacktrace.frames.len().saturating_sub(display_limit) + stacktrace.truncated;
    if hidden > 0 {
        outln!(
            "{indent}{}",
            format!("... {} more frames", hidden).bright_black()
        );
    }
}

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

    #[test]
    fn stop_disassembly_starts_at_rip_and_only_looks_forward() {
        let rip = 0xffff_f807_c0e1_3ae0;
        let rows = decode_disasm_context(&[0x90; 8], rip, false, 64, |_| String::new());
        let ips = rows.iter().map(|row| row.ip).collect::<Vec<_>>();

        assert_eq!(ips, (rip..rip + 7).collect::<Vec<_>>());
    }

    #[test]
    fn cpsr_flags_align_under_hex_digits() {
        assert_eq!(format_cpsr(0x6000_0044), "        ZC    F ");
        assert_eq!(format_cpsr(0x8000_01c4), "        N    AIF");
        assert_eq!(format_cpsr(0x0000_0000), "                ");
    }

    #[test]
    fn source_location_labels_recorded_and_local_paths() {
        let recorded = SourceLocation {
            file: r"C:\build\driver.c".into(),
            line: 42,
            column: Some(7),
            local_path: None,
            local_exists: false,
        };
        assert_eq!(
            format_source_location(&recorded),
            r"[recorded C:\build\driver.c:42:7]"
        );

        let local = SourceLocation {
            local_path: Some("/checkout/driver.c".into()),
            local_exists: true,
            ..recorded
        };
        assert_eq!(
            format_source_location(&local),
            "[local /checkout/driver.c:42:7]"
        );
    }
}