mapsample 0.1.0

In-process Windows x64 stack sampler with a rolling stall recorder, P/E-core placement readings, and an MSVC /MAP symbolizer
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
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
//! x64 unwinding in safe Rust, over a copied stack and image bytes read through a callback.
//!
//! Nothing here touches memory it was not handed: the stack is a byte slice holding a copy of
//! `[base, base + len)` of the thread's stack, and image bytes (PE headers, `.pdata`,
//! `UNWIND_INFO`, epilog code) come from an [`Image`] that fails cleanly outside the image. A
//! read that would leave the copy stops the walk. The rules follow the documented x64
//! exception handling model: the function's own unwind info applies only the prolog codes
//! already executed, chained infos apply in full, and a thread caught in an epilog has the rest
//! of the epilog emulated, from the instruction bytes (version 1 infos) or from the epilog
//! descriptors and prolog codes (version 2).

/// Chained unwind infos followed at most (a real chain is one or two long).
const MAX_CHAIN: usize = 32;
/// Indirect `RUNTIME_FUNCTION` hops followed at most.
const MAX_INDIRECT: usize = 4;
/// Instruction bytes looked at for an epilog.
const EPILOG_WINDOW: usize = 64;
/// Pops an epilog may hold (there are 16 integer registers).
const MAX_POPS: usize = 16;
const UNW_FLAG_CHAININFO: u8 = 0x4;
const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
const IMAGE_NT_OPTIONAL_HDR64_MAGIC: u16 = 0x20b;
const IMAGE_SCN_MEM_READ: u32 = 0x4000_0000;
const IMAGE_DIRECTORY_ENTRY_EXCEPTION: usize = 3;
/// Header bytes read first: the DOS and NT headers and, for most images, the section table.
const FIRST_HEADER_BYTES: usize = 4096;
/// The largest header (through the end of the section table) read from a module.
const MAX_HEADER_BYTES: usize = 1 << 20;

/// Register number of the stack pointer.
pub(crate) const RSP: usize = 4;

/// Reads image bytes by RVA.
pub(crate) trait Image {
    /// Fill `out` with the bytes at `rva`. False (and `out` unspecified) when any of them lies
    /// outside the readable part of the image.
    fn read(&mut self, rva: u32, out: &mut [u8]) -> bool;
}

impl<F: FnMut(u32, &mut [u8]) -> bool> Image for F {
    fn read(&mut self, rva: u32, out: &mut [u8]) -> bool {
        self(rva, out)
    }
}

fn u16_at(bytes: &[u8], at: usize) -> Option<u16> {
    bytes
        .get(at..at.checked_add(2)?)
        .and_then(|b| b.try_into().ok())
        .map(u16::from_le_bytes)
}

fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
    bytes
        .get(at..at.checked_add(4)?)
        .and_then(|b| b.try_into().ok())
        .map(u32::from_le_bytes)
}

fn i32_at(bytes: &[u8], at: usize) -> Option<i32> {
    u32_at(bytes, at).map(|value| i32::from_le_bytes(value.to_le_bytes()))
}

/// What the unwinder needs from a PE32+ header.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PeImage {
    /// `SizeOfImage`.
    pub size: u32,
    /// `TimeDateStamp` and `CheckSum`, which tell two builds apart.
    pub stamp: u32,
    pub checksum: u32,
    /// The exception directory (`.pdata`): RVA and size, `(0, 0)` when there is none.
    pub exception: (u32, u32),
    /// Readable RVA ranges `[start, end)`: the headers and every readable section.
    pub readable: Vec<(u32, u32)>,
}

impl PeImage {
    /// Whether `[rva, rva + len)` lies inside one readable range.
    pub fn is_readable(&self, rva: u32, len: usize) -> bool {
        let Some(end) = u32::try_from(len).ok().and_then(|len| rva.checked_add(len)) else {
            return false;
        };
        self.readable
            .iter()
            .any(|&(start, stop)| rva >= start && end <= stop)
    }
}

/// Parse the headers of an x64 image from its first bytes. `None` unless it is a well-formed
/// AMD64 PE32+ header whose section table lies inside `bytes`.
pub(crate) fn parse_pe(bytes: &[u8]) -> Option<PeImage> {
    if bytes.get(..2)? != b"MZ" {
        return None;
    }
    let nt = usize::try_from(u32_at(bytes, 0x3c)?).ok()?;
    if bytes.get(nt..nt.checked_add(4)?)? != b"PE\0\0" {
        return None;
    }
    let file = nt + 4;
    if u16_at(bytes, file)? != IMAGE_FILE_MACHINE_AMD64 {
        return None;
    }
    let sections = usize::from(u16_at(bytes, file + 2)?);
    let stamp = u32_at(bytes, file + 4)?;
    let optional_size = usize::from(u16_at(bytes, file + 16)?);
    let optional = file + 20;
    if u16_at(bytes, optional)? != IMAGE_NT_OPTIONAL_HDR64_MAGIC {
        return None;
    }
    let size = u32_at(bytes, optional + 56)?;
    let headers = u32_at(bytes, optional + 60)?.min(size);
    let checksum = u32_at(bytes, optional + 64)?;
    let directories = usize::try_from(u32_at(bytes, optional + 108)?).ok()?;
    let exception = if directories > IMAGE_DIRECTORY_ENTRY_EXCEPTION
        && optional_size >= 112 + 8 * (IMAGE_DIRECTORY_ENTRY_EXCEPTION + 1)
    {
        let at = optional + 112 + 8 * IMAGE_DIRECTORY_ENTRY_EXCEPTION;
        (u32_at(bytes, at)?, u32_at(bytes, at + 4)?)
    } else {
        (0, 0)
    };
    let mut readable = vec![(0, headers)];
    let table = optional.checked_add(optional_size)?;
    for index in 0..sections {
        let at = table.checked_add(index.checked_mul(40)?)?;
        let header = bytes.get(at..at.checked_add(40)?)?;
        let virtual_size = u32_at(header, 8)?;
        let address = u32_at(header, 12)?;
        let raw_size = u32_at(header, 16)?;
        let characteristics = u32_at(header, 36)?;
        let extent = if virtual_size == 0 {
            raw_size
        } else {
            virtual_size
        };
        if characteristics & IMAGE_SCN_MEM_READ != 0 && address < size {
            let end = address.saturating_add(extent).min(size);
            readable.push((address, end));
        }
    }
    Some(PeImage {
        size,
        stamp,
        checksum,
        exception,
        readable,
    })
}

/// Bytes from the start of an image to the end of its section table, from the DOS and COFF
/// headers at the start of `bytes`: `Err` with the bytes needed to tell when the COFF header
/// lies past them, `Ok(None)` when they are not the start of a PE image.
fn header_len(bytes: &[u8]) -> Result<Option<usize>, usize> {
    if bytes.get(..2) != Some(b"MZ") {
        return Ok(None);
    }
    let Some(nt) = u32_at(bytes, 0x3c).and_then(|at| usize::try_from(at).ok()) else {
        return Ok(None);
    };
    let Some(coff_end) = nt.checked_add(24) else {
        return Ok(None);
    };
    if bytes.len() < coff_end {
        return Err(coff_end);
    }
    if bytes.get(nt..nt + 4) != Some(b"PE\0\0") {
        return Ok(None);
    }
    let len = u16_at(bytes, nt + 6)
        .zip(u16_at(bytes, nt + 20))
        .and_then(|(sections, optional)| {
            usize::from(sections)
                .checked_mul(40)?
                .checked_add(usize::from(optional))?
                .checked_add(coff_end)
        });
    Ok(len)
}

/// Read and parse the headers of an x64 image through `read`, which fills a buffer from the
/// start of the image and returns the bytes it read. The first read takes one page; when the
/// NT headers or the section table reach past it, exactly the bytes they need are read again
/// (up to [`MAX_HEADER_BYTES`]).
pub(crate) fn read_pe(mut read: impl FnMut(&mut [u8]) -> usize) -> Option<PeImage> {
    let mut bytes = vec![0_u8; FIRST_HEADER_BYTES];
    // At most three reads: the first page, the NT headers, the whole section table.
    for _ in 0..3 {
        let asked = bytes.len();
        let got = read(&mut bytes).min(asked);
        bytes.truncate(got);
        let wanted = match header_len(&bytes) {
            Ok(Some(len)) if len <= got => return parse_pe(bytes.get(..len)?),
            Ok(Some(len)) | Err(len) => len,
            Ok(None) => return None,
        };
        // A short read already stopped before the bytes needed; so does an oversized header.
        if got < asked || wanted > MAX_HEADER_BYTES {
            return None;
        }
        bytes.resize(wanted, 0);
    }
    None
}

/// A `RUNTIME_FUNCTION`: the function's RVA range and its `UNWIND_INFO` RVA.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct RuntimeFunction {
    pub begin: u32,
    pub end: u32,
    pub unwind: u32,
}

impl RuntimeFunction {
    fn from_bytes(bytes: &[u8]) -> Option<Self> {
        Some(Self {
            begin: u32_at(bytes, 0)?,
            end: u32_at(bytes, 4)?,
            unwind: u32_at(bytes, 8)?,
        })
    }
}

/// The entries of an exception directory (12 bytes each; a trailing partial one is ignored).
pub(crate) fn parse_pdata(bytes: &[u8]) -> Vec<RuntimeFunction> {
    bytes
        .as_chunks::<12>()
        .0
        .iter()
        .filter_map(|entry| RuntimeFunction::from_bytes(entry))
        .collect()
}

/// Follow `RUNTIME_FUNCTION_INDIRECT` entries (low bit of `unwind` set: the RVA of the primary
/// entry) to the entry that holds the unwind info.
fn resolve(mut function: RuntimeFunction, image: &mut impl Image) -> Option<RuntimeFunction> {
    for _ in 0..=MAX_INDIRECT {
        if function.unwind & 1 == 0 {
            return Some(function);
        }
        let mut bytes = [0_u8; 12];
        if !image.read(function.unwind & !1, &mut bytes) {
            return None;
        }
        function = RuntimeFunction::from_bytes(&bytes)?;
    }
    None
}

/// The table entry holding a pc, and the entry its unwind info comes from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Entry {
    /// The entry whose range holds the pc (an indirect one for a separated fragment).
    pub sampled: RuntimeFunction,
    /// That entry with indirect entries resolved: it names the unwind info.
    pub function: RuntimeFunction,
}

/// The entry holding `rva`, from a table sorted by `begin`, with indirect entries resolved.
pub(crate) fn lookup(table: &[RuntimeFunction], rva: u32, image: &mut impl Image) -> Option<Entry> {
    let after = table.partition_point(|function| function.begin <= rva);
    let sampled = *table.get(after.checked_sub(1)?)?;
    if rva >= sampled.end {
        return None;
    }
    Some(Entry {
        sampled,
        function: resolve(sampled, image)?,
    })
}

/// The primary entry of the function `function` belongs to: chained unwind infos followed
/// to the entry whose info is not chained.
fn primary_entry(mut function: RuntimeFunction, image: &mut impl Image) -> Option<RuntimeFunction> {
    for _ in 0..=MAX_CHAIN {
        let mut header = [0_u8; 4];
        if !image.read(function.unwind, &mut header) {
            return None;
        }
        if (header[0] >> 3) & UNW_FLAG_CHAININFO == 0 {
            return Some(function);
        }
        let count = u32::from(header[2]);
        let at = function.unwind.checked_add(4 + (count + (count & 1)) * 2)?;
        let mut bytes = [0_u8; 12];
        if !image.read(at, &mut bytes) {
            return None;
        }
        function = resolve(RuntimeFunction::from_bytes(&bytes)?, image)?;
    }
    None
}

/// Whether `target` lies in the same function as `function` (a resolved entry): in an entry
/// with the same primary entry. Returns that primary entry.
fn same_function(
    function: RuntimeFunction,
    target: u32,
    table: &[RuntimeFunction],
    image: &mut impl Image,
) -> Option<RuntimeFunction> {
    let primary = primary_entry(function, image)?;
    let other = primary_entry(lookup(table, target, image)?.function, image)?;
    (other.begin == primary.begin).then_some(primary)
}

/// One decoded unwind code.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Op {
    /// `UWOP_PUSH_NONVOL`: pop the register.
    Push(u8),
    /// `UWOP_ALLOC_LARGE`, `UWOP_ALLOC_SMALL`: release bytes.
    Alloc(u64),
    /// `UWOP_SET_FPREG`: the stack pointer comes back from the frame register.
    SetFrame,
    /// `UWOP_SAVE_NONVOL(_FAR)`: the register was saved at this offset from the frame base.
    Save(u8, u64),
    /// `UWOP_SAVE_XMM128(_FAR)`: nothing an integer walk needs. Also version 2 `UWOP_EPILOG`,
    /// whose descriptors the block keeps as [`Epilogs`].
    Skip,
    /// `UWOP_PUSH_MACHFRAME`, with an error code pushed or not.
    MachineFrame(bool),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Code {
    /// Prolog offset just past the instruction the code describes.
    offset: u8,
    op: Op,
}

/// Version 2 `UWOP_EPILOG` descriptors: where a function's epilogs are. Every epilog of the
/// function has the same size, and its region starts after the stack adjustment, at the first
/// `pop`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Epilogs {
    size: u8,
    /// One epilog ends at the end of the function.
    at_end: bool,
    /// The starts of the others, as bytes back from the end of the function.
    back: Vec<u16>,
}

impl Epilogs {
    /// The offset of `pc` inside one of the epilogs of `function`, if it is in one.
    fn holding(&self, function: RuntimeFunction, pc: u32) -> Option<u32> {
        let size = u32::from(self.size);
        let at_end = self.at_end.then_some(size);
        at_end
            .into_iter()
            .chain(self.back.iter().map(|&back| u32::from(back)))
            .map(|back| pc.wrapping_sub(function.end.wrapping_sub(back)))
            .find(|&into| into < size)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct Block {
    version: u8,
    /// Version 2 only, when the codes start with epilog descriptors.
    epilogs: Option<Epilogs>,
    prolog: u8,
    /// 0 for none.
    frame_register: u8,
    /// Bytes the frame register points above the frame base.
    frame_offset: u64,
    chained: bool,
    codes: Vec<Code>,
}

/// The decoded unwind info chain of one function: its own info first, then the chained ones.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct UnwindPlan {
    blocks: Vec<Block>,
}

/// Decode one `UNWIND_INFO` at `rva`. `None` for an unknown version or code, a truncated list,
/// an operation the walk cannot honour, or a frame register used inconsistently.
fn decode_block(
    rva: u32,
    image: &mut impl Image,
    depth: usize,
    primary_frame: u8,
) -> Option<(Block, Option<u32>)> {
    let mut header = [0_u8; 4];
    if !image.read(rva, &mut header) {
        return None;
    }
    let [version_flags, prolog, count, frame] = header;
    let version = version_flags & 7;
    let chained = (version_flags >> 3) & UNW_FLAG_CHAININFO != 0;
    if version != 1 && version != 2 {
        return None;
    }
    let frame_register = frame & 0xf;
    if depth > 0 && frame_register != 0 && frame_register != primary_frame {
        return None;
    }
    let count = usize::from(count);
    // Codes, padded to an even count, then the chained RUNTIME_FUNCTION when there is one.
    let padded = count + (count & 1);
    let mut raw = [0_u8; 512 + 12];
    let wanted = raw.get_mut(..padded * 2 + if chained { 12 } else { 0 })?;
    if !image.read(rva.checked_add(4)?, wanted) {
        return None;
    }
    let slot = |index: usize| u16_at(wanted, index * 2);
    let far = |index: usize| -> Option<u64> {
        Some(u64::from(slot(index + 1)?) | (u64::from(slot(index + 2)?) << 16))
    };
    // Version 2 epilog descriptors lead the codes, one slot each: the first holds the epilog
    // size and whether one ends the function, each next one an epilog's start back from the
    // end (0 pads the list to an even length).
    let op_of = |index: usize| {
        wanted
            .get(index * 2 + 1)
            .map(|&byte| (byte & 0xf, byte >> 4))
    };
    let epilogs = match (version, op_of(0)) {
        (2, Some((6, info))) if count > 0 => {
            let back = (1..count)
                .map_while(|index| match op_of(index)? {
                    (6, high) => {
                        let low = *wanted.get(index * 2)?;
                        let back = u16::from(low) | (u16::from(high) << 8);
                        (back != 0).then_some(back)
                    }
                    _ => None,
                })
                .collect();
            Some(Epilogs {
                size: *wanted.first()?,
                at_end: info & 1 != 0,
                back,
            })
        }
        _ => None,
    };
    let mut codes = Vec::with_capacity(count);
    let mut i = 0;
    while i < count {
        let offset = *wanted.get(i * 2)?;
        let op_byte = *wanted.get(i * 2 + 1)?;
        let (op, info) = (op_byte & 0xf, op_byte >> 4);
        let (decoded, used) = match op {
            0 => (Op::Push(info), 1),
            1 => match info {
                0 => (Op::Alloc(u64::from(slot(i + 1)?) * 8), 2),
                1 => (Op::Alloc(far(i)?), 3),
                _ => return None,
            },
            2 => (Op::Alloc(u64::from(info) * 8 + 8), 1),
            3 => {
                if frame_register == 0 {
                    return None;
                }
                (Op::SetFrame, 1)
            }
            4 => (Op::Save(info, u64::from(slot(i + 1)?) * 8), 2),
            5 => (Op::Save(info, far(i)?), 3),
            6 if version == 2 => (Op::Skip, 2),
            8 => {
                slot(i + 1)?;
                (Op::Skip, 2)
            }
            9 => {
                far(i)?;
                (Op::Skip, 3)
            }
            10 => {
                if info > 1 || i + 1 != count || chained {
                    return None;
                }
                (Op::MachineFrame(info == 1), 1)
            }
            _ => return None,
        };
        codes.push(Code {
            offset,
            op: decoded,
        });
        i += used;
    }
    if i != count {
        return None;
    }
    let next = if chained {
        let function = RuntimeFunction::from_bytes(wanted.get(padded * 2..)?)?;
        Some(resolve(function, image)?.unwind)
    } else {
        None
    };
    let block = Block {
        version,
        epilogs,
        prolog,
        frame_register,
        frame_offset: u64::from(frame >> 4) * 16,
        chained,
        codes,
    };
    Some((block, next))
}

/// Decode the unwind info chain starting at `rva` (a resolved `RUNTIME_FUNCTION.UnwindData`).
pub(crate) fn load_plan(rva: u32, image: &mut impl Image) -> Option<UnwindPlan> {
    let mut blocks: Vec<Block> = Vec::new();
    let mut next = Some(rva);
    while let Some(rva) = next {
        if blocks.len() >= MAX_CHAIN {
            return None;
        }
        let primary = blocks.first().map_or(0, |block| block.frame_register);
        let (block, chained) = decode_block(rva, image, blocks.len(), primary)?;
        blocks.push(block);
        next = chained;
    }
    Some(UnwindPlan { blocks })
}

/// The integer registers (by x64 number: rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, r8 to r15)
/// and the instruction pointer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Registers {
    pub rip: u64,
    pub gpr: [u64; 16],
}

impl Registers {
    pub fn rsp(&self) -> u64 {
        self.gpr[RSP]
    }

    fn get(&self, number: u8) -> Option<u64> {
        self.gpr.get(usize::from(number)).copied()
    }

    fn set(&mut self, number: u8, value: u64) -> Option<()> {
        *self.gpr.get_mut(usize::from(number))? = value;
        Some(())
    }
}

/// A copy of the stack range `[base, base + bytes.len())`.
#[derive(Clone, Copy, Debug)]
pub(crate) struct StackCopy<'a> {
    pub base: u64,
    pub bytes: &'a [u8],
}

impl StackCopy<'_> {
    /// The word at `address`, if all eight bytes are in the copy.
    pub fn word(&self, address: u64) -> Option<u64> {
        let at = usize::try_from(address.checked_sub(self.base)?).ok()?;
        let bytes = self.bytes.get(at..at.checked_add(8)?)?;
        Some(u64::from_le_bytes(bytes.try_into().ok()?))
    }

    /// Whether the word at `address` is in the copy.
    pub fn holds(&self, address: u64) -> bool {
        self.word(address).is_some()
    }
}

/// The frame being unwound.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Frame<'a> {
    /// The entry holding the pc, and the resolved entry the plan belongs to.
    pub entry: Entry,
    pub plan: &'a UnwindPlan,
    /// The pc as an RVA.
    pub pc: u32,
    /// The pc is where the thread was (the leaf, or below a machine frame), not a return
    /// address, so it may be inside an epilog.
    pub exact: bool,
}

/// How a step went.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stepped {
    /// The registers are the caller's, at a return address.
    Return,
    /// The registers came from a machine frame: the new pc is exact.
    MachineFrame,
}

/// A version 1 epilog, decoded from its instructions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Epilog {
    /// `add rsp, imm` (false) or `lea rsp, [frame + disp]` (true), with the displacement.
    adjust: Option<(bool, i64)>,
    pops: [u8; MAX_POPS],
    pop_count: usize,
    /// Bytes `ret imm16` releases after the return address.
    release: u64,
}

/// Where in an epilog the thread is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum InEpilog {
    /// Version 1: the rest of the epilog, decoded from the instruction bytes.
    Decoded(Epilog),
    /// Version 2: the byte offset into an epilog the unwind codes describe.
    Described(u32),
}

/// Read the longest readable run of up to [`EPILOG_WINDOW`] bytes at `rva` into `out`; returns
/// its length.
fn read_window(image: &mut impl Image, rva: u32, out: &mut [u8; EPILOG_WINDOW]) -> usize {
    if image.read(rva, out) {
        return EPILOG_WINDOW;
    }
    // Near the end of a section fewer bytes are readable, and a readable run's prefixes are
    // readable too: search for the longest one.
    let (mut good, mut bad) = (0, EPILOG_WINDOW);
    while bad - good > 1 {
        let mid = good + (bad - good) / 2;
        if out.get_mut(..mid).is_some_and(|part| image.read(rva, part)) {
            good = mid;
        } else {
            bad = mid;
        }
    }
    // A failed read leaves `out` unspecified, so read the run found once more.
    if out
        .get_mut(..good)
        .is_some_and(|part| image.read(rva, part))
    {
        good
    } else {
        0
    }
}

/// Decode the epilog starting at the instruction `code[0]` (at `rva`), the forms the x64
/// calling convention allows: an optional `add rsp, imm` or `lea rsp, [frame + disp]`, any
/// pops, an optional `repne` prefix, then `ret`, `rep ret`, `ret imm16`, or a jump out of the
/// function (a tail call). `function` is the resolved entry and `block` its own unwind info.
fn decode_epilog(
    code: &[u8],
    rva: u32,
    function: RuntimeFunction,
    block: &Block,
    table: &[RuntimeFunction],
    image: &mut impl Image,
) -> Option<Epilog> {
    let frame_register = block.frame_register;
    let byte = |at: usize| code.get(at).copied();
    let mut at = 0;
    let mut adjust = None;
    let (b0, b1, b2) = (byte(0)?, byte(1), byte(2));
    if b0 & 0xf8 == 0x48 {
        match (b1, b2) {
            (Some(0x83), Some(0xc4)) if b0 == 0x48 => {
                adjust = Some((false, i64::from(i8::from_le_bytes([byte(3)?]))));
                at = 4;
            }
            (Some(0x81), Some(0xc4)) if b0 == 0x48 => {
                adjust = Some((false, i64::from(i32_at(code, 3)?)));
                at = 7;
            }
            (Some(0x8d), Some(modrm)) if b0 & 0xfe == 0x48 => {
                let base = ((b0 & 1) << 3) | (modrm & 7);
                // `lea rsp, [frame + disp8 or disp32]`, no SIB byte.
                if base != 0 && base == frame_register && modrm & 7 != 4 {
                    match modrm & 0xf8 {
                        0x60 => {
                            adjust = Some((true, i64::from(i8::from_le_bytes([byte(3)?]))));
                            at = 4;
                        }
                        0xa0 => {
                            adjust = Some((true, i64::from(i32_at(code, 3)?)));
                            at = 7;
                        }
                        _ => return None,
                    }
                } else {
                    return None;
                }
            }
            _ => {}
        }
    }
    let mut pops = [0_u8; MAX_POPS];
    let mut pop_count = 0;
    loop {
        let (rex, op) = match byte(at)? {
            prefix @ 0x40..=0x4f => (prefix, byte(at + 1)?),
            op => (0, op),
        };
        if op & 0xf8 != 0x58 {
            break;
        }
        *pops.get_mut(pop_count)? = ((rex & 1) << 3) | (op & 7);
        pop_count += 1;
        at += if rex == 0 { 1 } else { 2 };
    }
    // A `repne` prefix on the control transfer changes nothing for unwinding.
    if byte(at)? == 0xf2 {
        at += 1;
    }
    let release = match (byte(at)?, byte(at + 1)) {
        // ret, rep ret, jmp [rip + disp32].
        (0xc3, _) | (0xf3, Some(0xc3)) | (0xff, Some(0x25)) => 0,
        (0xc2, _) => u64::from(u16_at(code, at + 1)?),
        (op @ (0xeb | 0xe9), _) => {
            let (length, displacement) = if op == 0xeb {
                (2, i64::from(i8::from_le_bytes([byte(at + 1)?])))
            } else {
                (5, i64::from(i32_at(code, at + 1)?))
            };
            let next = i64::from(rva) + i64::try_from(at).ok()? + length;
            // A target outside the u32 RVA range leaves the image and is an external tail call.
            // A jump to the start of the function is a recursive tail call. A jump elsewhere
            // inside its entry is ordinary control flow, and so is one into another entry of
            // the same function (one with the same primary entry, across chained infos).
            let tail_call = match u32::try_from(next + displacement) {
                Err(_) => true,
                Ok(target) if target < function.begin || target >= function.end => {
                    same_function(function, target, table, image)
                        .is_none_or(|primary| target == primary.begin)
                }
                Ok(target) => target == function.begin && !block.chained,
            };
            if !tail_call {
                return None;
            }
            0
        }
        (rex, Some(0xff)) if rex & 0xf8 == 0x48 && byte(at + 2)? & 0x38 == 0x20 => 0,
        _ => return None,
    };
    Some(Epilog {
        adjust,
        pops,
        pop_count,
        release,
    })
}

/// The epilog the thread is in, if any: decoded from the instructions for version 1, looked
/// up in the epilog descriptors for version 2 (whose instructions are never decoded).
fn find_epilog(
    frame: &Frame,
    block: &Block,
    table: &[RuntimeFunction],
    image: &mut impl Image,
) -> Option<InEpilog> {
    if block.version >= 2 {
        let epilogs = block.epilogs.as_ref()?;
        return epilogs
            .holding(frame.entry.function, frame.pc)
            .map(InEpilog::Described);
    }
    let mut window = [0_u8; EPILOG_WINDOW];
    let len = read_window(image, frame.pc, &mut window);
    let code = window.get(..len)?;
    decode_epilog(code, frame.pc, frame.entry.function, block, table, image).map(InEpilog::Decoded)
}

fn emulate_epilog(
    epilog: &Epilog,
    frame_register: u8,
    regs: &mut Registers,
    stack: &StackCopy,
) -> Option<()> {
    match epilog.adjust {
        Some((false, add)) => regs.gpr[RSP] = regs.rsp().checked_add_signed(add)?,
        Some((true, disp)) => regs.gpr[RSP] = regs.get(frame_register)?.checked_add_signed(disp)?,
        None => {}
    }
    for &register in epilog.pops.get(..epilog.pop_count)? {
        let value = stack.word(regs.rsp())?;
        regs.set(register, value)?;
        regs.gpr[RSP] = regs.rsp().checked_add(8)?;
    }
    regs.rip = stack.word(regs.rsp())?;
    regs.gpr[RSP] = regs.rsp().checked_add(8)?.checked_add(epilog.release)?;
    Some(())
}

/// Finish a version 2 epilog `into` bytes in. Its instructions mirror the prolog's pushes: the
/// pops in unwind-code order (one byte each, two for r8 to r15), an optional one-byte pop
/// for a pushed RFLAGS (`UWOP_ALLOC_SMALL` 8), then `ret`, a jump, or `iretq` for a machine
/// frame. The pushes all sit in the first info of the chain that has any.
fn finish_described_epilog(
    plan: &UnwindPlan,
    into: u32,
    regs: &mut Registers,
    stack: &StackCopy,
) -> Option<Stepped> {
    let pushes = |code: &Code| matches!(code.op, Op::Push(_) | Op::MachineFrame(_));
    let codes = plan
        .blocks
        .iter()
        .find_map(|block| block.codes.get(block.codes.iter().position(pushes)?..))
        .unwrap_or_default();
    let mut codes = codes.iter().peekable();
    // Epilog bytes before the instruction undoing the next code.
    let mut done = 0_u32;
    while let Some(&&Code {
        op: Op::Push(register),
        ..
    }) = codes.peek()
    {
        if done >= into {
            let value = stack.word(regs.rsp())?;
            regs.set(register, value)?;
            regs.gpr[RSP] = regs.rsp().checked_add(8)?;
        }
        done += if register >= 8 { 2 } else { 1 };
        codes.next();
    }
    if codes.next_if(|code| code.op == Op::Alloc(8)).is_some() && done >= into {
        regs.gpr[RSP] = regs.rsp().checked_add(8)?;
    }
    match codes.next() {
        None => {}
        Some(&Code {
            op: Op::MachineFrame(_),
            ..
        }) => {
            // As the system unwinder does in an epilog: the frame is at the stack pointer.
            regs.rip = stack.word(regs.rsp())?;
            regs.gpr[RSP] = stack.word(regs.rsp().checked_add(24)?)?;
            return Some(Stepped::MachineFrame);
        }
        // No other operation can follow the pushes an epilog undoes.
        Some(_) => return None,
    }
    regs.rip = stack.word(regs.rsp())?;
    regs.gpr[RSP] = regs.rsp().checked_add(8)?;
    Some(Stepped::Return)
}

/// Unwind one frame: on success `regs` hold the caller's registers. Every stack read goes
/// through `stack` and every image read through `image`, so a frame that would read outside
/// them stops the walk (`None`, with `regs` unchanged).
pub(crate) fn step(
    frame: &Frame,
    regs: &mut Registers,
    stack: &StackCopy,
    table: &[RuntimeFunction],
    image: &mut impl Image,
) -> Option<Stepped> {
    let primary = frame.plan.blocks.first()?;
    let Entry { sampled, function } = frame.entry;
    let pc = frame.pc;
    // The pc must be in the entry it was found in (a return address may be just past it).
    if pc < sampled.begin || pc > sampled.end || (frame.exact && pc == sampled.end) {
        return None;
    }
    // A pc outside the resolved entry is in an indirect fragment: body code, no prolog.
    let offset = if pc >= function.begin && pc <= function.end {
        pc - function.begin
    } else {
        u32::MAX
    };
    let in_prolog = offset < u32::from(primary.prolog);
    let mut next = *regs;
    let frame_register = primary.frame_register;
    // Epilogs first: past its `pop rbp` the frame register no longer marks the frame.
    if frame.exact
        && !in_prolog
        && let Some(epilog) = find_epilog(frame, primary, table, image)
    {
        let stepped = match epilog {
            InEpilog::Decoded(epilog) => {
                emulate_epilog(&epilog, frame_register, &mut next, stack)?;
                Stepped::Return
            }
            InEpilog::Described(into) => {
                finish_described_epilog(frame.plan, into, &mut next, stack)?
            }
        };
        *regs = next;
        return Some(stepped);
    }
    // The frame base, which only saves need.
    let from_frame = |regs: &Registers| regs.get(frame_register)?.checked_sub(primary.frame_offset);
    let frame_base = if frame_register == 0 {
        Some(regs.rsp())
    } else if !in_prolog || primary.chained {
        from_frame(regs)
    } else {
        // In the prolog: the frame register holds the frame once its SET_FPREG ran.
        primary
            .codes
            .iter()
            .find(|code| code.op == Op::SetFrame)
            .and_then(|code| {
                if offset >= u32::from(code.offset) {
                    from_frame(regs)
                } else {
                    Some(regs.rsp())
                }
            })
    };
    let mut machine_frame = false;
    for (index, block) in frame.plan.blocks.iter().enumerate() {
        for code in &block.codes {
            // The function's own prolog codes apply once executed; chained ones always.
            if index == 0 && offset < u32::from(code.offset) {
                continue;
            }
            match code.op {
                Op::Push(register) => {
                    let value = stack.word(next.rsp())?;
                    next.set(register, value)?;
                    next.gpr[RSP] = next.rsp().checked_add(8)?;
                }
                Op::Alloc(bytes) => next.gpr[RSP] = next.rsp().checked_add(bytes)?,
                Op::SetFrame => {
                    next.gpr[RSP] = next
                        .get(block.frame_register)?
                        .checked_sub(block.frame_offset)?;
                }
                Op::Save(register, at) => {
                    let value = stack.word(frame_base?.checked_add(at)?)?;
                    next.set(register, value)?;
                }
                Op::Skip => {}
                Op::MachineFrame(error_code) => {
                    let base = next.rsp().checked_add(if error_code { 8 } else { 0 })?;
                    next.rip = stack.word(base)?;
                    next.gpr[RSP] = stack.word(base.checked_add(24)?)?;
                    machine_frame = true;
                }
            }
        }
    }
    if machine_frame {
        *regs = next;
        return Some(Stepped::MachineFrame);
    }
    next.rip = stack.word(next.rsp())?;
    next.gpr[RSP] = next.rsp().checked_add(8)?;
    *regs = next;
    Some(Stepped::Return)
}

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

    /// A fake image: bytes placed at RVAs; everything in it is readable.
    struct Fake(Vec<u8>);

    impl Fake {
        fn new() -> Self {
            Self(vec![0; 0x2000])
        }

        fn put(&mut self, rva: usize, bytes: &[u8]) {
            self.0[rva..rva + bytes.len()].copy_from_slice(bytes);
        }

        /// An `UNWIND_INFO`: `version`, `flags`, prolog size, frame byte, code slots.
        fn info_v(
            &mut self,
            rva: usize,
            version: u8,
            flags: u8,
            prolog: u8,
            frame: u8,
            slots: &[u16],
        ) {
            let mut bytes = vec![
                version | (flags << 3),
                prolog,
                u8::try_from(slots.len()).unwrap(),
                frame,
            ];
            for slot in slots {
                bytes.extend(slot.to_le_bytes());
            }
            self.put(rva, &bytes);
        }

        fn info(&mut self, rva: usize, flags: u8, prolog: u8, frame: u8, slots: &[u16]) {
            self.info_v(rva, 1, flags, prolog, frame, slots);
        }

        fn function(&mut self, rva: usize, begin: u32, end: u32, unwind: u32) {
            let mut bytes = Vec::new();
            bytes.extend(begin.to_le_bytes());
            bytes.extend(end.to_le_bytes());
            bytes.extend(unwind.to_le_bytes());
            self.put(rva, &bytes);
        }

        fn reader(&self) -> impl FnMut(u32, &mut [u8]) -> bool + '_ {
            |rva, out| {
                let start = rva as usize;
                match self.0.get(start..start + out.len()) {
                    Some(src) => {
                        out.copy_from_slice(src);
                        true
                    }
                    None => false,
                }
            }
        }

        fn plan(&self, rva: u32) -> Option<UnwindPlan> {
            load_plan(rva, &mut self.reader())
        }
    }

    fn code(offset: u8, op: u8, info: u8) -> u16 {
        u16::from(offset) | (u16::from(op | (info << 4)) << 8)
    }

    /// The bytes of a stack copy holding `words`.
    fn stack_of(words: &[u64]) -> Vec<u8> {
        words.iter().flat_map(|word| word.to_le_bytes()).collect()
    }

    const BASE: u64 = 0x10_0000;
    const FUNCTION: RuntimeFunction = RuntimeFunction {
        begin: 0x1000,
        end: 0x1100,
        unwind: 0x100,
    };

    const ENTRY: Entry = Entry {
        sampled: FUNCTION,
        function: FUNCTION,
    };

    const fn function(begin: u32, end: u32, unwind: u32) -> RuntimeFunction {
        RuntimeFunction { begin, end, unwind }
    }

    /// Step `frame` over a stack copy holding `bytes`.
    fn step_over(
        image: &Fake,
        frame: &Frame,
        table: &[RuntimeFunction],
        regs: &mut Registers,
        bytes: &[u8],
    ) -> Option<Stepped> {
        let stack = StackCopy { base: BASE, bytes };
        step(frame, regs, &stack, table, &mut image.reader())
    }

    fn regs(rsp: u64) -> Registers {
        let mut regs = Registers::default();
        regs.gpr[RSP] = rsp;
        regs
    }

    fn run(
        image: &Fake,
        plan: &UnwindPlan,
        pc: u32,
        exact: bool,
        regs: &mut Registers,
        bytes: &[u8],
    ) -> Option<Stepped> {
        let frame = Frame {
            entry: ENTRY,
            plan,
            pc,
            exact,
        };
        let stack = StackCopy { base: BASE, bytes };
        step(&frame, regs, &stack, &[FUNCTION], &mut image.reader())
    }

    #[test]
    fn stack_words_stay_inside_the_copy() {
        let bytes = stack_of(&[1, 2]);
        let stack = StackCopy {
            base: BASE,
            bytes: &bytes,
        };
        assert_eq!(stack.word(BASE), Some(1));
        assert_eq!(stack.word(BASE + 8), Some(2));
        assert_eq!(stack.word(BASE + 9), None, "runs past the end");
        assert_eq!(stack.word(BASE + 16), None);
        assert_eq!(stack.word(BASE - 8), None);
        assert_eq!(stack.word(u64::MAX - 3), None);
        assert!(
            !StackCopy {
                base: 0,
                bytes: &[]
            }
            .holds(0)
        );
    }

    #[test]
    fn a_leaf_info_pops_only_the_return_address() {
        let mut image = Fake::new();
        image.info(0x100, 0, 0, 0, &[]);
        let plan = image.plan(0x100).unwrap();
        let bytes = stack_of(&[0xdead]);
        let mut r = regs(BASE);
        assert_eq!(
            run(&image, &plan, 0x1010, false, &mut r, &bytes),
            Some(Stepped::Return)
        );
        assert_eq!((r.rip, r.rsp()), (0xdead, BASE + 8));
    }

    #[test]
    fn prolog_codes_apply_only_once_executed() {
        let mut image = Fake::new();
        // push rbx (1); push rbp (2); sub rsp, 0x10 (6). Codes in unwind order.
        image.info(
            0x100,
            0,
            6,
            0,
            &[code(6, 2, 1), code(2, 0, 5), code(1, 0, 3)],
        );
        let plan = image.plan(0x100).unwrap();
        // Body: [rsp] 16 bytes of locals, saved rbp, saved rbx, return address.
        let bytes = stack_of(&[0, 0, 0xb9, 0xb3, 0xaaa]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1020, false, &mut r, &bytes).unwrap();
        assert_eq!(
            (r.rip, r.rsp(), r.gpr[5], r.gpr[3]),
            (0xaaa, BASE + 40, 0xb9, 0xb3)
        );
        // One byte in: only `push rbx` ran, so [rsp] is rbx and then the return address.
        let bytes = stack_of(&[0xb3, 0xbbb]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1001, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0xbbb, BASE + 16, 0xb3));
        // At the very start nothing ran.
        let bytes = stack_of(&[0xccc]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1000, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp()), (0xccc, BASE + 8));
    }

    #[test]
    fn large_allocations_and_far_saves() {
        let mut image = Fake::new();
        // sub rsp, 0x18 (large, 16-bit scaled: 3 * 8); save rsi at [base + 0x8] (far).
        image.info(
            0x100,
            0,
            12,
            0,
            &[code(12, 5, 6), 0x0008, 0x0000, code(7, 1, 0), 3],
        );
        let plan = image.plan(0x100).unwrap();
        let bytes = stack_of(&[0, 0x51, 0, 0x777]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1040, false, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp(), r.gpr[6]), (0x777, BASE + 32, 0x51));
        // 32-bit allocation.
        image.info(0x200, 0, 9, 0, &[code(9, 1, 1), 0x0010, 0x0000]);
        let plan = image.plan(0x200).unwrap();
        let mut words = vec![0_u64; 2];
        words.push(0x888);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1040, false, &mut r, &stack_of(&words)).unwrap();
        assert_eq!((r.rip, r.rsp()), (0x888, BASE + 24));
    }

    #[test]
    fn frame_register_establishes_the_frame() {
        let mut image = Fake::new();
        // push rbp (1); sub rsp, 0x20 (5); lea rbp, [rsp + 0x10] (10: SET_FPREG, offset 1*16);
        // save rbx at [base + 0x8] (14).
        image.info(
            0x100,
            0,
            14,
            5 | (1 << 4),
            &[
                code(14, 4, 3),
                1,
                code(10, 3, 0),
                code(5, 2, 3),
                code(1, 0, 5),
            ],
        );
        let plan = image.plan(0x100).unwrap();
        // The body moved rsp down by 0x40 more (a dynamic alloca); rbp still marks the frame.
        let frame = BASE + 0x40;
        let mut words = vec![0_u64; 8];
        words.extend([0, 0xb3, 0, 0, 0xb9, 0x999]);
        let bytes = stack_of(&words);
        let mut r = regs(BASE);
        r.gpr[5] = frame + 0x10;
        run(&image, &plan, 0x1050, false, &mut r, &bytes).unwrap();
        assert_eq!(r.gpr[3], 0xb3, "rbx from [frame base + 8]");
        assert_eq!((r.rip, r.gpr[5], r.rsp()), (0x999, 0xb9, frame + 0x30));
        // A frame register pointing below the copy stops the walk.
        let mut r = regs(BASE);
        r.gpr[5] = 0x8;
        assert_eq!(run(&image, &plan, 0x1050, false, &mut r, &bytes), None);
        assert_eq!(r.gpr[5], 0x8, "registers untouched on a stop");
    }

    #[test]
    fn in_the_prolog_the_frame_register_counts_once_set() {
        let mut image = Fake::new();
        // push rbp (1); mov rbp, rsp (4: SET_FPREG); sub rsp, 0x10 (8).
        image.info(
            0x100,
            0,
            8,
            5,
            &[code(8, 2, 1), code(4, 3, 0), code(1, 0, 5)],
        );
        let plan = image.plan(0x100).unwrap();
        // Offset 4: rbp = rsp, nothing allocated yet.
        let bytes = stack_of(&[0xb9, 0x123]);
        let mut r = regs(BASE);
        r.gpr[5] = BASE;
        run(&image, &plan, 0x1004, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.gpr[5], r.rsp()), (0x123, 0xb9, BASE + 16));
        // Offset 1: rbp is the caller's, rsp is the frame.
        let mut r = regs(BASE);
        r.gpr[5] = 0x5555;
        run(&image, &plan, 0x1001, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.gpr[5], r.rsp()), (0x123, 0xb9, BASE + 16));
    }

    #[test]
    fn machine_frames_give_an_exact_pc() {
        let mut image = Fake::new();
        image.info(0x100, 0, 0, 0, &[code(0, 10, 0)]);
        let plan = image.plan(0x100).unwrap();
        // rip, cs, eflags, rsp, ss.
        let bytes = stack_of(&[0x4242, 0x33, 0x246, BASE + 0x1000, 0x2b]);
        let mut r = regs(BASE);
        assert_eq!(
            run(&image, &plan, 0x1000, false, &mut r, &bytes),
            Some(Stepped::MachineFrame)
        );
        assert_eq!((r.rip, r.rsp()), (0x4242, BASE + 0x1000));
        // With an error code first.
        image.info(0x180, 0, 0, 0, &[code(0, 10, 1)]);
        let plan = image.plan(0x180).unwrap();
        let bytes = stack_of(&[7, 0x4343, 0x33, 0x246, BASE + 0x2000, 0x2b]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1000, false, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp()), (0x4343, BASE + 0x2000));
        // Truncated frame: stops.
        let mut r = regs(BASE);
        assert_eq!(
            run(&image, &plan, 0x1000, false, &mut r, &bytes[..32]),
            None
        );
    }

    #[test]
    fn chained_infos_apply_in_full() {
        let mut image = Fake::new();
        // The fragment's own code: one push (offset 1, past its prolog of 1), chained (odd
        // count: one padding slot) to the parent.
        image.info(0x100, UNW_FLAG_CHAININFO, 1, 0, &[code(1, 0, 3)]);
        image.function(0x100 + 4 + 4, 0x800, 0x900, 0x200);
        // The parent: sub rsp, 0x18 (5); push rbp (1). Its offsets are its own and all apply.
        image.info(0x200, 0, 5, 0, &[code(5, 2, 2), code(1, 0, 5)]);
        let plan = image.plan(0x100).unwrap();
        let bytes = stack_of(&[0xb3, 0, 0, 0, 0xb9, 0xabc]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1010, false, &mut r, &bytes).unwrap();
        assert_eq!(
            (r.rip, r.rsp(), r.gpr[3], r.gpr[5]),
            (0xabc, BASE + 48, 0xb3, 0xb9)
        );
    }

    #[test]
    fn chained_frame_registers_must_agree() {
        let mut image = Fake::new();
        // The fragment names rbp; its parent sets the frame through rbp: fine.
        image.info(0x100, UNW_FLAG_CHAININFO, 0, 5, &[]);
        image.function(0x104, 0x800, 0x900, 0x200);
        image.info(0x200, 0, 4, 5, &[code(4, 3, 0), code(1, 0, 5)]);
        let plan = image.plan(0x100).unwrap();
        // Out of the prolog the fragment unwinds from rbp: rsp = rbp, pop rbp, return.
        let bytes = stack_of(&[0, 0, 0xb9, 0xfed]);
        let mut r = regs(BASE);
        r.gpr[5] = BASE + 16;
        run(&image, &plan, 0x1010, false, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.gpr[5], r.rsp()), (0xfed, 0xb9, BASE + 32));
        // A parent with another frame register is refused.
        image.info(0x300, UNW_FLAG_CHAININFO, 0, 5, &[]);
        image.function(0x304, 0x800, 0x900, 0x400);
        image.info(0x400, 0, 4, 3, &[code(4, 3, 0)]);
        assert!(image.plan(0x300).is_none());
        // A parent that sets a frame the fragment does not name is refused.
        image.info(0x500, UNW_FLAG_CHAININFO, 0, 0, &[]);
        image.function(0x504, 0x800, 0x900, 0x200);
        assert!(image.plan(0x500).is_none());
    }

    #[test]
    fn malformed_infos_are_refused() {
        let mut image = Fake::new();
        image.put(0x100, &[3, 0, 0, 0]);
        assert!(image.plan(0x100).is_none(), "version 3");
        image.put(0x110, &[0, 0, 0, 0]);
        assert!(image.plan(0x110).is_none(), "version 0");
        image.info(0x200, 0, 4, 0, &[code(4, 1, 0)]);
        assert!(image.plan(0x200).is_none(), "ALLOC_LARGE without its slot");
        image.info(0x280, 0, 4, 0, &[code(4, 1, 2), 0, 0]);
        assert!(image.plan(0x280).is_none(), "ALLOC_LARGE info 2");
        for op in [6, 7, 11, 12, 15] {
            image.info(0x300, 0, 4, 0, &[code(4, op, 0), 0, 0]);
            assert!(image.plan(0x300).is_none(), "op {op} in version 1");
        }
        image.info(0x380, 0, 4, 0, &[code(4, 3, 0)]);
        assert!(
            image.plan(0x380).is_none(),
            "SET_FPREG without a frame register"
        );
        // Machine frames: not last, a bad info, or chained.
        image.info(0x400, 0, 0, 0, &[code(0, 10, 0), code(0, 0, 3)]);
        assert!(image.plan(0x400).is_none());
        image.info(0x440, 0, 0, 0, &[code(0, 10, 2)]);
        assert!(image.plan(0x440).is_none());
        image.info(0x480, UNW_FLAG_CHAININFO, 0, 0, &[code(0, 10, 0)]);
        assert!(image.plan(0x480).is_none());
        // Codes running past the image, and a header outside it.
        let mut tail = Fake(vec![0; 8]);
        tail.put(4, &[1, 0, 200, 0]);
        assert!(tail.plan(4).is_none());
        assert!(image.plan(0xffff_fff0).is_none());
        // A chain that never ends.
        image.info(0x500, UNW_FLAG_CHAININFO, 0, 0, &[]);
        image.function(0x504, 0, 0, 0x500);
        assert!(image.plan(0x500).is_none());
    }

    #[test]
    fn version_two_epilog_codes_are_skipped() {
        let mut image = Fake::new();
        image.info_v(0x100, 2, 0, 4, 0, &[code(1, 6, 1), 0x0000, code(1, 0, 3)]);
        let plan = image.plan(0x100).unwrap();
        let bytes = stack_of(&[0xb3, 0x321]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1040, false, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x321, BASE + 16, 0xb3));
    }

    #[test]
    fn huge_allocations_stop_instead_of_reading_past_the_copy() {
        let mut image = Fake::new();
        image.info(
            0x100,
            0,
            4,
            0,
            &[code(4, 1, 1), 0xffff, 0xffff, code(4, 1, 1), 0xffff, 0xffff],
        );
        let plan = image.plan(0x100).unwrap();
        let bytes = stack_of(&[1, 2, 3]);
        let mut r = regs(BASE);
        assert_eq!(run(&image, &plan, 0x1040, false, &mut r, &bytes), None);
        // And a save far above the copy.
        image.info(0x200, 0, 4, 0, &[code(4, 5, 3), 0xfff8, 0x7fff]);
        let plan = image.plan(0x200).unwrap();
        let mut r = regs(BASE);
        assert_eq!(run(&image, &plan, 0x1040, false, &mut r, &bytes), None);
        // A stack pointer near the top of the address space does not wrap.
        let mut r = regs(u64::MAX - 7);
        let stack = StackCopy {
            base: u64::MAX - 7,
            bytes: &bytes[..8],
        };
        let frame = Frame {
            entry: ENTRY,
            plan: &plan,
            pc: 0x1040,
            exact: false,
        };
        assert_eq!(step(&frame, &mut r, &stack, &[], &mut image.reader()), None);
    }

    /// An info with `push rbx; sub rsp, 0x10` whose epilog is `add rsp, 0x10; pop rbx; ret`.
    fn epilog_image(tail: &[u8]) -> (Fake, UnwindPlan) {
        let mut image = Fake::new();
        image.info(0x100, 0, 5, 0, &[code(5, 2, 1), code(1, 0, 3)]);
        image.put(0x1080, tail);
        let plan = image.plan(0x100).unwrap();
        (image, plan)
    }

    #[test]
    fn an_exact_pc_in_an_epilog_finishes_the_epilog() {
        let (image, plan) = epilog_image(&[0x48, 0x83, 0xc4, 0x10, 0x5b, 0xc3]);
        // At `add rsp, 0x10`: the whole frame is still there.
        let bytes = stack_of(&[0, 0, 0xb3, 0x1111]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x1111, BASE + 32, 0xb3));
        // At `pop rbx`: the locals are gone. The prolog codes would read the wrong slots.
        let bytes = stack_of(&[0xb3, 0x2222]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1084, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x2222, BASE + 16, 0xb3));
        // At `ret`.
        let bytes = stack_of(&[0x3333]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1085, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp()), (0x3333, BASE + 8));
        // A return address there is not exact: the prolog codes apply.
        let bytes = stack_of(&[0, 0, 0xb3, 0x4444]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1080, false, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp()), (0x4444, BASE + 32));
    }

    #[test]
    fn epilog_forms() {
        // add rsp, imm32; pop r12 (REX.B); rep ret.
        let (image, plan) =
            epilog_image(&[0x48, 0x81, 0xc4, 0x10, 0, 0, 0, 0x41, 0x5c, 0xf3, 0xc3]);
        let bytes = stack_of(&[0, 0, 0xc12, 0x5555]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.gpr[12], r.rsp()), (0x5555, 0xc12, BASE + 32));
        // ret 8 releases the argument bytes too.
        let (image, plan) = epilog_image(&[0xc2, 0x08, 0x00]);
        let bytes = stack_of(&[0x6666, 0]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp()), (0x6666, BASE + 16));
        // pop rbx; jmp rel32 to outside the function: a tail call.
        let (image, plan) = epilog_image(&[0x5b, 0xe9, 0x00, 0x01, 0x00, 0x00]);
        let bytes = stack_of(&[0xb3, 0x7777]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.gpr[3], r.rsp()), (0x7777, 0xb3, BASE + 16));
        // jmp [rip + disp32].
        let (image, plan) = epilog_image(&[0xff, 0x25, 0, 0, 0, 0]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1080, true, &mut r, &stack_of(&[0x8888])).unwrap();
        assert_eq!(r.rip, 0x8888);
    }

    #[test]
    fn jumps_inside_the_function_are_not_epilogs() {
        // pop rbx; jmp short back into the function: ordinary code, so the prolog codes apply.
        let (image, plan) = epilog_image(&[0x5b, 0xeb, 0xf0]);
        let bytes = stack_of(&[0, 0, 0xb3, 0x9999]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.rsp()), (0x9999, BASE + 32));
        // Not an epilog either: a plain instruction.
        let (image, plan) = epilog_image(&[0x90, 0xc3]);
        let mut r = regs(BASE);
        run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
        assert_eq!(r.rsp(), BASE + 32);
    }

    #[test]
    fn lea_epilogs_need_the_frame_register() {
        let mut image = Fake::new();
        // push rbp (1); mov rbp, rsp (4); sub rsp, 0x20 (8).
        image.info(
            0x100,
            0,
            8,
            5,
            &[code(8, 2, 3), code(4, 3, 0), code(1, 0, 5)],
        );
        // lea rsp, [rbp + 0]; pop rbp; ret.
        image.put(0x1080, &[0x48, 0x8d, 0x65, 0x00, 0x5d, 0xc3]);
        // lea rsp, [rbx + 0] (not the frame register): not an epilog.
        image.put(0x1090, &[0x48, 0x8d, 0x63, 0x00, 0x5d, 0xc3]);
        let plan = image.plan(0x100).unwrap();
        let mut words = vec![0_u64; 4];
        words.extend([0xb9, 0xaaaa]);
        let bytes = stack_of(&words);
        let mut r = regs(BASE);
        r.gpr[5] = BASE + 32;
        run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
        assert_eq!((r.rip, r.gpr[5], r.rsp()), (0xaaaa, 0xb9, BASE + 48));
        let mut r = regs(BASE);
        r.gpr[5] = BASE + 32;
        r.gpr[3] = 0x1;
        run(&image, &plan, 0x1090, true, &mut r, &bytes).unwrap();
        assert_eq!(r.rsp(), BASE + 48, "unwound from the codes instead");
    }

    #[test]
    fn epilogs_reading_past_the_copy_stop() {
        let (image, plan) = epilog_image(&[0x48, 0x81, 0xc4, 0x00, 0x00, 0x10, 0x00, 0xc3]);
        let bytes = stack_of(&[1, 2, 3]);
        let mut r = regs(BASE);
        assert_eq!(run(&image, &plan, 0x1080, true, &mut r, &bytes), None);
        // An epilog at the very end of the readable image still decodes from fewer bytes.
        let mut image = Fake(vec![0; 0x1082]);
        image.info(0x100, 0, 0, 0, &[]);
        image.put(0x1080, &[0x5b, 0xc3]);
        let plan = image.plan(0x100).unwrap();
        let mut r = regs(BASE);
        run(
            &image,
            &plan,
            0x1080,
            true,
            &mut r,
            &stack_of(&[0xb3, 0xbbbb]),
        )
        .unwrap();
        assert_eq!((r.rip, r.gpr[3]), (0xbbbb, 0xb3));
    }

    #[test]
    fn jumps_into_chained_fragments_of_the_function_are_not_tail_calls() {
        let mut image = Fake::new();
        // P, the primary entry: push rbx (1).
        image.info(0x200, 0, 1, 0, &[code(1, 0, 3)]);
        // A and B: separated fragments whose infos chain to P and have no codes of their own.
        image.info(0x100, UNW_FLAG_CHAININFO, 0, 0, &[]);
        image.function(0x104, 0x1400, 0x1500, 0x200);
        image.info(0x300, UNW_FLAG_CHAININFO, 0, 0, &[]);
        image.function(0x304, 0x1400, 0x1500, 0x200);
        // C, another function.
        image.info(0x400, 0, 0, 0, &[]);
        let a = function(0x1000, 0x1100, 0x100);
        let table = [
            a,
            function(0x1200, 0x1300, 0x300),
            function(0x1400, 0x1500, 0x200),
            function(0x1600, 0x1700, 0x400),
        ];
        let plan = image.plan(0x100).unwrap();
        let frame = Frame {
            entry: Entry {
                sampled: a,
                function: a,
            },
            plan: &plan,
            pc: 0x1080,
            exact: true,
        };
        // [rsp] is rbx: a tail call would take it for the return address.
        let bytes = stack_of(&[0xb3, 0x1234]);
        let check = |image: &mut Fake, target: u32, tail_call: bool| {
            // jmp rel32 at 0x1080, so relative to 0x1085.
            image.put(0x1080, &[0xe9]);
            image.put(0x1081, &target.wrapping_sub(0x1085).to_le_bytes());
            let mut r = regs(BASE);
            assert_eq!(
                step_over(image, &frame, &table, &mut r, &bytes),
                Some(Stepped::Return)
            );
            let expected = if tail_call {
                (0xb3, 0, BASE + 8)
            } else {
                (0x1234, 0xb3, BASE + 16)
            };
            assert_eq!((r.rip, r.gpr[3], r.rsp()), expected, "jmp {target:x}");
        };
        // Into fragment B, or into P past its start: the same function (primary entry P), so
        // the body unwinds through P's codes.
        check(&mut image, 0x1210, false);
        check(&mut image, 0x1410, false);
        // To A's own start: A is a chained fragment, not a function start.
        check(&mut image, 0x1000, false);
        // To P's start: a recursive tail call. To C: a tail call.
        check(&mut image, 0x1400, true);
        check(&mut image, 0x1610, true);
        // B chained to another primary entry belongs to another function.
        image.function(0x304, 0x1600, 0x1700, 0x400);
        check(&mut image, 0x1210, true);
    }

    /// A version 2 info for push r12 (2); push rbx (3); sub rsp, 0x20 (7). Its epilogs are
    /// `add rsp, 0x20` and then the 4-byte region `pop rbx; pop r12; ret`: one ends the
    /// function, one starts 0x40 bytes before the end.
    fn v2_image() -> (Fake, UnwindPlan) {
        let mut image = Fake::new();
        image.info_v(
            0x100,
            2,
            0,
            7,
            0,
            &[
                code(4, 6, 1),
                code(0x40, 6, 0),
                code(7, 2, 3),
                code(3, 0, 3),
                code(2, 0, 12),
            ],
        );
        // Bytes shaped like a version 1 epilog where there is none: never decoded.
        image.put(0x1050, &[0x5b, 0xc3]);
        let plan = image.plan(0x100).unwrap();
        (image, plan)
    }

    #[test]
    fn version_two_epilogs_follow_their_descriptors() {
        let (image, plan) = v2_image();
        let epilogs = plan.blocks[0].epilogs.clone().unwrap();
        assert_eq!(
            epilogs,
            Epilogs {
                size: 4,
                at_end: true,
                back: vec![0x40]
            }
        );
        let full = stack_of(&[0, 0, 0, 0, 0xb3, 0xc12, 0x1111]);
        let unwound = |r: &Registers| (r.rip, r.rsp(), r.gpr[3], r.gpr[12]);
        // At the end epilog's first pop (0x10fc): both pops and the return remain.
        let mut r = regs(BASE);
        let bytes = stack_of(&[0xb3, 0xc12, 0x1111]);
        assert_eq!(
            run(&image, &plan, 0x10fc, true, &mut r, &bytes),
            Some(Stepped::Return)
        );
        assert_eq!(unwound(&r), (0x1111, BASE + 24, 0xb3, 0xc12));
        // One byte in, `pop rbx` ran: rbx is already the caller's.
        let mut r = regs(BASE);
        r.gpr[3] = 0x77;
        run(
            &image,
            &plan,
            0x10fd,
            true,
            &mut r,
            &stack_of(&[0xc12, 0x2222]),
        )
        .unwrap();
        assert_eq!(unwound(&r), (0x2222, BASE + 16, 0x77, 0xc12));
        // At `ret`, after the two-byte `pop r12`.
        let mut r = regs(BASE);
        run(&image, &plan, 0x10ff, true, &mut r, &stack_of(&[0x3333])).unwrap();
        assert_eq!(unwound(&r), (0x3333, BASE + 8, 0, 0));
        // The other epilog, one byte in.
        let mut r = regs(BASE);
        run(
            &image,
            &plan,
            0x10c1,
            true,
            &mut r,
            &stack_of(&[0xc12, 0x4444]),
        )
        .unwrap();
        assert_eq!(unwound(&r), (0x4444, BASE + 16, 0, 0xc12));
        // Before the region (at `add rsp, 0x20`), and at a return address inside it, the body
        // unwinds through every code.
        for (pc, exact) in [(0x10f8, true), (0x10fc, false), (0x10c1, false)] {
            let mut r = regs(BASE);
            run(&image, &plan, pc, exact, &mut r, &full).unwrap();
            assert_eq!(unwound(&r), (0x1111, BASE + 56, 0xb3, 0xc12), "{pc:x}");
        }
        // Version 2 never decodes instructions: `pop rbx; ret` at 0x1050 is body code.
        let mut r = regs(BASE);
        run(&image, &plan, 0x1050, true, &mut r, &full).unwrap();
        assert_eq!(unwound(&r), (0x1111, BASE + 56, 0xb3, 0xc12));
        // An epilog whose stack is cut short stops.
        let mut r = regs(BASE);
        assert_eq!(run(&image, &plan, 0x10fc, true, &mut r, &bytes[..16]), None);
    }

    #[test]
    fn version_two_machine_frame_epilogs_end_in_iretq() {
        // Modelled on an ntdll interrupt-style routine: the processor pushed a machine frame,
        // then push rbx (1). The epilog `pop rbx; iretq` (5b 48 cf) ends the function.
        let mut image = Fake::new();
        image.info_v(
            0x100,
            2,
            0,
            1,
            0,
            &[code(3, 6, 1), code(0, 6, 0), code(1, 0, 3), code(0, 10, 0)],
        );
        image.put(0x10fd, &[0x5b, 0x48, 0xcf]);
        let plan = image.plan(0x100).unwrap();
        // rip, cs, eflags, rsp, ss.
        let frame = [0x4242, 0x33, 0x246, BASE + 0x1000, 0x2b];
        let mut words = vec![0xb3];
        words.extend(frame);
        let mut r = regs(BASE);
        assert_eq!(
            run(&image, &plan, 0x10fd, true, &mut r, &stack_of(&words)),
            Some(Stepped::MachineFrame)
        );
        assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x4242, BASE + 0x1000, 0xb3));
        // At the `iretq`: rbx was popped, the frame is on top.
        let mut r = regs(BASE);
        assert_eq!(
            run(&image, &plan, 0x10fe, true, &mut r, &stack_of(&frame)),
            Some(Stepped::MachineFrame)
        );
        assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x4242, BASE + 0x1000, 0));
    }

    #[test]
    fn epilogs_at_a_section_end_and_repne_transfers() {
        // `pop r12; ret` in the last three readable bytes of the image.
        let mut image = Fake(vec![0; 0x1083]);
        image.info(0x100, 0, 0, 0, &[]);
        image.put(0x1080, &[0x41, 0x5c, 0xc3]);
        let plan = image.plan(0x100).unwrap();
        let mut window = [0_u8; EPILOG_WINDOW];
        assert_eq!(read_window(&mut image.reader(), 0x1080, &mut window), 3);
        assert_eq!(window[..3], [0x41, 0x5c, 0xc3]);
        let mut r = regs(BASE);
        run(
            &image,
            &plan,
            0x1080,
            true,
            &mut r,
            &stack_of(&[0xc12, 0xbbbb]),
        )
        .unwrap();
        assert_eq!((r.rip, r.gpr[12], r.rsp()), (0xbbbb, 0xc12, BASE + 16));
        // At `pop rbx` of `add rsp, 0x10; pop rbx; repne ret`: the locals are gone.
        let (image, plan) = epilog_image(&[0x48, 0x83, 0xc4, 0x10, 0x5b, 0xf2, 0xc3]);
        let mut r = regs(BASE);
        run(
            &image,
            &plan,
            0x1084,
            true,
            &mut r,
            &stack_of(&[0xb3, 0x2222]),
        )
        .unwrap();
        assert_eq!((r.rip, r.gpr[3], r.rsp()), (0x2222, 0xb3, BASE + 16));
        // pop rbx; repne jmp rel32 out of the function: a tail call.
        let (image, plan) = epilog_image(&[0x5b, 0xf2, 0xe9, 0x00, 0x01, 0x00, 0x00]);
        let mut r = regs(BASE);
        run(
            &image,
            &plan,
            0x1080,
            true,
            &mut r,
            &stack_of(&[0xb3, 0x7777]),
        )
        .unwrap();
        assert_eq!((r.rip, r.gpr[3], r.rsp()), (0x7777, 0xb3, BASE + 16));
        // pop rbx; repne jmp short back inside: ordinary code, the prolog codes apply.
        let (image, plan) = epilog_image(&[0x5b, 0xf2, 0xeb, 0xf0]);
        let mut r = regs(BASE);
        run(
            &image,
            &plan,
            0x1080,
            true,
            &mut r,
            &stack_of(&[0, 0, 0xb3, 0x9999]),
        )
        .unwrap();
        assert_eq!((r.rip, r.rsp()), (0x9999, BASE + 32));
        // repne jmp rel32 targeting below the image base (negative RVA): external tail call.
        let (image, plan) = epilog_image(&[0xf2, 0xe9, 0x5a, 0xef, 0xff, 0xff]);
        let mut r = regs(BASE);
        run(
            &image,
            &plan,
            0x1080,
            true,
            &mut r,
            &stack_of(&[0x5555, 0, 0xdead]),
        )
        .unwrap();
        assert_eq!((r.rip, r.rsp()), (0x5555, BASE + 8));
    }

    #[test]
    fn an_epilog_unwinds_once_the_frame_register_is_restored() {
        let mut image = Fake::new();
        // push rbp (1); lea rbp, [rsp + 0x10] (5: SET_FPREG, frame offset 16).
        image.info(0x100, 0, 5, 5 | (1 << 4), &[code(5, 3, 0), code(1, 0, 5)]);
        // pop rbp; ret.
        image.put(0x1080, &[0x5d, 0xc3]);
        let plan = image.plan(0x100).unwrap();
        // At `ret`, rbp holds the caller's 0, which is below the frame offset.
        let mut r = regs(BASE);
        assert_eq!(
            run(&image, &plan, 0x1081, true, &mut r, &stack_of(&[0x5678])),
            Some(Stepped::Return)
        );
        assert_eq!((r.rip, r.rsp(), r.gpr[5]), (0x5678, BASE + 8, 0));
    }

    #[test]
    fn lookups_follow_the_table_and_indirect_entries() {
        let mut image = Fake::new();
        image.function(0x600, 0x3000, 0x3100, 0x700);
        let table = [
            RuntimeFunction {
                begin: 0x1000,
                end: 0x1100,
                unwind: 0x100,
            },
            RuntimeFunction {
                begin: 0x2000,
                end: 0x2010,
                unwind: 0x601,
            },
        ];
        let mut reader = image.reader();
        let own = |function| {
            Some(Entry {
                sampled: function,
                function,
            })
        };
        assert_eq!(lookup(&table, 0x1000, &mut reader), own(table[0]));
        assert_eq!(lookup(&table, 0x10ff, &mut reader), own(table[0]));
        assert_eq!(
            lookup(&table, 0x1100, &mut reader),
            None,
            "end is exclusive"
        );
        assert_eq!(lookup(&table, 0xfff, &mut reader), None);
        let fragment = lookup(&table, 0x2008, &mut reader).unwrap();
        assert_eq!(
            fragment.sampled, table[1],
            "the entry holding the pc is kept"
        );
        assert_eq!(fragment.function, function(0x3000, 0x3100, 0x700));
        assert_eq!(lookup(&[], 5, &mut reader), None);
        drop(reader);
        // A pc in the fragment, below its primary entry, is body code of the primary: its codes
        // (push rbx; sub rsp, 0x10) apply in full.
        image.info(0x700, 0, 5, 0, &[code(5, 2, 1), code(1, 0, 3)]);
        let plan = image.plan(0x700).unwrap();
        let bytes = stack_of(&[0, 0, 0xb3, 0xfeed]);
        for exact in [false, true] {
            let frame = Frame {
                entry: fragment,
                plan: &plan,
                pc: 0x2008,
                exact,
            };
            let mut r = regs(BASE);
            assert_eq!(
                step_over(&image, &frame, &table, &mut r, &bytes),
                Some(Stepped::Return)
            );
            assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0xfeed, BASE + 32, 0xb3));
        }
        // A return address just past the fragment is still in it; anything else is not.
        let at = |pc, exact| Frame {
            entry: fragment,
            plan: &plan,
            pc,
            exact,
        };
        let mut r = regs(BASE);
        assert!(step_over(&image, &at(0x2010, false), &table, &mut r, &bytes).is_some());
        for (pc, exact) in [
            (0x2010, true),
            (0x1fff, false),
            (0x2011, false),
            (0x3008, true),
        ] {
            let mut r = regs(BASE);
            assert_eq!(
                step_over(&image, &at(pc, exact), &table, &mut r, &bytes),
                None,
                "{pc:x}"
            );
        }
        // An indirect entry pointing at itself is refused.
        image.function(0x800, 0, 0, 0x801);
        let looping = [RuntimeFunction {
            begin: 0,
            end: 0x10,
            unwind: 0x801,
        }];
        assert_eq!(lookup(&looping, 4, &mut image.reader()), None);
    }

    #[test]
    fn pdata_parses_whole_entries() {
        let mut bytes = Vec::new();
        for value in [0x1000_u32, 0x1010, 0x100, 0x2000, 0x2020, 0x200, 7] {
            bytes.extend(value.to_le_bytes());
        }
        let table = parse_pdata(&bytes);
        assert_eq!(table.len(), 2);
        assert_eq!(table[1].unwind, 0x200);
    }

    /// A minimal PE32+ header: two sections, one readable.
    fn pe_header() -> Vec<u8> {
        let mut bytes = vec![0_u8; 0x400];
        bytes[0..2].copy_from_slice(b"MZ");
        bytes[0x3c..0x40].copy_from_slice(&0x80_u32.to_le_bytes());
        bytes[0x80..0x84].copy_from_slice(b"PE\0\0");
        let file = 0x84;
        bytes[file..file + 2].copy_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
        bytes[file + 2..file + 4].copy_from_slice(&2_u16.to_le_bytes());
        bytes[file + 4..file + 8].copy_from_slice(&0x1234_5678_u32.to_le_bytes());
        bytes[file + 16..file + 18].copy_from_slice(&240_u16.to_le_bytes());
        let opt = file + 20;
        bytes[opt..opt + 2].copy_from_slice(&IMAGE_NT_OPTIONAL_HDR64_MAGIC.to_le_bytes());
        bytes[opt + 56..opt + 60].copy_from_slice(&0x5000_u32.to_le_bytes());
        bytes[opt + 60..opt + 64].copy_from_slice(&0x400_u32.to_le_bytes());
        bytes[opt + 64..opt + 68].copy_from_slice(&0xabcd_u32.to_le_bytes());
        bytes[opt + 108..opt + 112].copy_from_slice(&16_u32.to_le_bytes());
        bytes[opt + 136..opt + 140].copy_from_slice(&0x3000_u32.to_le_bytes());
        bytes[opt + 140..opt + 144].copy_from_slice(&0x24_u32.to_le_bytes());
        let section = |bytes: &mut Vec<u8>, at: usize, size: u32, address: u32, flags: u32| {
            bytes[at + 8..at + 12].copy_from_slice(&size.to_le_bytes());
            bytes[at + 12..at + 16].copy_from_slice(&address.to_le_bytes());
            bytes[at + 36..at + 40].copy_from_slice(&flags.to_le_bytes());
        };
        let table = opt + 240;
        section(&mut bytes, table, 0x1800, 0x1000, 0x6000_0020);
        section(&mut bytes, table + 40, 0x800, 0x3000, 0x0000_0040);
        bytes
    }

    #[test]
    fn pe_headers_parse() {
        let pe = parse_pe(&pe_header()).unwrap();
        assert_eq!(pe.size, 0x5000);
        assert_eq!((pe.stamp, pe.checksum), (0x1234_5678, 0xabcd));
        assert_eq!(pe.exception, (0x3000, 0x24));
        assert_eq!(pe.readable, vec![(0, 0x400), (0x1000, 0x2800)]);
        assert!(pe.is_readable(0x1000, 0x1800));
        assert!(!pe.is_readable(0x1000, 0x1801));
        assert!(!pe.is_readable(0x3000, 4), "not a readable section");
        assert!(!pe.is_readable(u32::MAX, 2));
        assert!(pe.is_readable(0x3c, 4), "headers");
    }

    #[test]
    fn foreign_or_truncated_headers_are_refused() {
        let good = pe_header();
        assert!(parse_pe(&good[..0x100]).is_none(), "section table cut off");
        let mut bad = good.clone();
        bad[0] = b'X';
        assert!(parse_pe(&bad).is_none());
        let mut arm = good.clone();
        arm[0x84..0x86].copy_from_slice(&0xaa64_u16.to_le_bytes());
        assert!(parse_pe(&arm).is_none(), "not x64");
        let mut pe32 = good.clone();
        pe32[0x98..0x9a].copy_from_slice(&0x10b_u16.to_le_bytes());
        assert!(parse_pe(&pe32).is_none(), "PE32");
        let mut far = good;
        far[0x3c..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
        assert!(parse_pe(&far).is_none());
        assert!(parse_pe(&[]).is_none());
    }

    /// A PE32+ header with its NT headers at `nt` and `sections` readable sections.
    fn wide_pe(nt: usize, sections: u16) -> Vec<u8> {
        let table = nt + 24 + 240;
        let mut bytes = vec![0_u8; table + usize::from(sections) * 40];
        let len = u32::try_from(bytes.len()).unwrap();
        bytes[0..2].copy_from_slice(b"MZ");
        bytes[0x3c..0x40].copy_from_slice(&u32::try_from(nt).unwrap().to_le_bytes());
        bytes[nt..nt + 4].copy_from_slice(b"PE\0\0");
        let file = nt + 4;
        bytes[file..file + 2].copy_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
        bytes[file + 2..file + 4].copy_from_slice(&sections.to_le_bytes());
        bytes[file + 16..file + 18].copy_from_slice(&240_u16.to_le_bytes());
        let opt = file + 20;
        bytes[opt..opt + 2].copy_from_slice(&IMAGE_NT_OPTIONAL_HDR64_MAGIC.to_le_bytes());
        bytes[opt + 56..opt + 60].copy_from_slice(&0x0100_0000_u32.to_le_bytes());
        bytes[opt + 60..opt + 64].copy_from_slice(&len.to_le_bytes());
        bytes[opt + 108..opt + 112].copy_from_slice(&16_u32.to_le_bytes());
        for index in 0..usize::from(sections) {
            let at = table + index * 40;
            let address = u32::try_from(index + 1).unwrap() * 0x1000;
            bytes[at + 8..at + 12].copy_from_slice(&0x1000_u32.to_le_bytes());
            bytes[at + 12..at + 16].copy_from_slice(&address.to_le_bytes());
            bytes[at + 36..at + 40].copy_from_slice(&0x4000_0040_u32.to_le_bytes());
        }
        bytes
    }

    /// Read the headers in `bytes` through [`read_pe`], with reads cut at `readable` bytes.
    /// Returns the image and the reads made.
    fn read_headers(bytes: &[u8], readable: usize) -> (Option<PeImage>, usize) {
        let mut reads = 0;
        let pe = read_pe(|out| {
            reads += 1;
            let len = out.len().min(bytes.len()).min(readable);
            out[..len].copy_from_slice(&bytes[..len]);
            len
        });
        (pe, reads)
    }

    #[test]
    fn section_tables_past_the_first_page_are_read_whole() {
        // 96 sections: the table runs from 0x188 to 0x1088, past the first page.
        let bytes = wide_pe(0x80, 96);
        assert_eq!(bytes.len(), 0x1088);
        assert!(
            parse_pe(&bytes[..FIRST_HEADER_BYTES]).is_none(),
            "one page is not enough"
        );
        let (pe, reads) = read_headers(&bytes, usize::MAX);
        let pe = pe.unwrap();
        assert_eq!(reads, 2, "the first page, then the whole table");
        assert_eq!(pe.readable.len(), 97);
        assert_eq!(pe.readable[96], (0x60000, 0x61000));
        assert_eq!(pe.readable[0], (0, 0x1088));
        // A header that fits the first page takes one read.
        let (pe, reads) = read_headers(&wide_pe(0x80, 2), usize::MAX);
        assert_eq!((pe.unwrap().readable.len(), reads), (3, 1));
        // NT headers past the first page: one more read to reach them.
        let (pe, reads) = read_headers(&wide_pe(0x1100, 2), usize::MAX);
        assert_eq!((pe.unwrap().readable.len(), reads), (3, 3));
        // A table that cannot be read whole, or one larger than any real image's, is refused.
        assert!(read_headers(&bytes, 0x1000).0.is_none());
        assert!(read_headers(&bytes, 0x1087).0.is_none());
        let (pe, reads) = read_headers(&wide_pe(0x80, u16::MAX), usize::MAX);
        assert!(pe.is_none());
        assert_eq!(reads, 1);
        // Not an image, and e_lfanew far past the end.
        assert!(read_headers(&[0; 64], usize::MAX).0.is_none());
        let mut far = wide_pe(0x80, 2);
        far[0x3c..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
        assert!(read_headers(&far, usize::MAX).0.is_none());
    }
}