ntoseye 0.21.0

Windows kernel debugger for Linux hosts running Windows under KVM/QEMU
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
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, OnceLock};

/// Per-frame unwinder diagnostics, gated on `NTOSEYE_UNWIND_TRACE`. Prints which
/// branch each `unwind_once` takes so early bail-outs (no function entry, bad
/// codes, failed reads) can be told apart from a genuine leaf pop.
fn unwind_trace_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| std::env::var_os("NTOSEYE_UNWIND_TRACE").is_some())
}

macro_rules! unwind_trace {
    ($($arg:tt)*) => {
        if unwind_trace_enabled() {
            eprintln!($($arg)*);
        }
    };
}

use std::cmp::Ordering;

use pelite::pe64::{
    Pe, PeView,
    image::{
        IMAGE_DIRECTORY_ENTRY_EXCEPTION, IMAGE_SCN_MEM_EXECUTE, RUNTIME_FUNCTION,
        UNW_FLAG_CHAININFO, UWOP_ALLOC_LARGE, UWOP_ALLOC_SMALL, UWOP_PUSH_MACHFRAME,
        UWOP_PUSH_NONVOL, UWOP_SAVE_NONVOL, UWOP_SAVE_NONVOL_FAR, UWOP_SAVE_XMM128,
        UWOP_SAVE_XMM128_FAR, UWOP_SET_FPREG,
    },
};

use crate::{
    backend::MemoryOps,
    bugchecks::looks_like_kernel_pointer,
    error::{Error, Result},
    gdb::RegisterMap,
    guest::{Guest, ModuleInfo, PeImage, ProcessInfo, read_pe_image, read_pe_image_from_file},
    memory::{AddressSpace, DTB_IDENTITY},
    phys::PhysMem,
    symbols::{SourceLocation, SymbolStore},
    target::{SavedThreadRegisters, Target, ThreadInfo},
    trapframe::{decode_kswitch_frame_seed, decode_ktrap_frame_for_thread},
    types::{Dtb, VirtAddr},
};

const CR3_PAGE_MASK: u64 = 0x000F_FFFF_FFFF_F000;
const STACK_SCAN_BYTES: usize = 0x1000;
// cap on chained unwind entries followed per frame, guarding against cyclic or
// corrupt unwind data
const MAX_CHAIN_DEPTH: usize = 32;
// hard cap on frames walked, so a stack switch (which relaxes the rsp-advances
// guard) can't let a cyclic/corrupt stack spin forever
const MAX_UNWIND_FRAMES: usize = 1024;

// version-2 unwind opcodes that pelite 0.10 doesn't define. They describe epilog
// locations and don't affect prolog-based unwinding, but must be counted so the
// code iterator stays aligned with the slot stream
const UWOP_EPILOG: u8 = 6;
const UWOP_SPARE_CODE: u8 = 7;
const UNWIND_REG_NAMES: [&str; 16] = [
    "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13",
    "r14", "r15",
];

#[derive(Debug, Clone)]
pub struct ThreadTraceContext {
    pub description: String,
    pub active_dtb: Dtb,
    pub kernel_dtb: Dtb,
    pub process_dtb: Option<Dtb>,
    pub kernel_modules: Vec<ModuleInfo>,
    pub process_modules: Vec<ModuleInfo>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameSource {
    Current,
    Seed,
    Unwind,
    Scan,
}

impl FrameSource {
    /// Stable lowercase tag for how a frame was recovered, surfaced by every
    /// host. Explicit rather than derived from `Debug`, which would drift if a
    /// variant were renamed.
    pub fn as_str(self) -> &'static str {
        match self {
            FrameSource::Current => "current",
            FrameSource::Seed => "seed",
            FrameSource::Unwind => "unwind",
            FrameSource::Scan => "scan",
        }
    }
}

#[derive(Debug, Clone)]
pub struct StackFrame {
    pub sp: u64,
    pub ip: u64,
    pub symbol: String,
    pub source: FrameSource,
    pub source_location: Option<SourceLocation>,
}

#[derive(Debug, Clone, Default)]
pub struct StackTrace {
    pub frames: Vec<StackFrame>,
    pub truncated: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThreadStackSource {
    TrapFrame { address: VirtAddr },
    ContextSwitch { kernel_stack: VirtAddr },
}

impl ThreadStackSource {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::TrapFrame { .. } => "ktrap-frame",
            Self::ContextSwitch { .. } => "kernel-stack",
        }
    }
}

#[derive(Debug, Clone)]
pub struct ThreadStackTrace {
    pub source: ThreadStackSource,
    pub stacktrace: StackTrace,
}

#[derive(Clone, Debug)]
struct RegisterContext {
    rip: u64,
    rsp: u64,
    regs: [Option<u64>; 16],
}

#[derive(Debug, Clone)]
struct CachedModule {
    info: ModuleInfo,
    // Arc so a frame walk can cheaply take its own handle to the image and
    // release the borrow on the cache while parsing unwind data
    image: Arc<PeImage>,
    executable_ranges: Vec<(u32, u32)>,
}

#[derive(Debug, Clone)]
struct OwnedModule {
    info: ModuleInfo,
    dtb: Dtb,
}

#[derive(Debug, Clone, Copy)]
struct UnwindCodeSlot {
    code_offset: u8,
    unwind_op: u8,
    op_info: u8,
    raw_op_info: u8,
}

#[derive(Debug, Clone)]
struct ParsedUnwindInfo {
    size_of_prolog: u8,
    frame_register: u8,
    frame_offset: u8,
    codes: Vec<UnwindCodeSlot>,
    /// Present when this is a chained entry (`UNW_FLAG_CHAININFO`): the parent
    /// RUNTIME_FUNCTION's unwind-data RVA, so the walk can follow the chain
    chained_unwind_data: Option<u32>,
}

/// Outcome of applying one frame's unwind codes
enum UnwindStep {
    /// Codes applied; keep going (pop the return address or follow a chain)
    Continue,
    /// A hardware trap/interrupt frame set rip+rsp directly; the frame is complete
    MachineFrame,
}

/// Outcome of unwinding one frame to its caller
enum Unwound {
    /// Could not unwind further; the caller falls back to a stack scan
    Stop,
    /// Advanced to the caller. `stack_switch` is set when we crossed a hardware
    /// trap/interrupt frame, where rsp may move to a different stack (e.g. an IST
    /// or the idle stack) and so need not be greater than the previous rsp.
    Frame { stack_switch: bool },
}

struct StackTracer<'a> {
    trace: &'a ThreadTraceContext,
    phys: &'a PhysMem,
    symbols: &'a SymbolStore,
    memory: AddressSpace<'a, PhysMem>,
    modules: HashMap<(Dtb, u64), CachedModule>,
}

pub fn resolve_thread_trace_context(debugger: &Target, cr3: u64) -> ThreadTraceContext {
    let cr3_masked = cr3 & CR3_PAGE_MASK;
    let kernel_dtb = debugger.kernel_dtb();
    let kernel_dtb_masked = kernel_dtb & CR3_PAGE_MASK;

    // Triage dumps use DTB_IDENTITY — page-table walks are impossible,
    // so force the kernel context regardless of the thread's real CR3.
    if kernel_dtb == DTB_IDENTITY || cr3_masked == kernel_dtb_masked {
        return ThreadTraceContext {
            description: "kernel".to_string(),
            active_dtb: kernel_dtb,
            kernel_dtb,
            process_dtb: None,
            kernel_modules: debugger.kernel_modules().unwrap_or_default(),
            process_modules: Vec::new(),
        };
    }

    if let Some(proc_info) = find_process_by_cr3(debugger, cr3_masked) {
        let process_modules = debugger
            .guest
            .as_ref()
            .map(|g| g.process_modules(&proc_info).unwrap_or_default())
            .unwrap_or_default();
        return ThreadTraceContext {
            description: format!("{} ({})", proc_info.name, proc_info.pid),
            active_dtb: cr3_masked,
            kernel_dtb,
            process_dtb: Some(proc_info.dtb),
            kernel_modules: debugger.kernel_modules().unwrap_or_default(),
            process_modules,
        };
    }

    ThreadTraceContext {
        description: "unknown".to_string(),
        active_dtb: cr3_masked,
        kernel_dtb,
        process_dtb: None,
        kernel_modules: debugger.kernel_modules().unwrap_or_default(),
        process_modules: Vec::new(),
    }
}

pub fn try_format_symbol(
    debugger: &Target,
    trace: &ThreadTraceContext,
    addr: u64,
) -> Option<String> {
    let try_format = |dtb| {
        debugger
            .symbols
            .format_closest_symbol_for_address(dtb, VirtAddr(addr))
    };

    if let Some(module) = trace.module_for_address(addr) {
        return Some(try_format(module.dtb).unwrap_or_else(|| {
            // TODO lazily load module symbols on stop so user return addresses resolve past module+offset.
            let offset = addr.saturating_sub(module.info.base_address.0);
            format!("{}+{:#x}", module.info.short_name, offset)
        }));
    }

    if let Some(process_dtb) = trace.process_dtb
        && let Some(symbol) = try_format(process_dtb)
    {
        return Some(symbol);
    }

    try_format(trace.kernel_dtb)
}

pub fn format_symbol(debugger: &Target, trace: &ThreadTraceContext, addr: u64) -> String {
    try_format_symbol(debugger, trace, addr).unwrap_or_else(|| format!("{addr:#x}"))
}

pub fn preferred_code_dtb(trace: &ThreadTraceContext, addr: u64) -> Dtb {
    trace
        .module_for_address(addr)
        .map(|module| module.dtb)
        .unwrap_or(trace.active_dtb)
}

fn frame_source_location(
    debugger: &Target,
    trace: &ThreadTraceContext,
    address: u64,
) -> Option<SourceLocation> {
    let module = trace.module_for_address(address)?;
    debugger
        .symbols
        .source_location(module.dtb, VirtAddr(address))
}
/// Resolve the x64 runtime-function entry containing `address`.
///
/// PE exception metadata is the authoritative function boundary for `uf`: it
/// remains correct when public symbols are sparse and avoids disassembling into
/// the next function. A paged-out `.pdata` table is retried against the matched
/// on-disk image through the same cache path used by the stack unwinder.
pub fn function_range(
    debugger: &Target,
    trace: &ThreadTraceContext,
    address: u64,
) -> Option<(u64, u64)> {
    fn range(image: &PeImage, base: u64, address: u64) -> Option<(u64, u64)> {
        let view = PeView::from_bytes(image.as_slice()).ok()?;
        let functions = view.exception().ok()?;
        let rva = u32::try_from(address.checked_sub(base)?).ok()?;
        let function = lookup_runtime_function(functions.image(), rva)?;
        Some((
            base + u64::from(function.BeginAddress),
            base + u64::from(function.EndAddress),
        ))
    }

    let mut tracer = StackTracer::new(debugger, trace);
    let base = tracer.module_containing(address)?.info.base_address.0;
    let image = tracer.module_image(address)?;
    if let Some(found) = range(&image, base, address) {
        return Some(found);
    }

    if !image.is_complete() && tracer.upgrade_module_image(address) {
        let image = tracer.module_image(address)?;
        return range(&image, base, address);
    }

    None
}

fn function_body_address(
    debugger: &Target,
    trace: &ThreadTraceContext,
    address: u64,
) -> Option<u64> {
    let (_, end) = function_range(debugger, trace, address)?;
    let mut tracer = StackTracer::new(debugger, trace);
    let base = tracer.module_containing(address)?.info.base_address.0;
    let mut image = tracer.module_image(address)?;
    let mut resolved = resolve_function(&image, base, address);
    if matches!(resolved, Resolve::Holed)
        && !image.is_complete()
        && tracer.upgrade_module_image(address)
    {
        image = tracer.module_image(address)?;
        resolved = resolve_function(&image, base, address);
    }

    let Resolve::Function { unwind_data, begin } = resolved else {
        return None;
    };
    let unwind = parse_unwind_info(&image, unwind_data)?;
    let body = base
        .checked_add(u64::from(begin))?
        .checked_add(u64::from(unwind.size_of_prolog))?;
    (body < end).then_some(body)
}

/// Recover the build-specific context-switch frame using the matching image's
/// x64 unwind metadata. `KTHREAD.KernelStack` is the RSP saved inside
/// `SwapContext`; no private `_KSWITCH_FRAME` layout or build table is needed.
fn recover_context_switch_seed(
    debugger: &Target,
    process_dtb: Dtb,
    kernel_stack: VirtAddr,
) -> Result<RegisterContext> {
    let ntoskrnl = &debugger.guest()?.ntoskrnl;
    let swap_context = ntoskrnl.symbol("SwapContext")?.address().0;
    let ki_swap_context = ntoskrnl.symbol("KiSwapContext")?.address().0;
    let trace = resolve_thread_trace_context(debugger, process_dtb);
    let body_rip = function_body_address(debugger, &trace, swap_context)
        .ok_or_else(|| Error::DebugInfo("SwapContext has no usable PE unwind metadata".into()))?;
    let ki_swap_range = function_range(debugger, &trace, ki_swap_context)
        .ok_or_else(|| Error::DebugInfo("KiSwapContext has no usable PE unwind metadata".into()))?;

    let mut tracer = StackTracer::new(debugger, &trace);
    let mut seed = RegisterContext {
        rip: body_rip,
        rsp: kernel_stack.0,
        regs: [None; 16],
    };
    if !matches!(
        tracer.unwind_once(&mut seed),
        Unwound::Frame {
            stack_switch: false
        }
    ) {
        return Err(Error::DebugInfo(
            "failed to unwind the saved SwapContext frame".into(),
        ));
    }
    if seed.rsp <= kernel_stack.0 || !(ki_swap_range.0..ki_swap_range.1).contains(&seed.rip) {
        return Err(Error::DebugInfo(format!(
            "SwapContext returned outside KiSwapContext ({:#x}, RSP {:#x})",
            seed.rip, seed.rsp
        )));
    }

    // Validate that the next unwind is coherent, but keep `seed` private to the
    // stack walker. It is not a complete saved register context: x64 unwind data
    // can recover nonvolatile registers while crossing KiSwapContext, but the
    // volatile registers and RFLAGS were never preserved. Full parked-thread
    // register display would need a real architecture-defined snapshot (for
    // example matching KTRAP/KEXCEPTION frames), plus per-register provenance;
    // splicing values recovered at different unwind phases is not such a snapshot.
    let mut caller = seed.clone();
    if !matches!(
        tracer.unwind_once(&mut caller),
        Unwound::Frame {
            stack_switch: false
        }
    ) || caller.rsp <= seed.rsp
        || !tracer.is_executable_address(caller.rip)
    {
        return Err(Error::DebugInfo(
            "failed to validate the saved KiSwapContext frame".into(),
        ));
    }

    Ok(seed)
}

pub fn build_stacktrace(
    debugger: &Target,
    register_map: &RegisterMap,
    regs: &[u8],
    limit: usize,
) -> StackTrace {
    let cr3 = register_map.read_u64("cr3", regs).unwrap_or(0);
    let trace = resolve_thread_trace_context(debugger, cr3);
    build_stacktrace_seeded(
        debugger,
        &trace,
        RegisterContext::from_registers(register_map, regs),
        FrameSource::Current,
        limit,
    )
}

fn switch_seed_is_plausible(thread: &ThreadInfo, seed: &RegisterContext) -> bool {
    let (Some(kernel_stack), Some(stack_limit), Some(stack_base)) =
        (thread.kernel_stack, thread.stack_limit, thread.stack_base)
    else {
        return false;
    };
    thread.kernel_stack_resident != Some(false)
        && looks_like_kernel_pointer(seed.rip)
        && kernel_stack >= stack_limit
        && kernel_stack < stack_base
        && seed.rsp >= stack_limit.0
        && seed.rsp <= stack_base.0
}

/// Build a non-running Windows thread's kernel stack without manufacturing a
/// persistent register context. A real KTRAP_FRAME is preferred; otherwise the
/// context-switch bootstrap remains private to this stack walk.
pub fn build_parked_thread_stack(
    debugger: &Target,
    thread: &ThreadInfo,
    limit: usize,
) -> Result<ThreadStackTrace> {
    let process_dtb = debugger.thread_process_dtb(thread).ok_or_else(|| {
        Error::DebugInfo("parked thread owning process DTB is unavailable".into())
    })?;
    let trace = resolve_thread_trace_context(debugger, process_dtb);
    let mut failures = Vec::new();

    if let Some(address) = thread.trap_frame {
        match decode_ktrap_frame_for_thread(debugger, process_dtb, address)
            .ok()
            .and_then(|registers| RegisterContext::from_saved(&registers))
        {
            Some(seed) if seed.rip != 0 && seed.rsp != 0 => {
                return Ok(ThreadStackTrace {
                    source: ThreadStackSource::TrapFrame { address },
                    stacktrace: build_stacktrace_seeded(
                        debugger,
                        &trace,
                        seed,
                        FrameSource::Seed,
                        limit,
                    ),
                });
            }
            _ => failures.push("KTHREAD.TrapFrame is absent or unusable".to_string()),
        }
    } else {
        failures.push("KTHREAD.TrapFrame is not present".to_string());
    }

    if let Some(kernel_stack) = thread.kernel_stack {
        let pdb_seed = decode_kswitch_frame_seed(debugger, process_dtb, kernel_stack)
            .ok()
            .and_then(|registers| RegisterContext::from_saved(&registers));
        let seed = match pdb_seed {
            Some(seed) => Ok(seed),
            None => recover_context_switch_seed(debugger, process_dtb, kernel_stack),
        };
        match seed {
            Ok(seed) if switch_seed_is_plausible(thread, &seed) => {
                return Ok(ThreadStackTrace {
                    source: ThreadStackSource::ContextSwitch { kernel_stack },
                    stacktrace: build_stacktrace_seeded(
                        debugger,
                        &trace,
                        seed,
                        FrameSource::Seed,
                        limit,
                    ),
                });
            }
            Ok(_) => failures.push(
                "context-switch seed is outside the captured resident kernel stack".to_string(),
            ),
            Err(error) => failures.push(format!("context-switch seed is unavailable: {error}")),
        }
    } else {
        failures.push("KTHREAD.KernelStack is not present".to_string());
    }

    Err(Error::DebugInfo(format!(
        "parked thread stack unavailable: {}",
        failures.join("; ")
    )))
}

fn build_stacktrace_seeded(
    debugger: &Target,
    trace: &ThreadTraceContext,
    mut context: RegisterContext,
    initial_source: FrameSource,
    limit: usize,
) -> StackTrace {
    let limit = limit.max(1);
    let mut raw: Vec<(u64, u64, FrameSource)> = vec![(context.rsp, context.rip, initial_source)];
    let mut tracer = StackTracer::new(debugger, trace);
    let mut seen = HashSet::from([context.rip]);

    // RSP normally advances every step. A trap/interrupt frame can switch to a
    // different stack, so the hard frame cap remains the final corruption guard.
    for _ in 0..MAX_UNWIND_FRAMES {
        let previous_rip = context.rip;
        let previous_rsp = context.rsp;

        let stack_switch = match tracer.unwind_once(&mut context) {
            Unwound::Stop => break,
            Unwound::Frame { stack_switch } => stack_switch,
        };

        if context.rip == 0 || context.rip == previous_rip {
            break;
        }
        if !stack_switch && context.rsp <= previous_rsp {
            break;
        }

        seen.insert(context.rip);
        raw.push((context.rsp, context.rip, FrameSource::Unwind));
    }

    for (sp, ip) in tracer.scan_stack(context.rsp, &seen) {
        raw.push((sp, ip, FrameSource::Scan));
    }

    ensure_frame_module_symbols(debugger, trace, raw.iter().map(|(_, ip, _)| *ip));

    let mut stacktrace = StackTrace::default();
    for (sp, ip, source) in raw {
        record_stack_frame(
            &mut stacktrace,
            limit,
            StackFrame {
                sp,
                ip,
                symbol: format_symbol(debugger, trace, ip),
                source,
                source_location: frame_source_location(debugger, trace, ip),
            },
        );
    }
    stacktrace
}

/// Lazily load symbols for the modules a backtrace touches. Only modules with no
/// prior load attempt are fetched (so kernel modules, loaded on stop, and an
/// attached process's modules are skipped), and each is loaded once per session.
fn ensure_frame_module_symbols(
    debugger: &Target,
    trace: &ThreadTraceContext,
    ips: impl Iterator<Item = u64>,
) {
    let mut by_dtb: HashMap<Dtb, Vec<ModuleInfo>> = HashMap::new();
    let mut seen: HashSet<(Dtb, u64)> = HashSet::new();
    for ip in ips {
        let Some(module) = trace.module_for_address(ip) else {
            continue;
        };
        let key = (module.dtb, module.info.base_address.0);
        if seen.insert(key)
            && debugger
                .symbols
                .module_symbol_status(module.dtb, module.info.base_address)
                .is_none()
        {
            by_dtb.entry(module.dtb).or_default().push(module.info);
        }
    }

    for (dtb, modules) in by_dtb {
        let _ = if let Some(g) = debugger.guest.as_ref() {
            g.load_symbols_for_modules(&debugger.phys, &debugger.symbols, modules, dtb)
        } else {
            Guest::load_module_symbols(&debugger.phys, &debugger.symbols, modules, dtb, false)
        };
    }
}

fn record_stack_frame(stacktrace: &mut StackTrace, limit: usize, frame: StackFrame) {
    if stacktrace.frames.len() < limit {
        stacktrace.frames.push(frame);
    } else {
        stacktrace.truncated += 1;
    }
}

fn find_process_by_cr3(debugger: &Target, cr3_masked: u64) -> Option<ProcessInfo> {
    debugger
        .guest
        .as_ref()?
        .enumerate_processes()
        .ok()?
        .into_iter()
        .find(|proc| (proc.dtb & CR3_PAGE_MASK) == cr3_masked)
}

impl RegisterContext {
    fn from_registers(register_map: &RegisterMap, regs: &[u8]) -> Self {
        let mut register_values = [None; 16];
        for (index, name) in UNWIND_REG_NAMES.iter().enumerate() {
            register_values[index] = register_map.read_u64(*name, regs).ok();
        }

        Self {
            rip: register_map.read_u64("rip", regs).unwrap_or(0),
            rsp: register_map.read_u64("rsp", regs).unwrap_or(0),
            regs: register_values,
        }
    }

    fn from_saved(registers: &SavedThreadRegisters) -> Option<Self> {
        let rip = registers.rip?;
        let rsp = registers.rsp?;
        let mut values = [None; 16];
        for (index, name) in UNWIND_REG_NAMES.iter().enumerate() {
            values[index] = registers.get(name);
        }
        Some(Self {
            rip,
            rsp,
            regs: values,
        })
    }

    fn get(&self, register: u8) -> Option<u64> {
        match register {
            4 => Some(self.rsp),
            _ => self.regs.get(register as usize).copied().flatten(),
        }
    }

    fn set(&mut self, register: u8, value: u64) {
        if register == 4 {
            self.rsp = value;
        }

        if let Some(slot) = self.regs.get_mut(register as usize) {
            *slot = Some(value);
        }
    }
}

impl ThreadTraceContext {
    fn module_for_address(&self, address: u64) -> Option<OwnedModule> {
        self.kernel_modules
            .iter()
            .find(|module| module.contains_address(VirtAddr(address)))
            .cloned()
            .map(|info| OwnedModule {
                info,
                dtb: self.kernel_dtb,
            })
            .or_else(|| {
                self.process_modules
                    .iter()
                    .find(|module| module.contains_address(VirtAddr(address)))
                    .cloned()
                    .map(|info| OwnedModule {
                        info,
                        dtb: self.process_dtb.unwrap_or(self.active_dtb),
                    })
            })
    }
}

impl<'a> StackTracer<'a> {
    fn new(debugger: &'a Target, trace: &'a ThreadTraceContext) -> Self {
        Self {
            trace,
            phys: &debugger.phys,
            symbols: &debugger.symbols,
            memory: AddressSpace::new(&debugger.phys, trace.active_dtb),
            modules: HashMap::new(),
        }
    }

    fn unwind_once(&mut self, context: &mut RegisterContext) -> Unwound {
        unwind_trace!("unwind: rip={:#x} rsp={:#x}", context.rip, context.rsp);
        let Some(base_address) = self
            .module_containing(context.rip)
            .map(|module| module.info.base_address.0)
        else {
            unwind_trace!("unwind: no module for rip -> leaf");
            return self.unwind_leaf(context);
        };
        let Some(mut image) = self.module_image(context.rip) else {
            return Unwound::Stop;
        };

        // Resolve the function entry. If the lookup or its unwind data lands in a
        // paged-out hole, upgrade to the complete on-disk image and re-resolve so
        // we can unwind through a module whose `.pdata`/`.xdata` isn't resident.
        let mut resolved = resolve_function(&image, base_address, context.rip);
        if matches!(resolved, Resolve::Holed)
            && !image.is_complete()
            && self.upgrade_module_image(context.rip)
        {
            let Some(upgraded) = self.module_image(context.rip) else {
                return Unwound::Stop;
            };
            image = upgraded;
            resolved = resolve_function(&image, base_address, context.rip);
        }

        let (mut unwind_data, begin) = match resolved {
            Resolve::Function { unwind_data, begin } => (unwind_data, begin),
            Resolve::Leaf => {
                unwind_trace!("unwind: no unwind info for rip -> leaf (true leaf)");
                return self.unwind_leaf(context);
            }
            Resolve::Holed => {
                unwind_trace!("unwind: unwind data paged out and unrecoverable -> stop");
                return Unwound::Stop;
            }
        };

        // Walk the function and any chained parents. Only the primary function's
        // codes are gated on the prolog progress at `rip`; chained parents already
        // ran their prologs in full, so all of their codes apply.
        let rva = (context.rip - base_address) as u32;
        let rip_offset = rva.saturating_sub(begin);
        let mut primary = true;

        for _ in 0..MAX_CHAIN_DEPTH {
            let Some(unwind_info) = parse_unwind_info(&image, unwind_data) else {
                unwind_trace!(
                    "unwind: parse_unwind_info failed/holed at unwind_data={unwind_data:#x} -> stop"
                );
                return Unwound::Stop;
            };

            unwind_trace!(
                "unwind: rva={:#x} begin={:#x} prolog={:#x} codes={} chained={} in_prolog={}",
                rva,
                begin,
                unwind_info.size_of_prolog,
                unwind_info.codes.len(),
                unwind_info.chained_unwind_data.is_some(),
                primary && rip_offset < unwind_info.size_of_prolog as u32,
            );

            let in_prolog = primary && rip_offset < unwind_info.size_of_prolog as u32;
            match self.apply_unwind_codes(context, &unwind_info, in_prolog, rip_offset) {
                Some(UnwindStep::Continue) => {}
                Some(UnwindStep::MachineFrame) => {
                    unwind_trace!(
                        "unwind: machine frame -> rip={:#x} rsp={:#x}",
                        context.rip,
                        context.rsp
                    );
                    return Unwound::Frame { stack_switch: true };
                }
                None => {
                    unwind_trace!("unwind: malformed unwind codes -> stop");
                    return Unwound::Stop;
                }
            }

            match unwind_info.chained_unwind_data {
                Some(next) => {
                    unwind_data = next;
                    primary = false;
                }
                None => {
                    let Ok(return_address) = self.memory.read::<u64>(VirtAddr(context.rsp)) else {
                        unwind_trace!(
                            "unwind: return-address read failed at rsp={:#x} -> stop",
                            context.rsp
                        );
                        return Unwound::Stop;
                    };
                    unwind_trace!(
                        "unwind: pop return -> rip={return_address:#x} rsp={:#x}",
                        context.rsp.saturating_add(8)
                    );
                    context.rip = return_address;
                    context.rsp = context.rsp.saturating_add(8);
                    return Unwound::Frame {
                        stack_switch: false,
                    };
                }
            }
        }

        // chain too deep or cyclic (corrupt unwind data); let the scan take over
        Unwound::Stop
    }

    /// Apply one frame's unwind codes to `context`, undoing the prolog. Returns
    /// `MachineFrame` if a trap/interrupt frame redirected rip+rsp (frame done),
    /// `Continue` otherwise, or `None` on malformed codes.
    fn apply_unwind_codes(
        &self,
        context: &mut RegisterContext,
        unwind_info: &ParsedUnwindInfo,
        in_prolog: bool,
        rip_offset: u32,
    ) -> Option<UnwindStep> {
        let original_context = context.clone();
        let mut index = 0usize;

        while index < unwind_info.codes.len() {
            let slot = unwind_info.codes[index];
            let slots_used = unwind_slot_count(slot.unwind_op, slot.op_info);
            if slots_used == 0 || index + slots_used > unwind_info.codes.len() {
                return None;
            }

            let executed = !in_prolog || u32::from(slot.code_offset) <= rip_offset;
            if executed
                && let UnwindStep::MachineFrame =
                    self.apply_unwind_code(context, &original_context, unwind_info, index)?
            {
                return Some(UnwindStep::MachineFrame);
            }

            index += slots_used;
        }

        Some(UnwindStep::Continue)
    }

    fn unwind_leaf(&mut self, context: &mut RegisterContext) -> Unwound {
        let Ok(return_address) = self.memory.read::<u64>(VirtAddr(context.rsp)) else {
            return Unwound::Stop;
        };

        if !self.is_executable_address(return_address) {
            return Unwound::Stop;
        }

        context.rip = return_address;
        context.rsp = context.rsp.saturating_add(8);
        Unwound::Frame {
            stack_switch: false,
        }
    }

    fn apply_unwind_code(
        &self,
        context: &mut RegisterContext,
        original_context: &RegisterContext,
        unwind_info: &ParsedUnwindInfo,
        index: usize,
    ) -> Option<UnwindStep> {
        let slot = unwind_info.codes[index];
        match slot.unwind_op {
            UWOP_PUSH_NONVOL => {
                let saved = self.memory.read::<u64>(VirtAddr(context.rsp)).ok()?;
                context.set(slot.op_info, saved);
                context.rsp = context.rsp.saturating_add(8);
            }
            UWOP_ALLOC_SMALL => {
                context.rsp = context
                    .rsp
                    .saturating_add(((u64::from(slot.op_info) + 1) * 8).max(8));
            }
            UWOP_ALLOC_LARGE => {
                let allocation = if slot.op_info == 0 {
                    u64::from(slot_u16(&unwind_info.codes, index + 1)?) * 8
                } else if slot.op_info == 1 {
                    u64::from(slot_u16(&unwind_info.codes, index + 1)?)
                        | (u64::from(slot_u16(&unwind_info.codes, index + 2)?) << 16)
                } else {
                    return None;
                };
                context.rsp = context.rsp.saturating_add(allocation);
            }
            UWOP_SET_FPREG => {
                // re-derive RSP from the established frame pointer: the prolog
                // set `fpreg = rsp + frame_offset*16`, so unwinding restores
                // RSP = fpreg - frame_offset*16. This supersedes any earlier
                // ALLOC adjustment, which is the whole point of a frame pointer
                // (the fixed allocation size need not be known to unwind)
                context.rsp = frame_base(context, unwind_info)?;
            }
            UWOP_EPILOG | UWOP_SPARE_CODE => {
                // version-2 epilog descriptors: they locate epilogs for the case
                // where the PC is mid-epilog. We unwind from the prolog/body, so
                // there's nothing to apply (their slots are skipped by the caller)
            }
            UWOP_SAVE_NONVOL | UWOP_SAVE_XMM128 => {
                let offset = if slot.unwind_op == UWOP_SAVE_NONVOL {
                    u64::from(slot_u16(&unwind_info.codes, index + 1)?) * 8
                } else {
                    u64::from(slot_u16(&unwind_info.codes, index + 1)?) * 16
                };
                if slot.unwind_op == UWOP_SAVE_NONVOL {
                    let base = frame_base(original_context, unwind_info)?;
                    let saved = self.memory.read::<u64>(VirtAddr(base + offset)).ok()?;
                    context.set(slot.op_info, saved);
                }
            }
            UWOP_SAVE_NONVOL_FAR | UWOP_SAVE_XMM128_FAR => {
                let offset = u64::from(slot_u16(&unwind_info.codes, index + 1)?)
                    | (u64::from(slot_u16(&unwind_info.codes, index + 2)?) << 16);
                let scaled = if slot.unwind_op == UWOP_SAVE_NONVOL_FAR {
                    offset
                } else {
                    offset * 16
                };
                if slot.unwind_op == UWOP_SAVE_NONVOL_FAR {
                    let base = frame_base(original_context, unwind_info)?;
                    let saved = self.memory.read::<u64>(VirtAddr(base + scaled)).ok()?;
                    context.set(slot.op_info, saved);
                }
            }
            UWOP_PUSH_MACHFRAME => {
                // a hardware-pushed trap/interrupt frame in iretq layout. op_info
                // == 1 means a CPU error code sits below it, so step over that to
                // reach the record: [+0]=rip [+8]=cs [+16]=eflags [+24]=rsp [+32]=ss
                let base = if slot.op_info == 1 {
                    context.rsp.saturating_add(8)
                } else {
                    context.rsp
                };
                let return_rip = self.memory.read::<u64>(VirtAddr(base)).ok()?;
                let return_rsp = self
                    .memory
                    .read::<u64>(VirtAddr(base.saturating_add(24)))
                    .ok()?;
                context.rip = return_rip;
                context.rsp = return_rsp;
                return Some(UnwindStep::MachineFrame);
            }
            _ => return None,
        }

        Some(UnwindStep::Continue)
    }

    fn scan_stack(&mut self, start_rsp: u64, seen: &HashSet<u64>) -> Vec<(u64, u64)> {
        let mut frames = Vec::new();
        let mut failures = 0usize;

        for slot in 0..(STACK_SCAN_BYTES / 8) {
            if failures >= 32 {
                break;
            }

            let sp = start_rsp.saturating_add((slot * 8) as u64);
            let potential_ip = match self.memory.read::<u64>(VirtAddr(sp)) {
                Ok(addr) => {
                    failures = 0;
                    addr
                }
                Err(_) => {
                    failures += 1;
                    continue;
                }
            };

            if seen.contains(&potential_ip) || !self.is_executable_address(potential_ip) {
                continue;
            }

            frames.push((sp, potential_ip));
        }

        frames
    }

    fn is_executable_address(&mut self, address: u64) -> bool {
        let Some(module) = self.module_containing(address) else {
            return false;
        };

        let rva = (address - module.info.base_address.0) as u32;
        module
            .executable_ranges
            .iter()
            .any(|(start, end)| rva >= *start && rva < *end)
    }

    fn module_containing(&mut self, address: u64) -> Option<&CachedModule> {
        let module = self.trace.module_for_address(address)?;

        self.ensure_module_loaded(&module)?;
        self.modules.get(&(module.dtb, module.info.base_address.0))
    }

    /// A cheap clone of the cached image handle for the module containing
    /// `address` (the module must already be loaded).
    fn module_image(&self, address: u64) -> Option<Arc<PeImage>> {
        let module = self.trace.module_for_address(address)?;
        self.modules
            .get(&(module.dtb, module.info.base_address.0))
            .map(|cached| cached.image.clone())
    }

    /// Replace a module's holed in-memory image with the complete on-disk one,
    /// downloading it if needed. Returns whether the cache now holds a complete
    /// image. No-op (false) when the image is already complete or the on-disk
    /// fetch fails (non-Microsoft module, offline); the caller then degrades to
    /// a stack scan.
    fn upgrade_module_image(&mut self, address: u64) -> bool {
        let Some(module) = self.trace.module_for_address(address) else {
            return false;
        };
        let key = (module.dtb, module.info.base_address.0);

        let disk = {
            let Some(cached) = self.modules.get(&key) else {
                return false;
            };
            if cached.image.is_complete() {
                return false;
            }
            self.load_on_disk_image(&cached.image, &module.info)
        };
        let Some(disk) = disk else {
            return false;
        };

        unwind_trace!(
            "unwind: recovered on-disk image for {} (in-memory unwind data paged out)",
            module.info.short_name
        );
        let executable_ranges = executable_ranges(&disk);
        self.modules.insert(
            key,
            CachedModule {
                info: module.info.clone(),
                image: Arc::new(disk),
                executable_ranges,
            },
        );
        true
    }

    fn ensure_module_loaded(&mut self, module: &OwnedModule) -> Option<()> {
        let key = (module.dtb, module.info.base_address.0);
        if self.modules.contains_key(&key) {
            return Some(());
        }

        let image_memory = AddressSpace::new(self.phys, module.dtb);
        let image = match read_pe_image(module.info.base_address, &image_memory) {
            Ok(img) => img,
            Err(_) => {
                // Triage dumps don't contain PE headers; download the PE from
                // the symbol server using the driver list's metadata.
                let tds = module.info.time_date_stamp?;
                unwind_trace!(
                    "unwind: in-memory PE unreadable for {}, downloading via timestamp",
                    module.info.short_name
                );
                let path = self
                    .symbols
                    .ensure_module_image_on_disk(&module.info.name, tds, module.info.size)
                    .ok()?;
                read_pe_image_from_file(&path).ok()?
            }
        };
        let executable_ranges = executable_ranges(&image);

        self.modules.insert(
            key,
            CachedModule {
                info: module.info.clone(),
                image: Arc::new(image),
                executable_ranges,
            },
        );

        Some(())
    }

    /// Download (if needed) and load the module's complete on-disk PE image,
    /// matched by the in-memory header's TimeDateStamp + SizeOfImage. The caller
    /// re-resolves against it to decide whether it actually recovered anything.
    fn load_on_disk_image(&self, image: &PeImage, info: &ModuleInfo) -> Option<PeImage> {
        let view = PeView::from_bytes(image.as_slice()).ok()?;
        let time_date_stamp = view.file_header().TimeDateStamp;
        let size_of_image = view.optional_header().SizeOfImage;

        let path = self
            .symbols
            .ensure_module_image_on_disk(&info.name, time_date_stamp, size_of_image)
            .ok()?;
        read_pe_image_from_file(&path).ok()
    }
}

/// The `[start, end)` RVA ranges of a module's executable sections (used to
/// validate scan candidates).
fn executable_ranges(image: &PeImage) -> Vec<(u32, u32)> {
    let Ok(view) = PeView::from_bytes(image.as_slice()) else {
        return Vec::new();
    };
    view.section_headers()
        .iter()
        .filter_map(|section| {
            if section.Characteristics & IMAGE_SCN_MEM_EXECUTE == 0 {
                return None;
            }
            let size = section.VirtualSize.max(section.SizeOfRawData);
            if size == 0 {
                return None;
            }
            Some((
                section.VirtualAddress,
                section.VirtualAddress.saturating_add(size),
            ))
        })
        .collect()
}

/// Resolution of an rip against a module's unwind tables.
enum Resolve {
    /// A genuine leaf: the `.pdata` table is readable but has no entry covering
    /// the rip (a function with no prologue to undo).
    Leaf,
    /// An entry was found and its unwind data is resident.
    Function { unwind_data: u32, begin: u32 },
    /// The lookup was blocked by a paged-out hole in `.pdata` or `.xdata`; an
    /// on-disk image could recover it.
    Holed,
}

/// Resolve `rip` against the image's unwind tables, distinguishing a true leaf
/// from a paged-out hole so the caller knows whether an on-disk image would help.
fn resolve_function(image: &PeImage, base_address: u64, rip: u64) -> Resolve {
    let Ok(view) = PeView::from_bytes(image.as_slice()) else {
        return Resolve::Leaf;
    };
    let Ok(exception) = view.exception() else {
        return Resolve::Leaf;
    };

    let rva = (rip - base_address) as u32;
    match lookup_runtime_function(exception.image(), rva) {
        // an entry is only usable if its unwind info (`.xdata`) is resident too
        Some(function) if image.is_present(function.UnwindData as usize, 4) => Resolve::Function {
            unwind_data: function.UnwindData,
            begin: function.BeginAddress,
        },
        Some(_) => Resolve::Holed,
        None => {
            // no entry: a true leaf if the table is resident, otherwise the table
            // itself is holed
            let pdata_present = view
                .data_directory()
                .get(IMAGE_DIRECTORY_ENTRY_EXCEPTION)
                .map(|d| {
                    d.Size == 0 || image.is_present(d.VirtualAddress as usize, d.Size as usize)
                })
                .unwrap_or(true);
            if pdata_present {
                Resolve::Leaf
            } else {
                Resolve::Holed
            }
        }
    }
}

/// Find the runtime function whose `[BeginAddress, EndAddress)` range covers
/// `rva`, by binary search over the (sorted) `.pdata` table. Replaces pelite
/// 0.10's `lookup_function_entry`, whose comparator is inverted and misses.
fn lookup_runtime_function(functions: &[RUNTIME_FUNCTION], rva: u32) -> Option<&RUNTIME_FUNCTION> {
    functions
        .binary_search_by(|rf| {
            if rva < rf.BeginAddress {
                Ordering::Greater
            } else if rva >= rf.EndAddress {
                Ordering::Less
            } else {
                Ordering::Equal
            }
        })
        .ok()
        .map(|index| &functions[index])
}

fn parse_unwind_info(image: &PeImage, unwind_rva: u32) -> Option<ParsedUnwindInfo> {
    // every read goes through `present_slice`, so unwind data that lands in a
    // paged-out hole returns None (fall back to scan) rather than being parsed as
    // zeros and fabricating a frame
    let offset = unwind_rva as usize;
    let header = image.present_slice(offset, 4)?;
    let version_flags = header[0];
    let count_of_codes = header[2] as usize;
    let frame_register_offset = header[3];

    let codes_offset = offset + 4;
    let codes_bytes = image.present_slice(codes_offset, count_of_codes.checked_mul(2)?)?;

    let aligned_code_count = (count_of_codes + 1) & !1;
    let tail_offset = offset + 4 + aligned_code_count * 2;
    let chained_unwind_data = if (version_flags >> 3) & UNW_FLAG_CHAININFO != 0 {
        // a chained entry is followed by the parent RUNTIME_FUNCTION
        // (BeginAddress, EndAddress, UnwindInfoAddress); only the parent's
        // unwind-data RVA is needed to keep walking the chain
        let tail = image.present_slice(tail_offset, 12)?;
        Some(u32::from_le_bytes([tail[8], tail[9], tail[10], tail[11]]))
    } else {
        None
    };

    let mut codes = Vec::with_capacity(count_of_codes);
    for raw in codes_bytes.chunks_exact(2) {
        codes.push(UnwindCodeSlot {
            code_offset: raw[0],
            unwind_op: raw[1] & 0x0f,
            op_info: raw[1] >> 4,
            raw_op_info: raw[1],
        });
    }

    Some(ParsedUnwindInfo {
        size_of_prolog: header[1],
        frame_register: frame_register_offset & 0x0f,
        frame_offset: frame_register_offset >> 4,
        codes,
        chained_unwind_data,
    })
}

fn frame_base(context: &RegisterContext, unwind_info: &ParsedUnwindInfo) -> Option<u64> {
    if unwind_info.frame_register == 0 {
        return Some(context.rsp);
    }

    let frame_register = context.get(unwind_info.frame_register)?;
    frame_register.checked_sub(u64::from(unwind_info.frame_offset) * 16)
}

fn unwind_slot_count(unwind_op: u8, op_info: u8) -> usize {
    match unwind_op {
        UWOP_PUSH_NONVOL | UWOP_ALLOC_SMALL | UWOP_SET_FPREG | UWOP_PUSH_MACHFRAME
        | UWOP_EPILOG => 1,
        UWOP_ALLOC_LARGE => {
            if op_info == 0 {
                2
            } else {
                3
            }
        }
        UWOP_SAVE_NONVOL | UWOP_SAVE_XMM128 => 2,
        UWOP_SAVE_NONVOL_FAR | UWOP_SAVE_XMM128_FAR | UWOP_SPARE_CODE => 3,
        _ => 0,
    }
}

fn slot_u16(codes: &[UnwindCodeSlot], index: usize) -> Option<u16> {
    let slot = codes.get(index)?;
    Some(u16::from_le_bytes([slot.code_offset, slot.raw_op_info]))
}

#[cfg(test)]
mod tests {
    use super::{
        FrameSource, ParsedUnwindInfo, PeImage, RUNTIME_FUNCTION, RegisterContext, StackFrame,
        StackTrace, UnwindCodeSlot, frame_base, lookup_runtime_function, parse_unwind_info,
        record_stack_frame, slot_u16, unwind_slot_count,
    };
    use crate::target::SavedThreadRegisters;

    #[test]
    fn lookup_runtime_function_resolves_across_a_large_sorted_table() {
        // entries [i*0x100, i*0x100+0x40) with a gap before the next; the
        // lower-half hits are exactly what pelite's inverted comparator missed
        let funcs: Vec<RUNTIME_FUNCTION> = (0..64u32)
            .map(|i| RUNTIME_FUNCTION {
                BeginAddress: i * 0x100,
                EndAddress: i * 0x100 + 0x40,
                UnwindData: i,
            })
            .collect();

        assert_eq!(
            lookup_runtime_function(&funcs, 0x0).unwrap().BeginAddress,
            0x0
        );
        assert_eq!(
            lookup_runtime_function(&funcs, 0x310).unwrap().BeginAddress,
            0x300
        );
        assert_eq!(
            lookup_runtime_function(&funcs, 0x3f00)
                .unwrap()
                .BeginAddress,
            0x3f00
        );
        // an address in the gap between two functions resolves to nothing
        assert!(lookup_runtime_function(&funcs, 0x350).is_none());
        // past the end of the table
        assert!(lookup_runtime_function(&funcs, 0x10000).is_none());
    }

    #[test]
    fn parse_unwind_info_reads_chained_parent() {
        // version 1 with UNW_FLAG_CHAININFO (0x4), no prolog, zero codes; the
        // parent RUNTIME_FUNCTION (begin, end, unwind-data) follows the header
        let blob = [
            0x21, 0x00, 0x00, 0x00, // ver/flags=chaininfo, prolog, count, frame
            0x00, 0x10, 0x00, 0x00, // BeginAddress = 0x1000
            0x00, 0x11, 0x00, 0x00, // EndAddress   = 0x1100
            0x00, 0x20, 0x00, 0x00, // UnwindData   = 0x2000
        ];
        let info =
            parse_unwind_info(&PeImage::complete(blob.to_vec()), 0).expect("unwind info parses");
        assert_eq!(info.chained_unwind_data, Some(0x2000));
    }

    #[test]
    fn parse_unwind_info_without_chain_flag_has_no_parent() {
        // version 1, no flags, no codes
        let blob = [0x01, 0x00, 0x00, 0x00];
        let info =
            parse_unwind_info(&PeImage::complete(blob.to_vec()), 0).expect("unwind info parses");
        assert_eq!(info.chained_unwind_data, None);
    }

    #[test]
    fn slot_count_matches_opcode_encoding() {
        assert_eq!(unwind_slot_count(0, 0), 1);
        assert_eq!(unwind_slot_count(1, 0), 2);
        assert_eq!(unwind_slot_count(1, 1), 3);
        assert_eq!(unwind_slot_count(4, 0), 2);
        assert_eq!(unwind_slot_count(5, 0), 3);
        assert_eq!(unwind_slot_count(6, 0), 1); // UWOP_EPILOG
        assert_eq!(unwind_slot_count(7, 0), 3); // UWOP_SPARE_CODE
    }

    #[test]
    fn slot_u16_reads_little_endian_slot_data() {
        let codes = vec![
            UnwindCodeSlot {
                code_offset: 0x34,
                unwind_op: 0,
                op_info: 0,
                raw_op_info: 0x12,
            },
            UnwindCodeSlot {
                code_offset: 0x78,
                unwind_op: 0,
                op_info: 0,
                raw_op_info: 0x56,
            },
        ];

        assert_eq!(slot_u16(&codes, 0), Some(0x1234));
        assert_eq!(slot_u16(&codes, 1), Some(0x5678));
    }

    #[test]
    fn frame_base_uses_frame_register_when_present() {
        let mut regs = [None; 16];
        regs[5] = Some(0x2000);
        let context = RegisterContext {
            rip: 0,
            rsp: 0x1800,
            regs,
        };
        let unwind = ParsedUnwindInfo {
            size_of_prolog: 0,
            frame_register: 5,
            frame_offset: 2,
            codes: Vec::new(),
            chained_unwind_data: None,
        };

        assert_eq!(frame_base(&context, &unwind), Some(0x1fe0));
    }

    #[test]
    fn record_stack_frame_counts_truncated_frames() {
        let mut stacktrace = StackTrace::default();

        for ip in [0x1000, 0x2000, 0x3000] {
            record_stack_frame(
                &mut stacktrace,
                2,
                StackFrame {
                    sp: 0,
                    ip,
                    symbol: String::new(),
                    source: FrameSource::Current,
                    source_location: None,
                },
            );
        }

        assert_eq!(stacktrace.frames.len(), 2);
        assert_eq!(stacktrace.truncated, 1);
    }

    #[test]
    fn saved_register_context_preserves_missing_values() {
        let registers = SavedThreadRegisters {
            rip: Some(0xffff_f800_1000),
            rsp: Some(0xffff_a000_2000),
            rbp: Some(0xffff_a000_2100),
            ..SavedThreadRegisters::default()
        };
        let context = RegisterContext::from_saved(&registers).unwrap();
        assert_eq!(context.rip, 0xffff_f800_1000);
        assert_eq!(context.rsp, 0xffff_a000_2000);
        assert_eq!(context.get(5), Some(0xffff_a000_2100));
        assert_eq!(context.get(3), None);

        let missing_rsp = SavedThreadRegisters {
            rip: Some(0xffff_f800_1000),
            ..SavedThreadRegisters::default()
        };
        assert!(RegisterContext::from_saved(&missing_rsp).is_none());
    }
}