hereticus-cli 0.2.1

Command line tool to compare functions between two binaries
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
//! Command line front end for `hereticus`.
//!
//! The library holds the analysis. This binary reads arguments, prints
//! results, and chooses an exit status.

mod formats;
mod functions;
mod tui;

/// The allocator of musl, the default target, serves the threads of the
/// matcher one at a time. Measured with this one in its place, the CLI on
/// two OpenWrt kernels took 30.0 seconds, not 34.8; the kernel test of
/// `tests/truth_kernels.rs` 68 seconds, not 9.6 minutes; and `--ubuntu` of
/// the research bench 81 seconds, not 27 minutes.
#[global_allocator]
static ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc;

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, ValueEnum};
use console::Term;
use hereticus::address::Contents;
use hereticus::matching::{
    Changed, Confidence, Diff, DiffLine, EditKind, EditKinds, Edits, Match, NearMiss, Options,
    PairedLabels, Phase, Progress, UseNames, View, diff_reporting, instruction_diff_in,
};
use hereticus::obj::{Binary, Isa};
use hereticus::raw::{check_base, suggest_base};
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
use tabled::settings::object::{Columns, Rows};
use tabled::settings::style::HorizontalLine;
use tabled::settings::{Alignment, Color, Style};
use tabled::{Table, Tabled};

/// Compare two binaries and report the functions that changed.
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// The earlier binary, or with `--functions` the one binary to list.
    before: PathBuf,

    /// The later binary.
    #[arg(required_unless_present = "functions")]
    after: Option<PathBuf>,

    /// Report every function, not only the ones that changed.
    #[arg(short, long)]
    all: bool,

    /// Show the instruction-level diff of one function, then stop.
    ///
    /// Give a name, or `sub_<hex>` for a function the binary did not name. The
    /// function is looked up in the earlier binary and diffed against whatever
    /// it was matched to in the later one.
    #[arg(long, value_name = "FUNCTION", conflicts_with = "diff_all")]
    diff: Option<String>,

    /// Show the instruction-level diff of every changed function, then stop.
    ///
    /// The functions are the ones the report would list, in its order, and
    /// `--all`, `--show-retouched`, `--show-data` and `--sort` choose them as
    /// they do there. Both binaries are read once, which `--diff` for each
    /// function in turn would repeat.
    #[arg(long)]
    diff_all: bool,

    /// Browse the report in the terminal, and change its order, its filters
    /// and the diff it shows without a second run.
    #[arg(long, conflicts_with_all = ["diff", "diff_all", "format", "exit_code"])]
    tui: bool,

    /// List the functions of one binary, then stop.
    ///
    /// Each line gives the address, the size, the instruction set and whether
    /// the function holds code or data. With `--format json`, another tool,
    /// such as a Ghidra script, can make a function at each address.
    #[arg(
        long,
        conflicts_with_all = ["after", "diff", "diff_all", "tui", "exit_code"]
    )]
    functions: bool,

    /// How `--diff`, `--diff-all` and `--tui` show each instruction.
    #[arg(long, value_enum, default_value_t = ViewName::Asm)]
    view: ViewName,

    /// Ignore symbol names, as though both binaries were stripped.
    ///
    /// Useful to see what `hereticus` finds from the code alone.
    #[arg(long)]
    ignore_names: bool,

    /// List functions that differ in nothing but a constant.
    ///
    /// A function whose shape is identical and whose instruction counts are
    /// all zero changed only a stored value. These outnumber the real edits on
    /// a whole kernel, so they are hidden by default.
    #[arg(long)]
    show_retouched: bool,

    /// List regions that look like data rather than code.
    ///
    /// A raw image holds tables and zero fill after its code, and a scan
    /// reads them as long functions. Every release changes thousands of
    /// their words, so they are hidden by default.
    #[arg(long)]
    show_data: bool,

    /// Lowest similarity that still counts as a match, from 0.0 to 1.0.
    #[arg(long, default_value_t = 0.65, value_parser = parse_threshold)]
    threshold: f64,

    /// Exit with a failure status when anything changed.
    ///
    /// For use as a build gate.
    #[arg(long)]
    exit_code: bool,

    /// Lowest score at which an unmatched function names its closest
    /// candidate, from 0.0 to 1.0.
    ///
    /// A function that no stage could pair still has a nearest neighbour.
    /// Naming it says whether the function was removed or only compiled
    /// differently. Raise this to hide weak guesses, lower it to see them all.
    #[arg(long, default_value_t = 0.25, value_parser = parse_threshold)]
    near_miss: f64,

    /// Read the inputs as raw code with no container format.
    ///
    /// For a firmware image dumped from flash, which has no ELF header. Needs
    /// `--base`, because nothing in the file says where it loads.
    #[arg(long)]
    raw: bool,

    /// Address a raw image loads at, for example `0x08000000`.
    ///
    /// Required with `--raw`. Branch targets and reported addresses are all
    /// relative to this, so a wrong value produces a report against the wrong
    /// addresses. Without it, the tool stops, and for MIPS it names the base
    /// that the calls in the image show.
    #[arg(long, value_parser = parse_address, requires = "raw")]
    base: Option<u64>,

    /// Take one part out of each firmware image before reading it raw.
    ///
    /// Reads the containers OpenWrt builds: a zImage, alone or in a FIT
    /// image or a sysupgrade tar, a uImage, an ELF lzma-loader and a TP-Link
    /// v2 image. `stub` is the decompressor that runs first, and `kernel`
    /// the kernel it holds, decompressed. Where the container says where the
    /// part loads, that is the base unless `--base` gives one.
    #[arg(long, value_enum, requires = "raw")]
    unpack: Option<PartName>,

    /// Architecture of a raw image.
    #[arg(long, value_enum, default_value_t = ArchName::Arm32, requires = "raw")]
    arch: ArchName,

    /// How to print the result.
    #[arg(long, value_enum, default_value_t = Format::Text)]
    format: Format,

    /// How to order the changed functions.
    ///
    /// The default puts the most instructions added first. A security fix
    /// adds a check, so it rises above the many functions that changed only
    /// a value or a text. Measured on four Apple CVE fixes, this put each fix
    /// in the top 19 rows, where `confidence` put each near the bottom.
    /// Above them all goes a function that turned a call into its bounded
    /// form, as `strcmp` into `strncmp`, a fix that adds almost nothing.
    #[arg(long, value_enum, default_value_t = Sort::Added, verbatim_doc_comment)]
    sort: Sort,

    /// When to show a progress bar.
    ///
    /// The bar goes to standard error, so it never mixes with the report.
    #[arg(long, value_enum, default_value_t = When::Auto, verbatim_doc_comment)]
    progress: When,

    /// When to color the report.
    ///
    /// Color goes to standard output with the report, so it is off by default
    /// unless standard output is a terminal. A redirected report stays plain
    /// text that another tool can read.
    #[arg(long, value_enum, default_value_t = When::Auto, verbatim_doc_comment)]
    color: When,
}

/// Whether to show a display that only a terminal can use.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum When {
    /// Show it when standard error is a terminal.
    Auto,
    /// Show it even when standard error is redirected.
    Always,
    /// Never show it.
    Never,
}

/// The architectures a raw image can be read as.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum PartName {
    /// The decompressor that runs first.
    Stub,
    /// The kernel, decompressed.
    Kernel,
}

/// Take the asked part out of a firmware image, with where it loads if the
/// container says.
fn unpack_part(
    bytes: Vec<u8>,
    part: Option<PartName>,
    path: &Path,
) -> Result<(Vec<u8>, Option<u64>), String> {
    let Some(part) = part else { return Ok((bytes, None)) };
    let unpacked = hereticus::unpack::unpack(&bytes)
        .map_err(|error| format!("cannot unpack {}: {error}", path.display()))?;
    let found = match part {
        PartName::Stub => unpacked
            .stub
            .ok_or_else(|| format!("{} holds no stub, only a kernel", path.display()))?,
        PartName::Kernel => unpacked.kernel,
    };
    Ok((found.bytes, found.load))
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum ArchName {
    /// ARM32, little endian, A32 instructions.
    Arm32,
    /// ARM32, little endian, Thumb-2 instructions, as Cortex-M firmware is.
    Thumb2,
    /// ARMv8-A, 64-bit, little endian.
    Aarch64,
    /// MIPS32, little endian.
    Mips32,
    /// MIPS32, big endian, as most shipped firmware is.
    Mips32Be,
    /// MIPS16e, little endian.
    Mips16,
    /// MIPS16e, big endian.
    Mips16Be,
    /// x86-64.
    #[value(name = "x86-64")]
    X86_64,
    /// 32-bit x86.
    X86,
}

impl From<ArchName> for Isa {
    fn from(name: ArchName) -> Self {
        match name {
            ArchName::Arm32 => Self::Arm32,
            ArchName::Thumb2 => Self::Thumb2,
            ArchName::Aarch64 => Self::Aarch64,
            ArchName::Mips32 => Self::Mips32,
            ArchName::Mips32Be => Self::Mips32Be,
            ArchName::Mips16 => Self::Mips16,
            ArchName::Mips16Be => Self::Mips16Be,
            ArchName::X86_64 => Self::X86_64,
            ArchName::X86 => Self::X86,
        }
    }
}

/// Read a load address, in hex with `0x` or in decimal.
fn parse_address(text: &str) -> Result<u64, String> {
    let text = text.trim();
    let parsed = match text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
        Some(hex) => u64::from_str_radix(hex, 16),
        None => text.parse::<u64>(),
    };
    parsed.map_err(|_| format!("`{text}` is not an address"))
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum Format {
    /// A table for a person to read.
    Text,
    /// One line per function, for a script to read.
    Compact,
    /// A markdown table, to paste into a document.
    Markdown,
    /// One JSON object, for another tool to read.
    Json,
}

/// How a diff shows each instruction.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum ViewName {
    /// As the decoder prints it.
    Asm,
    /// As the IL reads it, one statement each, the same on every
    /// architecture, as `w0 = w1 + 0x10` and `if (w2 u> 0x3f) goto $+0x40`.
    Il,
}

impl From<ViewName> for View {
    fn from(name: ViewName) -> Self {
        match name {
            ViewName::Asm => Self::Assembly,
            ViewName::Il => Self::Il,
        }
    }
}

/// How to order the changed functions in the report.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum Sort {
    /// Strongest match first, then closest score.
    Confidence,
    /// Most instructions added first, with a check before an early exit
    /// as five more, after the functions that turned a call into its
    /// bounded form. The default.
    Added,
    /// Most instructions removed first.
    Removed,
    /// Most instructions rewritten first.
    Modified,
    /// Most instructions added first, where an addition that few other
    /// functions share weighs more. A fix adds its own code, while another
    /// compiler or flag adds the same code to many functions.
    Rare,
}

impl Sort {
    /// The measure of a pair this order ranks by, if any.
    ///
    /// `Confidence` ranks by no measure, so it returns nothing and the report
    /// keeps the order the library gave it.
    fn key_of(self, pair: &Match) -> Option<f64> {
        match self {
            Self::Confidence => None,
            Self::Added => Some(pair.edits.added as f64 + early_exit_weight(pair)),
            Self::Removed => Some(pair.edits.removed as f64),
            Self::Modified => Some(pair.edits.edited as f64),
            Self::Rare => Some(pair.rarity),
        }
    }

    /// The order after this one, to step through them all with one key.
    fn next(self) -> Self {
        match self {
            Self::Added => Self::Removed,
            Self::Removed => Self::Modified,
            Self::Modified => Self::Rare,
            Self::Rare => Self::Confidence,
            Self::Confidence => Self::Added,
        }
    }

    /// The name `--sort` takes for this order.
    fn name(self) -> &'static str {
        match self {
            Self::Confidence => "confidence",
            Self::Added => "added",
            Self::Removed => "removed",
            Self::Modified => "modified",
            Self::Rare => "rare",
        }
    }
}

/// Reject a threshold outside the range a similarity score can take.
fn parse_threshold(text: &str) -> Result<f64, String> {
    let value: f64 = text.parse().map_err(|_| format!("`{text}` is not a number"))?;
    if (0.0..=1.0).contains(&value) {
        Ok(value)
    } else {
        Err(format!("threshold must be between 0.0 and 1.0, but is {value}"))
    }
}

/// A progress bar on standard error, one phase at a time.
///
/// The library reports steps; this draws them. Keeping the bar on standard
/// error leaves standard output holding only the report, so a pipe still works
/// while a person still sees the tool is alive.
struct Bar {
    bar: ProgressBar,
}

impl Bar {
    fn new(when: When) -> Self {
        // A hidden bar still accepts every call, so the reporting code needs no
        // test for whether anything is drawn. `stderr` hides itself when
        // standard error is not a terminal, which is the behavior `Auto` wants.
        let target = match when {
            When::Auto => ProgressDrawTarget::stderr(),
            // `stderr` draws nothing when standard error is redirected, which
            // is what `Auto` wants and what `Always` must override. A
            // `TermLike` target skips that test, so the bar is written whatever
            // standard error happens to be.
            When::Always => ProgressDrawTarget::term_like(Box::new(Term::stderr())),
            When::Never => ProgressDrawTarget::hidden(),
        };

        Self { bar: ProgressBar::with_draw_target(None, target) }
    }
}

impl Progress for Bar {
    fn start(&self, phase: Phase, total: usize) {
        self.bar.reset();
        self.bar.set_length(total as u64);
        self.bar.set_message(phase.label());
        self.bar.set_style(
            ProgressStyle::with_template("{msg:26} [{bar:32}] {pos}/{len} {elapsed_precise}")
                .expect("the template is a constant")
                .progress_chars("=> "),
        );
    }

    fn advance(&self, steps: usize) {
        self.bar.inc(steps as u64);
    }

    fn finish(&self) {
        // Clear rather than leave the bar behind: six finished bars above a
        // report is noise, and the report is what a reader came for.
        self.bar.finish_and_clear();
    }
}

fn main() -> ExitCode {
    end_quietly_on_a_closed_pipe();
    let args = Args::parse();

    match run(&args) {
        Ok(changed) => {
            // A build gate wants a failure status when something changed.
            if args.exit_code && changed { ExitCode::from(1) } else { ExitCode::SUCCESS }
        }
        Err(error) => {
            eprintln!("hereticus: {error}");
            ExitCode::from(2)
        }
    }
}

/// Let a closed pipe end the tool, as it ends other Unix tools.
///
/// Rust ignores `SIGPIPE`, so each write to a pipe that the reader closed
/// fails, and `println!` panics: `hereticus --functions lib.so | head`
/// printed a panic after the first lines.
fn end_quietly_on_a_closed_pipe() {
    #[cfg(unix)]
    // SAFETY: no other thread runs yet, and the default action for
    // `SIGPIPE` needs no handler.
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
}

/// Compare the two binaries and print the result.
///
/// Returns whether anything changed.
fn run(args: &Args) -> Result<bool, String> {
    // Fail before the comparison, which can take minutes.
    if args.tui && !Term::stdout().is_term() {
        return Err("--tui needs a terminal on standard output".to_string());
    }
    if args.functions {
        let binary = read_one(args, &args.before)?;
        functions::print_functions(&binary, args.format);
        return Ok(false);
    }
    let after_path = args.after.as_deref().ok_or("needs a later binary to compare with")?;
    let (before_bytes, load) = unpack_part(read_file(&args.before)?, args.unpack, &args.before)?;
    let (after_bytes, _) = unpack_part(read_file(after_path)?, args.unpack, after_path)?;
    let before = read_binary(args, &before_bytes, load, &args.before, BaseCheck::Report)?;
    // Comparing a file with itself is a normal way to inspect one image,
    // and saying the same thing twice about it helps nobody.
    let after_check = if after_path == args.before { BaseCheck::Skip } else { BaseCheck::Report };
    let after = read_binary(args, &after_bytes, load, after_path, after_check)?;
    warn_if_raw(args);

    if before.isa != after.isa {
        return Err(format!(
            "the two binaries are for different architectures: {:?} and {:?}",
            before.isa, after.isa
        ));
    }

    let options = Options {
        threshold: args.threshold,
        use_names: if args.ignore_names { UseNames::No } else { UseNames::Yes },
    };
    let diff = diff_reporting(&before, &after, options, &Bar::new(args.progress));

    // `--diff` asks about one function, so it answers and stops rather than
    // printing the whole report.
    if let Some(wanted) = &args.diff {
        let paint = Paint::resolve(args.color);
        return print_one_diff(&diff, &before, &after, wanted, args.view.into(), paint)
            .map(|()| false);
    }
    if args.tui {
        let file_name = |path: &Path| {
            path.file_name().map_or_else(
                || path.display().to_string(),
                |name| name.to_string_lossy().into_owned(),
            )
        };
        let start = tui::Start {
            files: [file_name(&args.before), file_name(after_path)],
            sort: args.sort,
            view: args.view.into(),
            scope: if args.all { tui::Scope::All } else { tui::Scope::Changed },
            hidden: Hidden::from_args(args),
            near_miss_floor: args.near_miss,
        };
        return tui::run(&diff, &before, &after, start).map(|()| false);
    }
    if args.diff_all {
        let mut shown: Vec<&Match> = diff
            .matched
            .iter()
            .filter(|pair| args.all || is_interesting(pair, Hidden::from_args(args)))
            .collect();
        sort_shown(&mut shown, args.sort);
        let paint = Paint::resolve(args.color);
        let paired = diff.paired_labels(&before, &after);
        for (index, pair) in shown.iter().enumerate() {
            if index > 0 {
                println!();
            }
            print_pair_diff(pair, &paired, &before, &after, args.view.into(), paint);
        }
        return Ok(!shown.is_empty());
    }

    match args.format {
        Format::Text => {
            let view = TextView {
                show_all: args.all,
                near_miss_floor: args.near_miss,
                hidden: Hidden::from_args(args),
                paint: Paint::resolve(args.color),
                sort: args.sort,
            };
            print_text(&diff, &before, &after, view)
        }
        Format::Compact => {
            print_compact(&diff, &before, &after, args.all, Hidden::from_args(args), args.sort)
        }
        Format::Markdown => formats::print_markdown(
            &diff,
            &before,
            &after,
            args.all,
            Hidden::from_args(args),
            args.sort,
            args.near_miss,
        ),
        Format::Json => formats::print_json(
            &diff,
            &before,
            &after,
            args.all,
            Hidden::from_args(args),
            args.sort,
        ),
    }

    Ok(diff.changed().count() > 0 || !diff.removed.is_empty() || !diff.added.is_empty())
}

/// Whether to warn when the load address looks wrong for an image.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum BaseCheck {
    Report,
    Skip,
}

/// Say once that the functions of a raw image are only approximate.
fn warn_if_raw(args: &Args) {
    if args.raw {
        eprintln!(
            "hereticus: a raw image has no exception index, so function boundaries \
             are recovered from the code and are approximate"
        );
    }
}

/// Read one binary for `--functions`, unpacked and raw as the arguments say.
fn read_one(args: &Args, path: &Path) -> Result<Binary, String> {
    let (bytes, load) = unpack_part(read_file(path)?, args.unpack, path)?;
    let binary = read_binary(args, &bytes, load, path, BaseCheck::Report)?;
    warn_if_raw(args);
    Ok(binary)
}

/// Read `bytes` as a binary, or as a raw image at the base the arguments or
/// its container, `load`, give.
fn read_binary(
    args: &Args,
    bytes: &[u8],
    load: Option<u64>,
    path: &Path,
    check: BaseCheck,
) -> Result<Binary, String> {
    if !args.raw {
        return parse(bytes, path);
    }
    let isa: Isa = args.arch.into();
    let base = args.base.or(load).ok_or_else(|| missing_base(bytes, isa))?;
    if check == BaseCheck::Report {
        check_and_report_base(bytes, base, isa, path);
    }
    parse_raw(bytes, base, isa, path)
}

fn read_file(path: &Path) -> Result<Vec<u8>, String> {
    std::fs::read(path).map_err(|error| format!("cannot read {}: {error}", path.display()))
}

fn parse(data: &[u8], path: &Path) -> Result<Binary, String> {
    Binary::parse(data).map_err(|error| format!("cannot read {}: {error}", path.display()))
}

fn parse_raw(data: &[u8], base: u64, isa: Isa, path: &Path) -> Result<Binary, String> {
    Binary::parse_raw(data, base, isa)
        .map_err(|error| format!("cannot read {}: {error}", path.display()))
}

/// Say that `--raw` needs `--base`, and suggest one when the image shows it.
///
/// The suggestion is not used in place of `--base`. It can be wrong, and a
/// wrong base gives a report against the wrong addresses with no other sign.
fn missing_base(data: &[u8], isa: Isa) -> String {
    let needed = "--raw needs --base, because a raw image does not say where it loads";
    match suggest_base(data, isa.arch()) {
        Some(base) => format!("{needed}. Its calls show that it loads at --base {base:#x}"),
        None => needed.to_string(),
    }
}

/// Warn when the given load address looks wrong for an image.
///
/// A wrong base does not stop anything: the code still decodes and every
/// branch still resolves, because a relative branch moves with the base it is
/// read at. Only the reported addresses are wrong, and silently so. This is
/// the one chance to notice.
fn check_and_report_base(data: &[u8], base: u64, isa: Isa, path: &Path) {
    let fit = check_base(data, base, isa.arch());
    if fit.is_suspect() {
        eprintln!("hereticus: {} may not load at {base:#x}: {fit}", path.display());
    }
}

/// Name a function, falling back to its address when it has no symbol.
fn name_of(binary: &Binary, index: usize) -> String {
    binary.functions[index].label()
}

/// The name `--view` takes for a view.
fn name_of_view(view: View) -> &'static str {
    match view {
        View::Assembly => "asm",
        View::Il => "il",
    }
}

/// Describe what happened to a matched pair.
fn describe(change: Changed) -> &'static str {
    match change {
        Changed::No => "same",
        Changed::Reordered => "reordered",
        Changed::InDetail => "changed values",
        Changed::Data => "changed data",
        Changed::Unreadable => "changed unread",
        Changed::Yes => "changed",
    }
}

/// Render an edit as added, removed and rewritten instructions.
///
/// A dash rather than three zeros where nothing was counted, so the eye finds
/// the functions that did change.
///
/// A function whose constants changed shows a dash, and that is right: no
/// instruction was touched. The `CHANGE` column names what did change, and
/// the two columns answer different questions.
///
/// Each count carries the color of its own kind, not of the row, because the
/// three numbers say three different things. The colors follow a patch: green
/// added, red removed, yellow rewritten. The separators stay plain, so the
/// field still reads as one value.
fn describe_edits(edits: Edits, paint: Paint) -> String {
    if edits.total() == 0 {
        return "-".to_string();
    }

    let added = paint.pick(ADDED_COLOR).colorize(edits.added.to_string());
    let removed = paint.pick(REMOVED_COLOR).colorize(edits.removed.to_string());
    let edited = paint.pick(EDITED_COLOR).colorize(edits.edited.to_string());
    format!("{added}/{removed}/{edited}")
}

/// Name what kind of code an edit touched, most telling kind first.
///
/// Reads as `2 branch, 1 const`. Control flow leads, because a branch that
/// appeared can change what the function does for some input, which a moved
/// load cannot. A dash where nothing was touched, as in the `+/-/~` column.
///
/// This is the one place a changed constant shows inside a larger edit. Once a
/// rewrite is big enough the `CHANGE` column only says `changed`, and the
/// value that moved with it would otherwise not appear at all.
///
/// Plain data instructions are left out. They are the bulk of any rewrite and
/// name nothing a reader can act on, so listing them would crowd out the kinds
/// that do. The `+/-/~` column already reports the size of the edit.
///
/// The names are short so that the column stays narrow. `const` rather than
/// `constant` keeps the common case to one short word.
///
/// The column stays quiet where it would only repeat the `CHANGE` word beside
/// it. `changed values` already says a constant moved and `changed unread`
/// already says the difference is unreadable, so naming that one kind again
/// fills the column on every row of a report and tells the reader nothing. A
/// second kind alongside it is new information, and then the whole list shows.
fn describe_kinds(kinds: EditKinds, change: Changed) -> String {
    let named: Vec<(EditKind, usize)> =
        kinds.present().filter(|(kind, _)| *kind != EditKind::Other).collect();

    if let [(only, _)] = named[..]
        && restates(change, only)
    {
        return "-".to_string();
    }

    let listed: Vec<String> =
        named.iter().map(|(kind, count)| format!("{count} {}", name_of_kind(*kind))).collect();

    if listed.is_empty() { "-".to_string() } else { listed.join(", ") }
}

/// Report whether naming this kind would only repeat the `CHANGE` column.
fn restates(change: Changed, kind: EditKind) -> bool {
    matches!(
        (change, kind),
        (Changed::InDetail, EditKind::Constant) | (Changed::Unreadable, EditKind::Opaque)
    )
}

/// The short name of one kind, for the `TOUCHED` column.
fn name_of_kind(kind: EditKind) -> &'static str {
    match kind {
        EditKind::Branch => "branch",
        EditKind::Call => "call",
        EditKind::Callee => "callee",
        EditKind::Jump => "jump",
        EditKind::Memory => "mem",
        EditKind::Constant => "const",
        EditKind::Text => "text",
        EditKind::Other => "other",
        EditKind::Opaque => "unread",
    }
}

/// The color of each count in the `+/-/~` column.
const ADDED_COLOR: Color = Color::FG_GREEN;
const REMOVED_COLOR: Color = Color::FG_RED;
const EDITED_COLOR: Color = Color::FG_YELLOW;

/// Describe why two functions were paired.
fn describe_confidence(confidence: Confidence) -> &'static str {
    match confidence {
        Confidence::IdenticalCode => "identical bytes",
        Confidence::IdenticalShape => "identical shape",
        Confidence::SameName => "same name",
        Confidence::SameRowText => "twin, by the text in its row",
        Confidence::TwinInOrder => "twin, in order",
        Confidence::SameTable => "same slot of a table",
        Confidence::SameImport => "same import",
        Confidence::SameReferences => "same references",
        Confidence::SameCallers => "same callers",
        Confidence::SameLayout => "same place",
        Confidence::Similar => "similar",
    }
}

/// Report whether a pair should appear when only changes are wanted.
///
/// A pair that scores a perfect 1.00 and touched no instruction has nothing a
/// reader can act on: the shape is identical and only a constant moved. On a
/// whole kernel these crowd out the real edits, so they are hidden unless
/// asked for. Measured on a whole-kernel pair, hiding them drops
/// the report from 8744 rows to 6375 while keeping every function that added,
/// removed or rewrote an instruction.
fn is_interesting(pair: &Match, hidden: Hidden) -> bool {
    match pair.changed {
        Changed::No => false,
        Changed::Data => hidden.data == DataRegions::Show,
        _ => hidden.retouched == Retouched::Show || !is_retouched(pair),
    }
}

/// Report whether a function that went or came should appear.
///
/// A raw image holds its headers and read-only data among its code, and they
/// move when the code before them grows. Data goes and comes as code does, so
/// it is hidden as a changed data region is.
fn is_shown_unmatched(contents: Contents, hidden: Hidden) -> bool {
    contents == Contents::Code || hidden.data == DataRegions::Show
}

/// The word that says a function went, or came, for what it holds.
fn unmatched_word(word: &'static str, contents: Contents) -> String {
    match contents {
        Contents::Code => word.to_string(),
        Contents::Data => format!("{word} data"),
    }
}

/// Report whether a pair differs in nothing but its constants.
///
/// The score and the edit counts must both be clean. A function that rewrote
/// an instruction is a real edit whatever it scores, and one that scores below
/// a perfect match differs in shape even if the counts round to nothing.
fn is_retouched(pair: &Match) -> bool {
    pair.edits.total() == 0 && pair.kinds.callees == 0 && pair.kinds.texts == 0 && pair.score >= 1.0
}

/// Which quiet changes to list.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct Hidden {
    retouched: Retouched,
    data: DataRegions,
}

impl Hidden {
    /// `--all` asks for every function, so it lists every quiet change too.
    fn from_args(args: &Args) -> Self {
        Self {
            retouched: Retouched::from(args.show_retouched || args.all),
            data: DataRegions::from(args.show_data || args.all),
        }
    }
}

/// Whether to list pairs that look like data.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum DataRegions {
    Show,
    Hide,
}

impl From<bool> for DataRegions {
    fn from(show: bool) -> Self {
        if show { Self::Show } else { Self::Hide }
    }
}

/// Whether to list pairs that only differ in a constant.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Retouched {
    Show,
    Hide,
}

impl From<bool> for Retouched {
    fn from(show: bool) -> Self {
        if show { Self::Show } else { Self::Hide }
    }
}

/// Whether the report is colored.
///
/// Resolved once, before anything prints, so every line agrees.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Paint {
    On,
    Off,
}

impl Paint {
    /// Decide from the flag and, for `Auto`, from what standard output is.
    ///
    /// Color belongs to a person reading a terminal. A report sent to a file
    /// or a pipe must stay plain, or the escape codes become part of whatever
    /// reads it next.
    fn resolve(when: When) -> Self {
        match when {
            When::Always => Self::On,
            When::Never => Self::Off,
            When::Auto => {
                if console::colors_enabled() && Term::stdout().is_term() {
                    Self::On
                } else {
                    Self::Off
                }
            }
        }
    }

    /// Give a color, or an empty one that prints no escape codes.
    fn pick(self, color: Color) -> Color {
        match self {
            Self::On => color,
            Self::Off => Color::empty(),
        }
    }
}

/// Where the change sits in [`Row`], which is the one column to color.
const CHANGE_COLUMN: usize = 1;

/// Where the score sits in [`Row`], which is the one column to align right.
const SCORE_COLUMN: usize = 2;

/// One line of the text report.
///
/// The column headings are short because the table sizes itself to the widest
/// cell, and a long heading would widen a column that holds nothing wide.
#[derive(Tabled)]
struct Row {
    #[tabled(rename = "FUNCTION")]
    function: String,
    #[tabled(rename = "CHANGE")]
    change: &'static str,
    #[tabled(rename = "SCORE")]
    score: String,
    /// Added, removed and rewritten instructions.
    #[tabled(rename = "+/-/~")]
    edits: String,
    /// What kind of code the edit touched.
    #[tabled(rename = "TOUCHED")]
    kinds: String,
    #[tabled(rename = "MATCHED BY")]
    matched_by: &'static str,
}

/// Color a row by what happened to the function.
///
/// The severity runs from an unread difference, through a changed constant, to
/// a rewritten body. A reader scanning a long report finds the real edits by
/// color before reading a word.
fn color_of(change: Changed) -> Color {
    match change {
        Changed::Yes => Color::FG_RED,
        Changed::Unreadable => Color::FG_MAGENTA,
        Changed::InDetail => Color::FG_YELLOW,
        Changed::Reordered => Color::FG_CYAN,
        Changed::Data => Color::FG_BLUE,
        Changed::No => Color::FG_GREEN,
    }
}

/// Find a function in a binary by the name the report would print for it.
///
/// A named function matches its name. A stripped one matches `sub_<hex>`, the
/// same label the report shows, so a reader can copy a name straight out of the
/// table.
fn find_function(binary: &Binary, wanted: &str) -> Option<usize> {
    let by_address = wanted
        .strip_prefix("sub_")
        .and_then(|hex| u64::from_str_radix(hex, 16).ok())
        .and_then(|address| binary.functions.iter().position(|f| f.address == address));

    by_address
        .or_else(|| binary.functions.iter().position(|f| !f.name.is_empty() && f.name == wanted))
}

/// Print the instruction-level diff of one function.
///
/// The function is looked up in the earlier binary. If it was matched, the diff
/// runs against its counterpart; if it was removed, there is nothing to diff
/// against and the tool says so.
fn print_one_diff(
    diff: &Diff,
    before: &Binary,
    after: &Binary,
    wanted: &str,
    view: View,
    paint: Paint,
) -> Result<(), String> {
    let index = find_function(before, wanted)
        .ok_or_else(|| format!("no function `{wanted}` in the earlier binary"))?;

    let pair = diff.matched.iter().find(|pair| pair.before == index).ok_or_else(|| {
        // A removed function has no counterpart, so say that rather than print
        // an empty diff.
        match diff.near_miss(index).and_then(|miss| miss.best) {
            Some(best) => format!(
                "`{wanted}` was not matched; its closest candidate is {}",
                name_of(after, best)
            ),
            None => format!("`{wanted}` was not matched to anything in the later binary"),
        }
    })?;

    print_pair_diff(pair, &diff.paired_labels(before, after), before, after, view, paint);
    Ok(())
}

/// Print the name of a pair, then its instruction-level diff.
fn print_pair_diff(
    pair: &Match,
    paired: &PairedLabels,
    before: &Binary,
    after: &Binary,
    view: View,
    paint: Paint,
) {
    let before_name = name_of(before, pair.before);
    let after_name = name_of(after, pair.after);
    if before_name == after_name {
        println!("{before_name}");
    } else {
        println!("{before_name} -> {after_name}");
    }

    let lines = instruction_diff_in(view, Some(paired), before, pair.before, after, pair.after);
    for line in &lines {
        println!("{}", render_diff_line(line, paint));
    }
}

/// Draw one diff line with a leading sign, in the color of its kind.
///
/// The signs follow a patch: a space for an unchanged line, `+` added, `-`
/// removed, `~` for a line kept but retouched. Color repeats the sign so the
/// line reads on a terminal that drops it and on one that keeps it.
fn render_diff_line(line: &DiffLine, paint: Paint) -> String {
    match line {
        DiffLine::Same(text) => format!("  {text}"),
        DiffLine::Added(text) => paint.pick(ADDED_COLOR).colorize(format!("+ {text}")).to_string(),
        DiffLine::Removed(text) => {
            paint.pick(REMOVED_COLOR).colorize(format!("- {text}")).to_string()
        }
        DiffLine::Changed { before, after } => {
            let removed = paint.pick(REMOVED_COLOR).colorize(format!("- {before}"));
            let added = paint.pick(ADDED_COLOR).colorize(format!("+ {after}"));
            format!("{removed}\n{added}")
        }
    }
}

/// Order the shown pairs by the chosen edit count, most first.
///
/// `Confidence` keeps the order the library gave, which is already strongest
/// match first. The count orders put a rescheduled pair last (see
/// [`is_rescheduled`]), and break a tie by the lowest score, so the least
/// certain of an equal-sized edit sits on top, where it wants the most
/// attention. The sort is stable, so pairs that tie on all keep their place.
fn sort_shown(shown: &mut [&Match], sort: Sort) {
    if sort == Sort::Confidence {
        return;
    }

    shown.sort_by(|a, b| rank(a, b, sort));
}

/// Which of two pairs a count order puts first: see [`sort_shown`].
fn rank(a: &Match, b: &Match, sort: Sort) -> core::cmp::Ordering {
    let a_key = sort.key_of(a).unwrap_or(0.0);
    let b_key = sort.key_of(b).unwrap_or(0.0);
    is_rescheduled(a)
        .cmp(&is_rescheduled(b))
        .then_with(|| match sort {
            Sort::Added => bounds_a_call(b).cmp(&bounds_a_call(a)),
            _ => core::cmp::Ordering::Equal,
        })
        .then_with(|| b_key.total_cmp(&a_key))
        .then_with(|| a.score.partial_cmp(&b.score).unwrap_or(core::cmp::Ordering::Equal))
}

/// What a check before an early exit adds to the count of instructions
/// added: as much as five instructions, once for each pair.
///
/// A fix that narrows what a function accepts adds a test and an early
/// return where it fails, as the fix of `luaZ_fill` in Lua does, and adds
/// few instructions. Measured on the backports, this cut the rank sum of
/// the fixes from 2970 to 2489, and on the Ubuntu updates from 304 to 300,
/// with one more first; on the published fixes it moved one fix from row 3
/// to row 5. A larger weight, or more for an edit that removes nothing,
/// lifted Lua further but sank tinyxml2 and more published fixes. See
/// RESEARCH.md, "Checks before an early exit".
fn early_exit_weight(pair: &Match) -> f64 {
    const WEIGHT: f64 = 5.0;
    if pair.early_exits > 0 { WEIGHT } else { 0.0 }
}

/// Report whether a pair turned a call into its bounded form, as `strcmp`
/// into `strncmp`.
///
/// Such a fix adds only the instruction that loads the limit, so a count
/// of the instructions added put the `procd` fix of CVE-2026-30874 on row
/// 18 to 20. Measured on the published fixes, this put it on row 1 for all
/// four builds, and moved no fix of the backports or the Ubuntu updates.
/// See RESEARCH.md, "Calls swapped for their bounded form".
fn bounds_a_call(pair: &Match) -> bool {
    pair.bounded_calls > 0
}

/// Report whether a pair only moved instructions that are not control
/// flow: the shape of a compiler scheduling the same code another way.
///
/// Under LTO, GCC schedules the code of many functions anew in each build:
/// most rows of an arm64 Ubuntu update are such pairs, and one put a
/// libssh fix on row 66. A fix that moves code moves branches or calls,
/// as the fix of CVE-2023-28484 in libxml2 does, so it stays in place.
/// Measured on the Ubuntu updates, this cut the rank sum of the fixes
/// from 342 to 303 and put 2 more in the first five; on the backports it
/// cut it from 3179 to 3035, with the first row and the first five the
/// same. See RESEARCH.md, "The Ubuntu updates, checked again".
fn is_rescheduled(pair: &Match) -> bool {
    pair.changed == Changed::Reordered && !pair.kinds.touches_control_flow()
}

/// How the text report shows a comparison.
#[derive(Copy, Clone, Debug)]
struct TextView {
    /// Show every pair, not only the changed ones.
    show_all: bool,
    /// The lowest score at which an unpaired function names its nearest
    /// neighbour.
    near_miss_floor: f64,
    hidden: Hidden,
    paint: Paint,
    sort: Sort,
}

fn print_text(diff: &Diff, before: &Binary, after: &Binary, view: TextView) {
    let TextView { show_all, near_miss_floor, hidden, paint, sort } = view;
    let mut shown: Vec<&Match> =
        diff.matched.iter().filter(|pair| show_all || is_interesting(pair, hidden)).collect();
    sort_shown(&mut shown, sort);

    if !shown.is_empty() {
        let rows = shown.iter().map(|pair| {
            // A renamed function reads as `old -> new`. The table sizes the
            // column to the widest label, so a rename cannot push it out of
            // line.
            let name = name_of(before, pair.before);
            let renamed = name_of(after, pair.after);
            Row {
                function: if name == renamed { name } else { format!("{name} -> {renamed}") },
                change: describe(pair.changed),
                score: format!("{:.2}", pair.score),
                edits: describe_edits(pair.edits, paint),
                kinds: describe_kinds(pair.kinds, pair.changed),
                matched_by: describe_confidence(pair.confidence),
            }
        });

        let mut table = Table::new(rows);
        table
            // `rounded` draws no line under the heading, so borrow one from
            // `modern_rounded`, which uses the same corner characters.
            .with(
                Style::rounded()
                    .horizontals([(1, HorizontalLine::inherit(Style::modern_rounded()))]),
            )
            .with(Alignment::left())
            // The score is a number, so it reads better against the decimal
            // point than against the left edge.
            .modify(Columns::one(SCORE_COLUMN), Alignment::right())
            .modify(Rows::first(), paint.pick(Color::BOLD));

        // Only the `CHANGE` cell takes the severity color. A whole colored row
        // buries the one word a reader is looking for, and the counts beside it
        // carry colors of their own. Row 0 is the heading, so the pairs start
        // at row 1.
        for (offset, pair) in shown.iter().enumerate() {
            let cell = (offset + 1, CHANGE_COLUMN);
            table.modify(cell, paint.pick(color_of(pair.changed)));
        }

        println!("{table}");
    }

    // Only the status word takes a color, as in the `CHANGE` column. The name
    // beside it stays plain, so the word is what the eye finds.
    for (index, contents) in diff.removed_with_contents() {
        if !is_shown_unmatched(contents, hidden) {
            continue;
        }
        let name = name_of(before, index);
        let gone = paint.pick(REMOVED_COLOR).colorize(unmatched_word("gone", contents));
        let notes = [
            near_miss_note(diff, index, after, near_miss_floor),
            place_note(diff.near_miss(index), after),
        ];
        println!("{name}: {gone}{}", joined_notes(notes));
    }
    for (index, contents) in diff.added_with_contents() {
        if !is_shown_unmatched(contents, hidden) {
            continue;
        }
        let name = name_of(after, index);
        let new = paint.pick(ADDED_COLOR).colorize(unmatched_word("new", contents));
        let notes = [
            added_near_miss_note(diff, index, before, near_miss_floor),
            place_note(diff.added_near_miss(index), before),
        ];
        println!("{name}: {new}{}", joined_notes(notes));
    }

    summarize(diff, hidden);
}

/// Describe the closest candidate for a function that went unmatched.
///
/// A function can go unmatched because it was removed, or because the two
/// builds compiled it too differently to recognize. The score separates those
/// two, and naming the candidate turns a dead end into somewhere to look.
fn near_miss_note(diff: &Diff, index: usize, after: &Binary, floor: f64) -> Option<String> {
    let miss = diff.near_miss(index)?;
    let best = miss.best?;
    if miss.score < floor {
        return None;
    }
    Some(format!("closest {} at {:.2}", name_of(after, best), miss.score))
}

/// Describe the closest candidate for a function that appears to be new.
///
/// The mirror of [`near_miss_note`]: the candidate is on the first binary. A
/// new function with a close candidate is likely one the cascade could not
/// pair, not truly new code, which is the distinction the finding needed.
fn added_near_miss_note(diff: &Diff, index: usize, before: &Binary, floor: f64) -> Option<String> {
    let miss = diff.added_near_miss(index)?;
    let best = miss.best?;
    if miss.score < floor {
        return None;
    }
    Some(format!("closest {} at {:.2}", name_of(before, best), miss.score))
}

/// Name the unpaired function of the other binary that sits in the same
/// place, between the same two pairs.
///
/// A fix that rewrites a function past any score, or splits it in two, leaves
/// a function gone and another new where it was. The place links the two
/// without a claim that they are one. See [`NearMiss::in_place`].
fn place_note(miss: Option<&NearMiss>, other: &Binary) -> Option<String> {
    Some(format!("same place as {}", name_of(other, miss?.in_place?)))
}

/// The notes that are present, each after a comma.
fn joined_notes(notes: impl IntoIterator<Item = Option<String>>) -> String {
    notes.into_iter().flatten().map(|note| format!(", {note}")).collect()
}

/// Print one line per function, with no header or alignment.
fn print_compact(
    diff: &Diff,
    before: &Binary,
    after: &Binary,
    show_all: bool,
    hidden: Hidden,
    sort: Sort,
) {
    let mut shown: Vec<&Match> =
        diff.matched.iter().filter(|pair| show_all || is_interesting(pair, hidden)).collect();
    sort_shown(&mut shown, sort);

    for pair in shown {
        // The edit counts go last so a reader of the first four columns keeps
        // working.
        println!(
            "{}\t{}\t{}\t{:.2}\t{}\t{}\t{}",
            describe(pair.changed),
            name_of(before, pair.before),
            name_of(after, pair.after),
            pair.score,
            pair.edits.added,
            pair.edits.removed,
            pair.edits.edited,
        );
    }
    for (index, contents) in diff.removed_with_contents() {
        if !show_all && !is_shown_unmatched(contents, hidden) {
            continue;
        }
        // The fourth column holds the near-miss score, so a script reading
        // this format finds it where a matched pair keeps its score.
        let miss = diff.near_miss(index);
        let closest =
            miss.and_then(|miss| miss.best).map(|best| name_of(after, best)).unwrap_or_default();
        let score = miss.map_or(0.0, |miss| miss.score);
        let gone = unmatched_word("gone", contents);
        println!("{gone}\t{}\t{closest}\t{score:.2}\t\t\t", name_of(before, index));
    }
    for (index, contents) in diff.added_with_contents() {
        if !show_all && !is_shown_unmatched(contents, hidden) {
            continue;
        }
        // The candidate on the first binary and its score go in the same two
        // columns a removed line uses, so one reader parses both.
        let miss = diff.added_near_miss(index);
        let closest =
            miss.and_then(|miss| miss.best).map(|best| name_of(before, best)).unwrap_or_default();
        let score = miss.map_or(0.0, |miss| miss.score);
        let new = unmatched_word("new", contents);
        println!("{new}\t{closest}\t{}\t{score:.2}\t\t\t", name_of(after, index));
    }
}

fn summarize(diff: &Diff, hidden: Hidden) {
    let lines = summary_lines(diff, hidden);
    // A table or a list comes before the totals, so a blank line parts them.
    if lines.len() > 1 || !nothing_happened(diff) {
        println!();
    }
    for line in lines {
        println!("{line}");
    }
}

/// Report whether nothing changed, went or came.
fn nothing_happened(diff: &Diff) -> bool {
    diff.changed().count() == 0 && diff.removed.is_empty() && diff.added.is_empty()
}

/// The totals of a report, and how many rows it held back, a line each.
fn summary_lines(diff: &Diff, hidden: Hidden) -> Vec<String> {
    let changed = diff.changed().count();
    let same = diff.matched.len() - changed;

    // Say so plainly when there is nothing to report. A bare count after an
    // empty table reads like the tool failed.
    if nothing_happened(diff) {
        return vec![format!("No functions changed. {} matched.", diff.matched.len())];
    }

    // A count that disagrees with the table reads like a bug, so say how many
    // rows were held back and how to see them.
    let hidden_retouched = if hidden.retouched == Retouched::Hide {
        diff.changed().filter(|pair| pair.changed != Changed::Data && is_retouched(pair)).count()
    } else {
        0
    };
    // A data region that went or came is a change too, so it counts here.
    let hidden_data = if hidden.data == DataRegions::Hide {
        let changed = diff.changed().filter(|pair| pair.changed == Changed::Data).count();
        let unmatched = diff.removed_contents.iter().chain(&diff.added_contents);
        changed + unmatched.filter(|&&contents| contents == Contents::Data).count()
    } else {
        0
    };

    let mut lines = vec![format!(
        "{} matched ({same} unchanged, {changed} changed), {} gone, {} new",
        diff.matched.len(),
        diff.removed.len(),
        diff.added.len()
    )];
    if hidden_retouched > 0 {
        lines.push(format!(
            "{hidden_retouched} changed only a constant, hidden. Use --show-retouched to list them."
        ));
    }
    if hidden_data > 0 {
        let regions = if hidden_data == 1 { "region" } else { "regions" };
        lines.push(format!(
            "{hidden_data} data {regions} changed, hidden. Use --show-data to list them."
        ));
    }
    lines
}

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

    #[test]
    fn rejects_a_threshold_outside_its_range() {
        assert!(parse_threshold("-0.1").is_err());
        assert!(parse_threshold("1.5").is_err());
        assert!(parse_threshold("not a number").is_err());
    }

    #[test]
    fn accepts_a_threshold_inside_its_range() {
        assert_eq!(parse_threshold("0.0"), Ok(0.0));
        assert_eq!(parse_threshold("0.65"), Ok(0.65));
        assert_eq!(parse_threshold("1.0"), Ok(1.0));
    }

    #[test]
    fn every_change_has_a_description() {
        for change in [
            Changed::No,
            Changed::Reordered,
            Changed::Data,
            Changed::InDetail,
            Changed::Unreadable,
            Changed::Yes,
        ] {
            assert!(!describe(change).is_empty());
        }
    }

    /// Build a pair with a given edit count and score, for the sort tests.
    fn pair_with(edits: Edits, score: f64) -> Match {
        Match { score, edits, ..edited_pair(Changed::Yes) }
    }

    /// A pair that only moved loads and arithmetic goes after the other
    /// changes, however many it moved; one that moved a branch does not.
    #[test]
    fn a_rescheduled_pair_goes_last() {
        let edits = Edits { added: 40, removed: 40, edited: 0 };
        let rescheduled = Match {
            kinds: EditKinds { memory: 40, ..EditKinds::default() },
            ..pair_with(edits, 1.0)
        };
        let rescheduled = Match { changed: Changed::Reordered, ..rescheduled };
        let moved_branch = Match {
            changed: Changed::Reordered,
            kinds: EditKinds { branches: 1, memory: 39, ..EditKinds::default() },
            ..pair_with(edits, 1.0)
        };
        let small = pair_with(Edits { added: 1, removed: 0, edited: 0 }, 0.9);
        let mut shown = vec![&rescheduled, &small, &moved_branch];

        sort_shown(&mut shown, Sort::Added);
        let order: Vec<_> = shown.iter().map(|pair| pair.kinds).collect();
        assert_eq!(order, [moved_branch.kinds, small.kinds, rescheduled.kinds]);
    }

    /// `--sort modified` puts the most-rewritten function first.
    #[test]
    fn sort_by_modified_ranks_by_rewritten_count() {
        let small = pair_with(Edits { added: 0, removed: 0, edited: 1 }, 0.9);
        let large = pair_with(Edits { added: 0, removed: 0, edited: 9 }, 0.9);
        let mut shown = vec![&small, &large];

        sort_shown(&mut shown, Sort::Modified);
        assert_eq!(shown[0].edits.edited, 9, "the largest edit is first");
    }

    /// Each count order ranks by its own column.
    #[test]
    fn each_sort_ranks_by_its_own_column() {
        let grew = pair_with(Edits { added: 5, removed: 0, edited: 0 }, 0.9);
        let shrank = pair_with(Edits { added: 0, removed: 5, edited: 0 }, 0.9);
        let mut shown = vec![&grew, &shrank];

        sort_shown(&mut shown, Sort::Added);
        assert_eq!(shown[0].edits.added, 5, "added ranks by the + column");

        sort_shown(&mut shown, Sort::Removed);
        assert_eq!(shown[0].edits.removed, 5, "removed ranks by the - column");
    }

    /// A call turned into its bounded form goes first under `added`, and
    /// only there.
    #[test]
    fn a_bounded_call_goes_first_under_added() {
        let large = pair_with(Edits { added: 30, removed: 0, edited: 0 }, 0.9);
        let bounded =
            Match { bounded_calls: 1, ..pair_with(Edits { added: 1, removed: 0, edited: 0 }, 1.0) };
        let mut shown = vec![&large, &bounded];

        sort_shown(&mut shown, Sort::Added);
        assert_eq!(shown[0].bounded_calls, 1, "the bounded call is first");
        sort_shown(&mut shown, Sort::Removed);
        sort_shown(&mut shown, Sort::Rare);
        assert_eq!(shown[0].edits.added, 30, "another order ignores it");
    }

    /// A check before an early exit weighs as five instructions added
    /// under `added`, once for each pair.
    #[test]
    fn a_check_before_an_early_exit_weighs_five_instructions() {
        let larger = pair_with(Edits { added: 6, removed: 0, edited: 0 }, 0.9);
        let checked =
            Match { early_exits: 2, ..pair_with(Edits { added: 2, removed: 0, edited: 0 }, 0.9) };
        let mut shown = vec![&larger, &checked];
        sort_shown(&mut shown, Sort::Added);
        assert_eq!(shown[0].edits.added, 2, "2 + 5 is more than 6");

        let much_larger = pair_with(Edits { added: 8, removed: 0, edited: 0 }, 0.9);
        let mut shown = vec![&checked, &much_larger];
        sort_shown(&mut shown, Sort::Added);
        assert_eq!(shown[0].edits.added, 8, "two checks weigh as one");
    }

    /// `--sort rare` ranks by the weighted additions, not by their count.
    #[test]
    fn sort_by_rare_ranks_by_rarity() {
        let common =
            Match { rarity: 6.0, ..pair_with(Edits { added: 6, removed: 0, edited: 0 }, 0.9) };
        let rare =
            Match { rarity: 9.5, ..pair_with(Edits { added: 4, removed: 0, edited: 0 }, 0.9) };
        let mut shown = vec![&common, &rare];

        sort_shown(&mut shown, Sort::Rare);
        assert_eq!(shown[0].edits.added, 4, "the rarer addition is first");
        sort_shown(&mut shown, Sort::Added);
        assert_eq!(shown[0].edits.added, 6, "added still ranks by the count");
    }

    /// An equal-sized edit is broken by the lowest score, which wants the most
    /// attention.
    #[test]
    fn an_equal_edit_puts_the_least_certain_first() {
        let sure = pair_with(Edits { added: 0, removed: 0, edited: 3 }, 0.95);
        let unsure = pair_with(Edits { added: 0, removed: 0, edited: 3 }, 0.60);
        let mut shown = vec![&sure, &unsure];

        sort_shown(&mut shown, Sort::Modified);
        assert_eq!(shown[0].score, 0.60, "the least certain of an equal edit is first");
    }

    /// The default order leaves the pairs as the library gave them.
    #[test]
    fn sort_by_confidence_keeps_the_order() {
        let first = pair_with(Edits { added: 0, removed: 0, edited: 1 }, 0.9);
        let second = pair_with(Edits { added: 0, removed: 0, edited: 9 }, 0.9);
        let mut shown = vec![&first, &second];

        sort_shown(&mut shown, Sort::Confidence);
        assert_eq!(shown[0].edits.edited, 1, "the library's order is untouched");
    }

    /// Build a pair that scores below a perfect match and rewrote one
    /// instruction, so only its [`Changed`] decides whether it is shown.
    fn edited_pair(changed: Changed) -> Match {
        Match {
            rarity: 0.0,
            bounded_calls: 0,
            early_exits: 0,
            before: 0,
            after: 0,
            confidence: Confidence::IdenticalCode,
            score: 0.9,
            changed,
            edits: Edits { added: 0, removed: 0, edited: 1 },
            kinds: EditKinds { other: 1, ..EditKinds::default() },
        }
    }

    /// Build a pair that changed nothing but a constant.
    fn retouched_pair(changed: Changed) -> Match {
        Match { score: 1.0, edits: Edits::default(), ..edited_pair(changed) }
    }

    /// A lone changed constant is left to the `CHANGE` column to report.
    #[test]
    fn a_constant_alone_does_not_repeat_the_change_column() {
        let kinds = EditKinds { constants: 1, ..EditKinds::default() };
        assert_eq!(describe_kinds(kinds, Changed::InDetail), "-");
    }

    /// The same for a difference that sits in unreadable bytes.
    #[test]
    fn unreadable_bytes_alone_do_not_repeat_the_change_column() {
        let kinds = EditKinds { opaque: 3, ..EditKinds::default() };
        assert_eq!(describe_kinds(kinds, Changed::Unreadable), "-");
    }

    /// A second kind makes the whole list worth printing.
    ///
    /// `changed unread` says the difference is unreadable, but it cannot say a
    /// branch went with it, so the column speaks up.
    #[test]
    fn a_second_kind_brings_the_list_back() {
        let kinds = EditKinds { opaque: 3, branches: 1, ..EditKinds::default() };
        assert_eq!(describe_kinds(kinds, Changed::Unreadable), "1 branch, 3 unread");
    }

    /// A constant inside a larger rewrite is the case the column exists for.
    ///
    /// Here `CHANGE` says only `changed`, so nothing else reports the value.
    #[test]
    fn a_constant_inside_a_rewrite_is_still_named() {
        let kinds = EditKinds { constants: 1, branches: 2, ..EditKinds::default() };
        assert_eq!(describe_kinds(kinds, Changed::Yes), "2 branch, 1 const");
    }

    /// The suppression follows the `CHANGE` word, not the kind alone.
    ///
    /// A lone constant under a plain `changed` is not a repeat of anything, so
    /// it must still be named.
    #[test]
    fn a_constant_under_a_plain_change_is_not_suppressed() {
        let kinds = EditKinds { constants: 1, ..EditKinds::default() };
        assert_eq!(describe_kinds(kinds, Changed::Yes), "1 const");
    }

    /// Plain data instructions never reach the column.
    #[test]
    fn other_instructions_are_left_out() {
        let kinds = EditKinds { other: 12, ..EditKinds::default() };
        assert_eq!(describe_kinds(kinds, Changed::Yes), "-");
    }

    /// What the report hides when no flag asks for more.
    const DEFAULT: Hidden = Hidden { retouched: Retouched::Hide, data: DataRegions::Hide };

    /// Data that went or came is hidden by the flag that hides changed data,
    /// and code never is.
    #[test]
    fn unmatched_data_is_hidden_as_changed_data_is() {
        assert!(is_shown_unmatched(Contents::Code, DEFAULT));
        assert!(!is_shown_unmatched(Contents::Data, DEFAULT));
        assert!(is_shown_unmatched(Contents::Data, Hidden { data: DataRegions::Show, ..DEFAULT }));
        assert!(
            !is_shown_unmatched(Contents::Data, Hidden { retouched: Retouched::Show, ..DEFAULT }),
            "--show-retouched does not show data"
        );
    }

    #[test]
    fn unmatched_data_says_it_is_data() {
        assert_eq!(unmatched_word("gone", Contents::Code), "gone");
        assert_eq!(unmatched_word("gone", Contents::Data), "gone data");
        assert_eq!(unmatched_word("new", Contents::Data), "new data");
    }

    /// Only unchanged functions and quiet changes are hidden when a reader
    /// wants changes.
    #[test]
    fn unchanged_functions_are_the_only_ones_hidden() {
        let shown = |changed| is_interesting(&edited_pair(changed), DEFAULT);

        assert!(!shown(Changed::No));
        assert!(!shown(Changed::Data), "data is hidden too, by its own flag");
        assert!(shown(Changed::Reordered));
        assert!(shown(Changed::InDetail));
        assert!(shown(Changed::Unreadable));
        assert!(shown(Changed::Yes));
    }

    /// A function that only changed a constant is held back by default.
    #[test]
    fn a_retouched_function_is_hidden_unless_asked_for() {
        let pair = retouched_pair(Changed::InDetail);

        assert!(is_retouched(&pair));
        assert!(!is_interesting(&pair, DEFAULT), "hidden by default");
        assert!(
            is_interesting(&pair, Hidden { retouched: Retouched::Show, ..DEFAULT }),
            "--show-retouched lists it"
        );
        assert!(
            !is_interesting(&pair, Hidden { data: DataRegions::Show, ..DEFAULT }),
            "--show-data does not"
        );
    }

    /// A pair that looks like data is held back by default, even with a
    /// perfect score, and `--show-data` lists it.
    #[test]
    fn a_data_region_is_hidden_unless_asked_for() {
        for pair in [edited_pair(Changed::Data), retouched_pair(Changed::Data)] {
            assert!(!is_interesting(&pair, DEFAULT), "hidden by default");
            assert!(
                !is_interesting(&pair, Hidden { retouched: Retouched::Show, ..DEFAULT }),
                "--show-retouched does not list it"
            );
            assert!(
                is_interesting(&pair, Hidden { data: DataRegions::Show, ..DEFAULT }),
                "--show-data lists it"
            );
        }
    }

    /// A rewritten instruction is a real edit whatever the pair scores.
    ///
    /// `do_mount` in a measured kernel pair scores 1.00 and rewrote
    /// one instruction. Hiding it would lose a real finding.
    #[test]
    fn a_perfect_score_with_an_edit_is_still_shown() {
        let pair = Match { score: 1.0, ..edited_pair(Changed::Yes) };

        assert!(!is_retouched(&pair), "an edited instruction is not a retouch");
        assert!(is_interesting(&pair, DEFAULT));
    }

    /// A pair below a perfect score differs in shape, so it is shown even
    /// when its counts round to nothing.
    #[test]
    fn an_imperfect_score_without_counts_is_still_shown() {
        let pair = Match { score: 0.9, edits: Edits::default(), ..edited_pair(Changed::Yes) };

        assert!(!is_retouched(&pair));
        assert!(is_interesting(&pair, DEFAULT));
    }

    /// The two flags that do not ask about the terminal always agree.
    #[test]
    fn the_color_flag_overrides_what_standard_output_is() {
        assert_eq!(Paint::resolve(When::Always), Paint::On);
        assert_eq!(Paint::resolve(When::Never), Paint::Off);
    }

    /// A test suite captures standard output through a pipe, so `Auto` must
    /// decide against color while these tests run.
    #[test]
    fn auto_gives_no_color_when_standard_output_is_not_a_terminal() {
        assert_eq!(Paint::resolve(When::Auto), Paint::Off);
    }

    /// An unpainted report must write no escape codes at all.
    #[test]
    fn no_color_prints_nothing_around_the_text() {
        let painted = Paint::On.pick(Color::FG_RED).colorize("do_mount").to_string();
        let plain = Paint::Off.pick(Color::FG_RED).colorize("do_mount").to_string();

        assert_eq!(plain, "do_mount");
        assert_ne!(painted, plain, "a painted cell carries escape codes");
    }

    /// The counts read the same with color as without.
    #[test]
    fn color_does_not_change_what_the_counts_say() {
        let edits = Edits { added: 1, removed: 2, edited: 3 };

        assert_eq!(describe_edits(edits, Paint::Off), "1/2/3");
        assert_eq!(describe_edits(Edits::default(), Paint::Off), "-");
        // A dash is not a count, so no color applies to it.
        assert_eq!(describe_edits(Edits::default(), Paint::On), "-");
    }

    /// Each count carries the color of its own kind.
    ///
    /// Coloring the three numbers alike would waste the column: the point is
    /// to tell an addition from a removal at a glance.
    #[test]
    fn each_count_carries_its_own_color() {
        let painted = describe_edits(Edits { added: 1, removed: 2, edited: 3 }, Paint::On);

        assert!(painted.contains(&ADDED_COLOR.colorize("1").to_string()));
        assert!(painted.contains(&REMOVED_COLOR.colorize("2").to_string()));
        assert!(painted.contains(&EDITED_COLOR.colorize("3").to_string()));
        // The separators stay plain, so the field still reads as one value.
        assert_eq!(painted.matches('/').count(), 2);
    }

    /// Each kind of change must be told apart by color.
    ///
    /// Two kinds sharing a color would hide the difference the report exists
    /// to show.
    #[test]
    fn every_change_has_its_own_color() {
        let changes = [
            Changed::No,
            Changed::Reordered,
            Changed::Data,
            Changed::InDetail,
            Changed::Unreadable,
            Changed::Yes,
        ];

        for (index, change) in changes.iter().enumerate() {
            for other in &changes[index + 1..] {
                assert_ne!(
                    color_of(*change).colorize("x").to_string(),
                    color_of(*other).colorize("x").to_string(),
                    "{change:?} and {other:?} must not share a color"
                );
            }
        }
    }
}