fnprint 0.6.1

Behavioral function fingerprinting: name functions in stripped binaries and patch-diff builds by what they do, not their bytes
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
use std::fs;
use std::io::{Read, Write};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Duration;

use anyhow::{bail, Context, Result};
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use fnprint_core::{
    both_named, dump_traces, eval, index_bytes, index_bytes_shard, match_aligned, match_by_name,
    query_corpus, source_str, triage, warm_pool, EffectTrace, IndexedFunc, Verdict, MIN_COMPLEXITY,
};
use fnprint_db::{Db, FuncPrint, FuncRec, MemCorpus};
use fnprint_emu::Config;
use fnprint_loader::FuncSource;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

// stdout is often a pipe that goes away early (`fnprint query ... | head`).
// println! panics on EPIPE and the release profile is panic=abort, so that idiom
// used to die with SIGABRT and a panic banner. every parent-side line goes
// through outln! instead: a broken pipe turns into this marker error, which
// main() maps to a quiet exit 0 the way head expects; any other write error is a
// real one and surfaces as usual. the worker never uses this, its reply goes out
// via emit() and a broken pipe there is a real failure.
#[derive(Debug)]
struct StdoutClosed;

impl std::fmt::Display for StdoutClosed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("stdout closed")
    }
}

impl std::error::Error for StdoutClosed {}

fn stdout_result(r: std::io::Result<()>) -> Result<()> {
    match r {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => Err(StdoutClosed.into()),
        Err(e) => Err(e).context("writing to stdout"),
    }
}

// println! that returns instead of panicking. only valid inside a fn returning
// anyhow::Result, same as every cmd_* here.
macro_rules! outln {
    ($($t:tt)*) => {
        stdout_result(writeln!(std::io::stdout(), $($t)*))?
    };
}

// hard caps on the privsep pipe so neither side can be pushed into an unbounded
// alloc. an ELF bigger than this we refuse; a worker reply bigger than this we
// treat as a compromised worker.
const MAX_INPUT: u64 = 512 << 20; // 512 MiB
                                  // the reply is fingerprints, far smaller than the input binary, so cap it well
                                  // below the input. this wire cap (enforced by the take(MAX_REPLY+1) read) is
                                  // the only bound on the reply: the parent sets no RLIMIT_AS on itself (setrlimit
                                  // only runs inside the jailed worker), so nothing else catches an oversized
                                  // decode. a compromised worker can amplify the wire size on decode: postcard
                                  // varint-decodes each zero u64 (1 wire byte) into 8 resident bytes, and the
                                  // Vec<String>/Vec<FuncRec> shapes add per-element String/struct overhead on top,
                                  // so the real worst case is ~24x: a full 128 MiB reply can balloon to roughly
                                  // 3 GiB transient in the parent before validate_* rejects it. that is the
                                  // accepted residual here - a compromised-worker-only transient spike (the jail
                                  // already held to let it get popped), not a persistent leak. we keep the cap at
                                  // 128 MiB rather than lower it (a smaller cap would false-reject a legit large
                                  // binary's prints) and rather than add a parent RLIMIT_AS (which would risk
                                  // false-killing a legitimately large in-memory corpus build).
const MAX_REPLY: u64 = 128 << 20;

// the hidden argv token the parent re-execs itself with to become the jailed
// worker. anything the emulator touches runs behind it.
const WORKER_TOKEN: &str = "__worker";

// wall-clock backstop on the whole worker interaction. the worker has its own
// deterministic per-function caps plus an RLIMIT_CPU, but neither bounds the
// PARENT: a worker wedged not consuming CPU, or one that forked a subtree before
// the jail latched, would otherwise block the parent's read/wait forever. past
// this deadline the parent SIGKILLs the worker's whole process group.
//
// it MUST sit strictly above the worker's own CPU budget so RLIMIT_CPU (the
// intended CPU bound) always fires first: the worker jail sets
// RLIMIT_CPU = 120 * min(threads, 16) cpu-seconds, and emulation is serialized
// behind a lock, so a legit large index can burn up to ~that many WALL seconds. a
// flat wall cap below that would false-abort a big index on a many-core box. so
// scale with the SAME clamped thread count and add margin; this only ever catches
// a true hang (a blocked syscall consuming no CPU, which RLIMIT_CPU can't catch).
// the clamp (mirrored from the sandbox's CPU_THREAD_CLAMP) keeps the ordering
// invariant AND stops the deadline from ballooning to hours on a big server.
const DEADLINE_THREAD_CLAMP: u64 = 16;
fn worker_deadline() -> Duration {
    let threads = std::thread::available_parallelism()
        .map(|n| n.get() as u64)
        .unwrap_or(8)
        .min(DEADLINE_THREAD_CLAMP);
    Duration::from_secs(120u64.saturating_mul(threads).saturating_add(300))
}

// once the reply is in hand the worker only has to unwind and exit (milliseconds).
// bound the reap anyway: a worker that closed stdout (giving us EOF) then made a
// blocking syscall burns no CPU, so RLIMIT_CPU can't catch it and a plain wait()
// would hang the parent forever. reachable only via a pre-jail compromise, but the
// parent should never be hangable.
const POST_REPLY_GRACE: Duration = Duration::from_secs(30);

// reap the worker without ever hanging. poll for exit up to `grace`, then SIGKILL
// the whole group and reap. kill-before-reap: the pid is still valid at the kill,
// so there is no window where we could signal a reused pid/pgid.
fn reap_bounded(
    child: &mut std::process::Child,
    pgid: Option<rustix::process::Pid>,
    grace: Duration,
) -> std::io::Result<std::process::ExitStatus> {
    let until = std::time::Instant::now() + grace;
    loop {
        if let Some(st) = child.try_wait()? {
            return Ok(st);
        }
        if std::time::Instant::now() >= until {
            if let Some(pgid) = pgid {
                let _ = rustix::process::kill_process_group(pgid, rustix::process::Signal::Kill);
            }
            return child.wait();
        }
        std::thread::sleep(Duration::from_millis(20));
    }
}

// what the jailed worker sends back over stdout. the parent treats every field
// as untrusted (a popped worker can put anything here): entry addresses and
// names are only ever printed escaped or written to the db, never used to index.
#[derive(Serialize, Deserialize)]
enum WorkerReply {
    IndexOk(Vec<IndexedFunc>),
    DumpOk(Vec<String>),
    // decoded corpus rows from the jailed db-reader. the parent rebuilds the LSH
    // index from these in memory; it never runs sqlite on the .db itself.
    DbOk(Vec<FuncRec>),
    Err(String),
}

#[derive(Parser)]
#[command(
    name = "fnprint",
    version,
    about = "behavioral function fingerprinting",
    after_help = "\
examples:
  fnprint index libz.so -o corpus.db               fingerprint a build you have symbols for
  fnprint query mystery.so --corpus corpus.db      name unknown functions from that corpus
  fnprint match old.so new.so                      show which shared functions changed behavior
  fnprint triage t.so --vuln v.db --patched p.db   rank a build against vuln vs patched
  fnprint query t.so --corpus c.db --format json   machine-readable output for scripts
  fnprint completions bash > ~/.local/share/bash-completion/completions/fnprint
                                                   install shell completion for your user
"
)]
struct Cli {
    /// run the emulator in-process without the sandbox. unsafe: only for a
    /// platform that can't jail, or debugging. default is always jailed.
    #[arg(long, global = true)]
    no_sandbox: bool,
    /// output format. human (default) is the readable tables; json is a stable
    /// machine schema for scripting/plugins; r2 emits a rizin script (query/triage
    /// only) that renames matched functions.
    #[arg(long, value_enum, default_value_t = Format::Human, global = true)]
    format: Format,
    /// how much a consistent call-graph neighbourhood lifts a pair when
    /// aligning (query, aligned match, eval; triage scores each side on its own). 0 turns propagation off
    /// and scores each function on its behavior alone.
    #[arg(long, default_value_t = fnprint_core::GRAPH_WEIGHT, global = true)]
    graph_weight: f64,
    #[command(subcommand)]
    cmd: Cmd,
}

// json/r2 consumers key off this; bump only when a schema shape changes, so it's
// independent of the fingerprint format.
const OUTPUT_SCHEMA_VERSION: u32 = 1;

#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
enum Format {
    Human,
    Json,
    R2,
}

#[derive(Subcommand)]
enum Cmd {
    /// fingerprint every function in a binary, optionally into a db
    Index {
        binary: String,
        #[arg(short, long)]
        out: Option<String>,
    },
    /// diff two binaries (or dbs) by behavior, the n-day view
    Match {
        a: String,
        b: String,
        /// max changed rows to print (0 = all). json output is never capped.
        #[arg(long, default_value_t = 40)]
        limit: usize,
        /// align the two builds on behavior + call graph instead of by symbol
        /// name. automatic when either side is stripped; force it here to see
        /// what the name-free view says about a symboled pair.
        #[arg(long)]
        align: bool,
    },
    /// name unknown functions in a binary using a corpus db
    Query {
        target: String,
        #[arg(long)]
        corpus: String,
        #[arg(long, default_value_t = 0.7)]
        threshold: f64,
        /// max named rows to print (0 = all). json/r2 output is never capped.
        #[arg(long, default_value_t = 0)]
        limit: usize,
    },
    /// accuracy metrics between two builds, using symbol names as ground truth
    Eval { a: String, b: String },
    /// n-day triage: rank a target against known-vulnerable and patched corpora
    Triage {
        target: String,
        #[arg(long)]
        vuln: String,
        #[arg(long)]
        patched: String,
        /// a side has to be at least this similar to count as a real lead
        #[arg(long, default_value_t = 0.6)]
        min_sim: f64,
        /// how far the two sides must separate before we commit to a verdict
        #[arg(long, default_value_t = 0.08)]
        margin: f64,
        /// max review-queue rows to print (0 = all). json/r2 output is never capped.
        #[arg(long, default_value_t = 0)]
        limit: usize,
    },
    /// print the recorded effect trace for one function (debugging)
    Dump { binary: String, func: String },
    /// print a shell completion script to stdout (bash, zsh, fish, ...)
    Completions {
        /// which shell to generate the completion script for
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
}

fn main() -> Result<()> {
    // privsep worker entrypoint. the parent re-execs itself as
    // `fnprint __worker <op> [func]`; the worker jails itself, reads the
    // untrusted binary from stdin, and writes a postcard reply to stdout. we
    // intercept it before clap so the worker protocol stays out of the cli.
    let mut raw = std::env::args();
    let _bin = raw.next();
    if raw.next().as_deref() == Some(WORKER_TOKEN) {
        let op = raw.next().unwrap_or_default();
        let func = raw.next();
        return worker_main(&op, func.as_deref());
    }

    let cli = Cli::parse();
    let ns = cli.no_sandbox;
    let fmt = cli.format;
    let gw = cli.graph_weight;
    if !gw.is_finite() || gw < 0.0 {
        bail!("--graph-weight must be a non-negative number");
    }
    let res = match cli.cmd {
        Cmd::Index { binary, out } => cmd_index(&binary, out.as_deref(), ns, fmt),
        Cmd::Match { a, b, limit, align } => cmd_match(&a, &b, limit, align, gw, ns, fmt),
        Cmd::Query {
            target,
            corpus,
            threshold,
            limit,
        } => cmd_query(&target, &corpus, threshold, limit, gw, ns, fmt),
        Cmd::Eval { a, b } => cmd_eval(&a, &b, gw, ns, fmt),
        Cmd::Triage {
            target,
            vuln,
            patched,
            min_sim,
            margin,
            limit,
        } => cmd_triage(&target, &vuln, &patched, min_sim, margin, limit, ns, fmt),
        Cmd::Dump { binary, func } => cmd_dump(&binary, &func, ns, fmt),
        // completions don't touch the emulator or a binary, so the sandbox and
        // format flags don't apply; just render the script.
        Cmd::Completions { shell } => cmd_completions(shell),
    };
    // the reader hung up mid-table (`| head`): nothing to report, exit clean
    match res {
        Err(e) if e.is::<StdoutClosed>() => Ok(()),
        r => r,
    }
}

// write a shell completion script for `fnprint` to stdout. the operator pipes it
// to the right place for their shell (see `--help` examples).
fn cmd_completions(shell: clap_complete::Shell) -> Result<()> {
    let mut cmd = Cli::command();
    // generate into a buffer (infallible) rather than straight to stdout: the
    // clap_complete writers unwrap on a write error, so `fnprint completions bash
    // | head` (closed pipe) would abort under panic=abort. we own the stdout write
    // and route it through the same broken-pipe handling as the tables.
    let mut buf = Vec::new();
    clap_complete::generate(shell, &mut cmd, "fnprint", &mut buf);
    stdout_result(std::io::stdout().write_all(&buf))
}

// ---- jailed worker ----------------------------------------------------------

fn worker_main(op: &str, func: Option<&str>) -> Result<()> {
    // first thing, before anything else touches inherited state: drop fds above
    // std{in,out,err}, arm pdeathsig, and bail if the parent already died. this
    // fails closed (we never read the input if it errors).
    fnprint_sandbox::harden_worker_preinput().context("worker preinput hardening")?;

    // spin up the rayon pool before we jail so the parallel index is warm and
    // doesn't pay thread-spawn cost under the sandbox.
    warm_thread_pool();

    // fail-closed: if the jail won't install, we do not read or touch the input.
    fnprint_sandbox::lock_down_worker().context("worker could not enter sandbox")?;

    // read the untrusted binary from stdin (read is allowed inside the jail, so
    // the worker never needs open()). bounded so a huge stdin can't OOM us.
    let mut input = Vec::new();
    let n = std::io::stdin()
        .lock()
        .take(MAX_INPUT + 1)
        .read_to_end(&mut input)
        .context("worker reading stdin")?;
    if n as u64 > MAX_INPUT {
        return emit(&WorkerReply::Err("input over size cap".into()));
    }

    // run the requested op, folding any error into the reply. this path parses
    // and micro-executes hostile bytes, so it must never panic the process.
    let reply = match op {
        "index" => {
            // func carries the shard as "idx/count" (absent -> whole binary).
            let (idx, cnt) = parse_shard(func);
            match index_bytes_shard(&input, emu_config(), idx, cnt) {
                Ok(funcs) => WorkerReply::IndexOk(funcs),
                Err(e) => WorkerReply::Err(format!("{e:#}")),
            }
        }
        "dump" => {
            let name = func.unwrap_or_default();
            match dump_traces(&input, name, emu_config()) {
                Ok(traces) => WorkerReply::DumpOk(render_traces(&traces)),
                Err(e) => WorkerReply::Err(format!("{e:#}")),
            }
        }
        // parse the untrusted corpus .db image in memory (no file open, so it
        // runs under this same jail) and hand the decoded rows back.
        "dbload" => match Db::open_image(&input).and_then(|db| db.all()) {
            Ok(recs) => WorkerReply::DbOk(recs),
            Err(e) => WorkerReply::Err(format!("{e:#}")),
        },
        other => WorkerReply::Err(format!("unknown worker op: {other}")),
    };
    emit(&reply)
}

fn warm_thread_pool() {
    // touching the global pool spins up its worker threads now, pre-jail.
    warm_pool();
}

// render the dump output to plain lines in the worker so the parent doesn't have
// to serialize the whole effect enum. matches the old cmd_dump format exactly.
fn render_traces(traces: &[EffectTrace]) -> Vec<String> {
    let mut out = Vec::new();
    for (i, t) in traces.iter().enumerate() {
        out.push(format!(
            "-- path {} ({} effects, instret {}, capped {}, coverage {:.2}) --",
            i,
            t.effects.len(),
            t.instret,
            t.capped,
            t.coverage
        ));
        for e in &t.effects {
            out.push(format!("   {e:?}"));
        }
    }
    out
}

fn emit(reply: &WorkerReply) -> Result<()> {
    let buf = postcard::to_allocvec(reply).context("serializing worker reply")?;
    std::io::stdout()
        .lock()
        .write_all(&buf)
        .context("worker writing reply")?;
    Ok(())
}

// ---- parent side of privsep -------------------------------------------------

// re-exec self as the jailed worker, hand it the bytes over stdin, read its
// postcard reply back. the input is written on a separate thread so a large ELF
// can't deadlock against the reply on a full pipe.
fn run_worker(op: &str, func: Option<&str>, input: Arc<Vec<u8>>) -> Result<WorkerReply> {
    let exe = std::env::current_exe().context("locating self for worker re-exec")?;
    let mut cmd = Command::new(exe);
    // the worker inherits nothing from our environment. it only needs argv (op +
    // optional shard/func) and the stdin payload; a stray var (LD_PRELOAD,
    // proxy/locale/tmpdir settings, anything the caller exported) is ambient
    // authority the jailed parser shouldn't get to read or act on. clear it all.
    cmd.env_clear();
    // the one knob the worker takes from us, passed explicitly (never the raw
    // environment): the blanket restart count, already parsed and clamped.
    cmd.env("FNPRINT_BLANKET", emu_config().blanket_restarts.to_string());
    cmd.arg(WORKER_TOKEN).arg(op);
    if let Some(f) = func {
        cmd.arg(f);
    }
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        // capture stderr instead of handing the worker our terminal. a crash or
        // panic message there can carry attacker-controlled bytes (a symbol name
        // echoed by the parser), and an inherited tty would let raw escape
        // sequences through unescaped. we drain it on a thread, keep a bounded
        // tail, and esc() it before it ever reaches the terminal.
        .stderr(Stdio::piped());
    // put the worker in its own process group (pgid == its pid) so we can signal
    // the whole subtree at once. setpgid runs in the child after fork, before
    // exec, so long before the worker installs its seccomp jail.
    cmd.process_group(0);
    let mut child = cmd.spawn().context("spawning jailed worker")?;
    // pgid == pid because of process_group(0) above
    let wpgid = rustix::process::Pid::from_raw(child.id() as i32);

    // stdin writer: feed the payload on its own thread so a large ELF can't
    // deadlock against the reply on a full pipe.
    let mut stdin = child.stdin.take().context("worker stdin")?;
    // clone the Arc handle, not the bytes: the sharded path spawns N workers off
    // one shared buffer, so a per-writer deep copy meant N extra full-ELF copies
    // resident in the parent at once. the handle move keeps it to the single Arc.
    let payload = Arc::clone(&input);
    let writer = std::thread::spawn(move || {
        // ignore the error: if the worker died early we'll see it in wait()
        let _ = stdin.write_all(&payload);
        drop(stdin);
    });

    // drain stderr on its own thread so a chatty worker can't wedge on a full
    // stderr pipe. keep only a bounded tail; discard the rest so the worker never
    // blocks writing.
    let mut errpipe = child.stderr.take().context("worker stderr")?;
    let errdrain = std::thread::spawn(move || {
        let mut buf = Vec::new();
        let _ = errpipe.by_ref().take(8 * 1024).read_to_end(&mut buf);
        let _ = std::io::copy(&mut errpipe, &mut std::io::sink());
        buf
    });

    // read the reply on its own thread and hand it back over a channel, so the
    // main thread can put a wall-clock deadline on the whole exchange with
    // recv_timeout. doing the kill from here (rather than a separate thread
    // watching an already-reaped child) means the SIGKILL on timeout always
    // happens BEFORE we wait()/reap, while the pid is still valid: there is no
    // window where we could signal a reused pid/pgid.
    let mut stdout = child.stdout.take().context("worker stdout")?;
    let (reply_tx, reply_rx) = std::sync::mpsc::channel::<std::io::Result<Vec<u8>>>();
    let reader = std::thread::spawn(move || {
        let mut out = Vec::new();
        let r = stdout.by_ref().take(MAX_REPLY + 1).read_to_end(&mut out);
        let _ = reply_tx.send(r.map(|_| out));
    });

    let deadline = worker_deadline();
    let out = match reply_rx.recv_timeout(deadline) {
        Ok(Ok(out)) => out,
        Ok(Err(e)) => {
            // read failed (worker died mid-write, etc). reap and report.
            let _ = child.wait();
            let _ = writer.join();
            let _ = reader.join();
            return Err(anyhow::Error::new(e).context("reading worker reply"));
        }
        Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
            // deadline hit. SIGKILL the whole group BEFORE reaping so the pid is
            // still valid (no reuse window) and any forked subtree dies too. we do
            // not join reader/writer/errdrain here: if a descendant escaped the
            // group and holds a pipe fd (only reachable via a pre-jail compromise)
            // a join could hang, and the parent is bailing out regardless.
            if let Some(pgid) = wpgid {
                let _ = rustix::process::kill_process_group(pgid, rustix::process::Signal::Kill);
            }
            let _ = child.wait();
            bail!(
                "jailed worker exceeded the {}s time budget and was killed",
                deadline.as_secs()
            );
        }
        Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
            // reader thread vanished without sending (panicked). reap and report.
            let _ = child.wait();
            bail!("jailed worker reply reader failed");
        }
    };

    // reply in hand; reap the worker, bounded so a post-reply blocking hang can't
    // wedge the parent (see reap_bounded).
    let status = reap_bounded(&mut child, wpgid, POST_REPLY_GRACE).context("waiting on worker")?;
    let _ = writer.join();
    let _ = reader.join();
    let errtail = errdrain.join().unwrap_or_default();

    if !status.success() {
        let tail = String::from_utf8_lossy(&errtail);
        let tail = tail.trim();
        if tail.is_empty() {
            bail!("jailed worker exited abnormally ({status}) - likely killed by the sandbox or a crash in the emulator");
        }
        bail!(
            "jailed worker exited abnormally ({status}) - likely killed by the sandbox or a crash in the emulator; stderr: {}",
            esc(tail)
        );
    }
    if out.len() as u64 > MAX_REPLY {
        bail!("jailed worker reply over size cap");
    }
    let reply: WorkerReply = postcard::from_bytes(&out).context("decoding worker reply")?;
    Ok(reply)
}

// parse the "idx/count" shard spec the parent hands an index worker. absent or
// malformed -> the whole binary (0 of 1), so the worker path stays fail-safe.
fn parse_shard(spec: Option<&str>) -> (usize, usize) {
    let s = match spec {
        Some(s) => s,
        None => return (0, 1),
    };
    let mut it = s.split('/');
    let idx = it.next().and_then(|v| v.parse::<usize>().ok());
    let cnt = it.next().and_then(|v| v.parse::<usize>().ok());
    match (idx, cnt) {
        (Some(i), Some(c)) if c >= 1 && i < c => (i, c),
        _ => (0, 1),
    }
}

// how many jailed worker processes to shard an index across. emulation is
// serialized inside each process (shared qemu TCG state), so parallelism comes
// from running several processes. this is OPT-IN via FNPRINT_SHARDS: each worker
// reloads the whole ELF and runs its own TCI (interpreter) VM, so on typical
// binaries the per-worker load + cache contention across many interpreter VMs
// eats the gain (measured: neutral on small, ~0.8x on a mid-size lib). it only
// pays off on large, function-rich corpora, so the default stays single-process
// (identical to pre-0.4.0). set FNPRINT_SHARDS=N to shard a big index.
// emulator config for this process. blanket restarts are off unless asked for
// (see fnprint_emu::BLANKET_RESTARTS for why), FNPRINT_BLANKET=N turns them on.
fn emu_config() -> Config {
    let mut cfg = Config::default();
    if let Ok(v) = std::env::var("FNPRINT_BLANKET") {
        if let Ok(n) = v.parse::<usize>() {
            cfg.blanket_restarts = n.min(16);
        }
    }
    cfg
}

fn shard_count() -> usize {
    if let Ok(v) = std::env::var("FNPRINT_SHARDS") {
        if let Ok(n) = v.parse::<usize>() {
            return n.clamp(1, 64);
        }
    }
    1
}

// coverage is advisory and never gates, but a popped worker controls the reply, so
// sanitize NaN/negative/huge to "assume covered" before it can render a garbage %.
fn sanitize_coverage(funcs: &mut [IndexedFunc]) {
    for f in funcs {
        f.coverage = if f.coverage.is_finite() {
            f.coverage.clamp(0.0, 1.0)
        } else {
            1.0
        };
    }
}

// each shard worker re-reads the WHOLE ELF into its own address space, so the
// system-wide footprint of a sharded index is input_len * shard_count, not just
// input_len. bound that product: past this, trim the shard count (never below 1)
// so a big ELF sharded wide can't commit tens of GiB across the child processes.
const MAX_AGGREGATE_INPUT: u64 = 2 << 30; // 2 GiB summed across shard children

// trim the requested shard count so input_len * shards stays under the aggregate
// budget. the corpus is byte-identical at any shard count (per-function prints +
// a sorted merge), so this only trades parallelism, never output.
fn clamp_shards_for_input(requested: usize, input_len: u64) -> usize {
    if input_len == 0 {
        return requested;
    }
    let max_by_mem = (MAX_AGGREGATE_INPUT / input_len).max(1);
    (requested as u64).min(max_by_mem) as usize
}

// index a binary's bytes, jailed by default. --no-sandbox runs it in-process.
fn run_index(bytes: &[u8], no_sandbox: bool) -> Result<Vec<IndexedFunc>> {
    if no_sandbox {
        eprintln!("warning: --no-sandbox, running the emulator without the jail");
        return index_bytes(bytes, emu_config());
    }
    let requested = shard_count();
    let n = clamp_shards_for_input(requested, bytes.len() as u64);
    if n < requested {
        eprintln!(
            "note: reduced shards {requested} -> {n} to bound memory for a {}-byte input",
            bytes.len()
        );
    }
    if n <= 1 {
        // single worker: exactly the old path (whole binary, one jailed process).
        return match run_worker("index", None, Arc::new(bytes.to_vec()))? {
            WorkerReply::IndexOk(mut funcs) => {
                validate_reply_fps(&funcs)?;
                sanitize_coverage(&mut funcs);
                Ok(funcs)
            }
            WorkerReply::Err(e) => bail!("{}", esc(&e)),
            _ => bail!("worker returned the wrong reply kind for index"),
        };
    }
    run_workers_sharded(bytes, n)
}

// spawn N jailed workers concurrently, one per shard, and merge. each worker
// jails itself the same way; a failure in any shard fails the whole index (no
// partial corpus). the merged result is sorted by (entry, name, source) to
// reconstruct the single-process order, so the corpus is byte-identical whatever
// N is (fingerprints are per-function independent + the func list is sorted).
fn run_workers_sharded(bytes: &[u8], n: usize) -> Result<Vec<IndexedFunc>> {
    // one buffer shared across all N worker threads (the ELF can be up to
    // MAX_INPUT); each thread clones only the Arc handle and streams the same
    // bytes to its child, so the parent holds exactly one copy, not N.
    let shared = Arc::new(bytes.to_vec());
    let handles: Vec<_> = (0..n)
        .map(|i| {
            let shared = Arc::clone(&shared);
            std::thread::spawn(move || {
                let spec = format!("{i}/{n}");
                run_worker("index", Some(&spec), shared)
            })
        })
        .collect();

    let mut all: Vec<IndexedFunc> = Vec::new();
    let mut first_err: Option<anyhow::Error> = None;
    for h in handles {
        // join every thread even after an error so no child is left orphaned.
        let res = match h.join() {
            Ok(r) => r,
            Err(_) => {
                if first_err.is_none() {
                    first_err = Some(anyhow::anyhow!("a shard worker thread panicked"));
                }
                continue;
            }
        };
        match res {
            Ok(WorkerReply::IndexOk(mut funcs)) => {
                if let Err(e) = validate_reply_fps(&funcs) {
                    if first_err.is_none() {
                        first_err = Some(e);
                    }
                    continue;
                }
                sanitize_coverage(&mut funcs);
                all.append(&mut funcs);
            }
            Ok(WorkerReply::Err(e)) => {
                if first_err.is_none() {
                    first_err = Some(anyhow::anyhow!("{}", esc(&e)));
                }
            }
            Ok(_) => {
                if first_err.is_none() {
                    first_err = Some(anyhow::anyhow!("worker returned the wrong reply kind"));
                }
            }
            Err(e) => {
                if first_err.is_none() {
                    first_err = Some(e);
                }
            }
        }
    }
    // fail-closed: any shard failure aborts the whole index, no partial corpus.
    if let Some(e) = first_err {
        return Err(e);
    }
    // canonical order == single-process order: the loader sorts funcs by entry
    // (deduped), and rayon collect preserves that, so sorting the merged shards by
    // entry (name/source break ties defensively) reproduces it byte-for-byte.
    all.sort_by(|a, b| {
        a.entry
            .cmp(&b.entry)
            .then_with(|| a.name.cmp(&b.name))
            .then_with(|| source_str(a.source).cmp(source_str(b.source)))
    });
    Ok(all)
}

// a compromised worker controls its reply. every fingerprint must carry a
// SIG_LEN signature; reject a malformed one loudly here rather than letting it
// flow into the comparators as silent zero-similarity noise.
fn validate_reply_fps(funcs: &[IndexedFunc]) -> Result<()> {
    for f in funcs {
        if f.fp.sig.len() != fnprint_core::SIG_LEN {
            bail!("jailed worker returned a fingerprint with an invalid signature length");
        }
    }
    Ok(())
}

fn run_dump(bytes: &[u8], func: &str, no_sandbox: bool) -> Result<Vec<String>> {
    if no_sandbox {
        eprintln!("warning: --no-sandbox, running the emulator without the jail");
        return Ok(render_traces(&dump_traces(bytes, func, emu_config())?));
    }
    match run_worker("dump", Some(func), Arc::new(bytes.to_vec()))? {
        WorkerReply::DumpOk(lines) => Ok(lines),
        WorkerReply::Err(e) => bail!("{}", esc(&e)),
        _ => bail!("worker returned the wrong reply kind for dump"),
    }
}

// ---- commands ---------------------------------------------------------------

fn is_db(p: &str) -> bool {
    Path::new(p).extension().map(|e| e == "db").unwrap_or(false)
}

// --limit of 0 means no cap. only the human tables honor it: json/r2 always emit
// the full set so a script or a plugin never silently loses rows to a display cap.
fn row_cap(limit: usize) -> usize {
    if limit == 0 {
        usize::MAX
    } else {
        limit
    }
}

// symbol names and labels come out of attacker-controlled ELF strings. anything
// that isn't a plain printable ascii char gets escaped so a crafted name can't
// smuggle terminal escape sequences (colors, cursor moves, title sets) into our
// output. c/rust symbol names are ascii so real names print unchanged.
fn esc(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        if b == b' ' || b.is_ascii_graphic() {
            out.push(b as char);
        } else {
            out.push_str(&format!("\\x{b:02x}"));
        }
    }
    out
}

// a symbol name emitted into a rizin script is a COMMAND TOKEN, not display text,
// so esc() (which only defangs terminal escapes) is not enough: spaces, ';', '`',
// newlines etc. could break out of the `afn <name> <addr>` argument and inject r2
// commands. map the name to a safe identifier ([A-Za-z0-9_.] only) and prefix it
// so a crafted name can never be anything but an argument. distinct escaping
// context from esc(), on purpose.
fn r2_ident(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    out.push_str("fnp.");
    for c in s.chars() {
        if c.is_ascii_alphanumeric() || c == '_' || c == '.' {
            out.push(c);
        } else {
            out.push('_');
        }
    }
    out
}

// print a serde_json value as one line and return Ok, the json output path.
fn emit_json(v: &serde_json::Value) -> Result<()> {
    outln!("{}", serde_json::to_string(v)?);
    Ok(())
}

// a compromised db-reader worker controls its reply, same threat model as the
// index reply: reject any record whose fingerprint isn't a well-formed SIG_LEN
// signature rather than letting it flow into the comparators as silent noise.
fn validate_corpus_records(recs: &[FuncRec]) -> Result<()> {
    for r in recs {
        if r.fp.sig.len() != fnprint_core::SIG_LEN {
            bail!("jailed db worker returned a record with an invalid signature length");
        }
    }
    Ok(())
}

// read a corpus .db and return its decoded rows. jailed by default: the parent
// reads the file bytes off disk but never parses them with sqlite; a jailed
// worker deserializes the image in memory and hands back decoded records. so a
// hostile .db can only ever hit sqlite inside the jail. --no-sandbox keeps the
// old in-process sqlite read for platforms that can't jail (loud opt-out).
fn load_corpus_records(path: &str, no_sandbox: bool) -> Result<Vec<FuncRec>> {
    if no_sandbox {
        eprintln!("warning: --no-sandbox, parsing corpus with in-process sqlite (unjailed)");
        return Db::open(path)
            .with_context(|| format!("opening corpus {}", esc(path)))?
            .all();
    }
    let bytes = read_input(path)?;
    match run_worker("dbload", None, Arc::new(bytes))? {
        WorkerReply::DbOk(recs) => {
            validate_corpus_records(&recs)?;
            Ok(recs)
        }
        // the worker's error text can carry attacker bytes (sqlite echoing a
        // crafted string); escape it before it reaches the terminal.
        WorkerReply::Err(e) => bail!("{}", esc(&e)),
        _ => bail!("worker returned the wrong reply kind for dbload"),
    }
}

// build the in-memory corpus (records + rebuilt LSH bands) that query/triage
// consume. no sqlite touches the untrusted image in the trusted parent.
fn load_corpus(path: &str, no_sandbox: bool) -> Result<MemCorpus> {
    Ok(MemCorpus::from_records(load_corpus_records(
        path, no_sandbox,
    )?))
}

// read a file we're about to hand the jailed worker, refusing anything over
// MAX_INPUT. open ONCE and stat + read through the same handle: a path stat'd and
// then re-read is a TOCTOU window where a symlink swap could size-check one file
// and read another. we also reject non-regular files: a device or fifo (e.g.
// /dev/zero) reports len 0, sails past a size check, then streams forever, so a
// naive read-to-end would spin or hang the parent. finally the read itself is
// capped at MAX_INPUT+1 so a file that grows after the stat still can't push the
// parent past the cap before the worker's own stdin cap would fire.
fn read_input(path: &str) -> Result<Vec<u8>> {
    // esc the path in every message: a crafted filename (operator sweeping a
    // directory of attacker-named files) could otherwise smuggle terminal escapes
    // through an error line.
    let f = fs::File::open(path).with_context(|| format!("opening {}", esc(path)))?;
    let md = f
        .metadata()
        .with_context(|| format!("stat {}", esc(path)))?;
    if !md.is_file() {
        bail!("{} is not a regular file", esc(path));
    }
    if md.len() > MAX_INPUT {
        bail!(
            "{} is {} bytes, over the {MAX_INPUT} byte cap",
            esc(path),
            md.len()
        );
    }
    let mut bytes = Vec::new();
    let n = f
        .take(MAX_INPUT + 1)
        .read_to_end(&mut bytes)
        .with_context(|| format!("reading {}", esc(path)))?;
    if n as u64 > MAX_INPUT {
        bail!("{} over the {MAX_INPUT} byte cap", esc(path));
    }
    Ok(bytes)
}

// load an index from either an ELF (jailed emulation) or a prebuilt db (jailed
// sqlite parse). in both cases the untrusted bytes are parsed behind the jail.
fn load_index(path: &str, no_sandbox: bool) -> Result<Vec<IndexedFunc>> {
    if is_db(path) {
        Ok(load_corpus_records(path, no_sandbox)?
            .into_iter()
            .map(|r| IndexedFunc {
                name: r.name,
                entry: r.entry,
                source: FuncSource::Symtab,
                fp: r.fp,
                // a .db target was indexed earlier and never stored coverage, so
                // we can't re-derive it. assume covered rather than gate a corpus.
                coverage: 1.0,
                callees: r.callees,
            })
            .collect())
    } else {
        let bytes = read_input(path)?;
        run_index(&bytes, no_sandbox)
    }
}

fn cmd_index(binary: &str, out: Option<&str>, no_sandbox: bool, fmt: Format) -> Result<()> {
    if fmt == Format::R2 {
        bail!("r2 output is only supported for query and triage");
    }
    let bytes = read_input(binary)?;
    let funcs = run_index(&bytes, no_sandbox)?;
    let label = Path::new(binary)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(binary);

    let named = funcs.iter().filter(|f| f.name.is_some()).count();
    let signal_cov: Vec<f32> = funcs
        .iter()
        .filter(|f| f.fp.complexity >= MIN_COMPLEXITY)
        .map(|f| f.coverage)
        .collect();
    let usable = signal_cov.len();
    // mean coverage over the prints that carry signal: how much of each function
    // body the microexecution actually observed. a low mean warns that these
    // prints rest on little behavior (guard-heavy or heavily-capped functions).
    let mean_cov = if signal_cov.is_empty() {
        None
    } else {
        Some(signal_cov.iter().sum::<f32>() / signal_cov.len() as f32)
    };

    let mut wrote = None;
    if let Some(path) = out {
        let db = Db::open(path)?;
        // one transaction for the whole binary, not a commit per function
        let prints: Vec<FuncPrint> = funcs
            .iter()
            .map(|f| FuncPrint {
                name: f.name.as_deref(),
                entry: f.entry,
                source: source_str(f.source),
                fp: &f.fp,
                callees: &f.callees,
            })
            .collect();
        db.insert_all(label, &prints)?;
        wrote = Some(path);
    }

    if fmt == Format::Json {
        let list: Vec<serde_json::Value> = funcs
            .iter()
            .map(|f| {
                serde_json::json!({
                    "entry": format!("{:#x}", f.entry),
                    "name": f.name.as_deref().map(esc),
                    "source": source_str(f.source),
                    "complexity": f.fp.complexity,
                    "shingles": f.fp.shingles,
                    "capped": f.fp.capped,
                    "coverage": f.coverage,
                })
            })
            .collect();
        return emit_json(&serde_json::json!({
            "schema_version": OUTPUT_SCHEMA_VERSION,
            "binary": esc(label),
            "functions": funcs.len(),
            "named": named,
            "with_signal": usable,
            "wrote": wrote,
            "funcs": list,
        }));
    }

    match mean_cov {
        Some(c) => outln!(
            "{}: {} functions, {} named, {} with enough signal ({:.0}% mean coverage)",
            esc(label),
            funcs.len(),
            named,
            usable,
            c * 100.0
        ),
        None => outln!(
            "{}: {} functions, {} named, {} with enough signal",
            esc(label),
            funcs.len(),
            named,
            usable
        ),
    }
    if let Some(path) = wrote {
        outln!("wrote {} prints -> {}", funcs.len(), esc(path));
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn cmd_match(
    a: &str,
    b: &str,
    limit: usize,
    force_align: bool,
    graph_weight: f64,
    no_sandbox: bool,
    fmt: Format,
) -> Result<()> {
    if fmt == Format::R2 {
        bail!("r2 output is only supported for query and triage");
    }
    let ia = load_index(a, no_sandbox)?;
    let ib = load_index(b, no_sandbox)?;
    // by name when both sides have symbols, otherwise (stripped firmware, the
    // usual case) align on behavior + call graph. --align forces the latter.
    let aligned = force_align || !both_named(&ia, &ib);
    let rep = if aligned {
        match_aligned(&ia, &ib, graph_weight)
    } else {
        match_by_name(&ia, &ib)
    };

    if fmt == Format::Json {
        let changed: Vec<serde_json::Value> = rep
            .changed
            .iter()
            .map(|c| {
                serde_json::json!({
                    "name": esc(&c.name),
                    "similarity": c.similarity,
                    "entry_a": c.entry_a.map(|e| format!("{e:#x}")),
                    "entry_b": c.entry_b.map(|e| format!("{e:#x}")),
                })
            })
            .collect();
        return emit_json(&serde_json::json!({
            "schema_version": OUTPUT_SCHEMA_VERSION,
            "mode": if aligned { "aligned" } else { "name" },
            "compared": rep.compared,
            "unchanged": rep.same,
            "changed": changed,
            "low_signal": rep.low_signal,
            "only_a": rep.only_a.iter().map(|s| esc(s)).collect::<Vec<_>>(),
            "only_b": rep.only_b.iter().map(|s| esc(s)).collect::<Vec<_>>(),
        }));
    }

    if aligned {
        outln!(
            "aligned {} function pairs by behavior + call graph (no symbol names needed)",
            rep.compared
        );
    } else {
        outln!("compared {} functions present in both", rep.compared);
    }
    outln!("  unchanged:  {}", rep.same);
    outln!("  changed:    {}", rep.changed.len());
    outln!("  low-signal: {} (too small to judge)", rep.low_signal);
    outln!("  only in {}: {}", esc(a), rep.only_a.len());
    outln!("  only in {}: {}", esc(b), rep.only_b.len());

    if !rep.changed.is_empty() {
        outln!("\nchanged behavior (lowest similarity first):");
        for c in rep.changed.iter().take(row_cap(limit)) {
            outln!("  {:>5.1}%  {}", c.similarity * 100.0, esc(&c.name));
        }
        let shown = rep.changed.len().min(row_cap(limit));
        if shown < rep.changed.len() {
            outln!(
                "  ... {} more (raise --limit or --limit 0 for all)",
                rep.changed.len() - shown
            );
        }
    }
    Ok(())
}

fn cmd_query(
    target: &str,
    corpus: &str,
    threshold: f64,
    limit: usize,
    graph_weight: f64,
    no_sandbox: bool,
    fmt: Format,
) -> Result<()> {
    let it = load_index(target, no_sandbox)?;
    let db = load_corpus(corpus, no_sandbox)?;
    let named = query_corpus(&it, &db, threshold, graph_weight)?;

    if fmt == Format::Json {
        let list: Vec<serde_json::Value> = named
            .iter()
            .map(|n| {
                serde_json::json!({
                    "entry": format!("{:#x}", n.entry),
                    "guess": esc(&n.guess),
                    "from_binary": esc(&n.from_binary),
                    "similarity": n.similarity,
                    "graph": n.graph,
                    "score": n.score,
                })
            })
            .collect();
        return emit_json(&serde_json::json!({
            "schema_version": OUTPUT_SCHEMA_VERSION,
            "threshold": threshold,
            "named": list,
        }));
    }

    if fmt == Format::R2 {
        // a rizin script: run with `. fnprint.r2` inside r2/rizin on the target.
        // names go through r2_ident so a crafted symbol can't inject commands.
        outln!(
            "# fnprint: {} function(s) named at >= {:.0}%",
            named.len(),
            threshold * 100.0
        );
        for n in &named {
            outln!("afn {} {:#x}", r2_ident(&n.guess), n.entry);
        }
        return Ok(());
    }

    if named.is_empty() {
        outln!(
            "no matches above {:.0}% (try a lower --threshold)",
            threshold * 100.0
        );
        return Ok(());
    }
    outln!("named {} function(s):", named.len());
    outln!("  addr        sim    graph  name");
    for n in named.iter().take(row_cap(limit)) {
        outln!(
            "  {:#010x}  {:>5.1}%  {:>4.0}%  {}  ({})",
            n.entry,
            n.similarity * 100.0,
            n.graph * 100.0,
            esc(&n.guess),
            esc(&n.from_binary)
        );
    }
    let shown = named.len().min(row_cap(limit));
    if shown < named.len() {
        outln!(
            "  ... {} more (raise --limit or --limit 0 for all)",
            named.len() - shown
        );
    }
    Ok(())
}

fn cmd_eval(a: &str, b: &str, graph_weight: f64, no_sandbox: bool, fmt: Format) -> Result<()> {
    if fmt == Format::R2 {
        bail!("r2 output is only supported for query and triage");
    }
    let ia = load_index(a, no_sandbox)?;
    let ib = load_index(b, no_sandbox)?;
    let r = eval(&ia, &ib, graph_weight);

    if fmt == Format::Json {
        return emit_json(&serde_json::json!({
            "schema_version": OUTPUT_SCHEMA_VERSION,
            "scored": r.scored,
            "rank1_acc": r.rank1_acc(),
            "recall_at_3": r.recall_at(3),
            "recall_at_5": r.recall_at(5),
            "mrr": r.mrr(),
            "precision": r.precision(),
            "recall": r.recall(),
            "abstain_rate": r.abstain_rate(),
            "tp": r.tp,
            "fp": r.fp,
            "abstained": r.abstained,
            "align_acc": r.align_acc(),
            "align_precision": r.align_precision(),
            "align_recall": r.align_recall(),
            "align_tp": r.align_tp,
            "align_fp": r.align_fp,
            "align_paired": r.align_paired,
        }));
    }

    outln!("scored {} functions (had signal + a twin in B)", r.scored);
    outln!("  rank-1 accuracy: {:.1}%", r.rank1_acc() * 100.0);
    outln!("  recall@3:        {:.1}%", r.recall_at(3) * 100.0);
    outln!("  recall@5:        {:.1}%", r.recall_at(5) * 100.0);
    outln!("  MRR:             {:.3}", r.mrr());
    outln!(
        "  precision@same:  {:.1}%  ({} tp / {} fp)",
        r.precision() * 100.0,
        r.tp,
        r.fp
    );
    outln!("  recall@same:     {:.1}%", r.recall() * 100.0);
    outln!(
        "  abstained:       {:.1}%  ({} of {} below same-threshold)",
        r.abstain_rate() * 100.0,
        r.abstained,
        r.scored
    );
    outln!(
        "aligned (1:1 + call graph, what query does; graph weight {:.2}):",
        graph_weight
    );
    outln!(
        "  aligned-acc:     {:.1}%  ({} of {} paired right)",
        r.align_acc() * 100.0,
        r.align_correct,
        r.scored
    );
    outln!(
        "  aligned-prec:    {:.1}%  ({} tp / {} fp at same-threshold)",
        r.align_precision() * 100.0,
        r.align_tp,
        r.align_fp
    );
    outln!("  aligned-recall:  {:.1}%", r.align_recall() * 100.0);
    Ok(())
}

// a cli dispatch fn: target + two corpora + two thresholds + limit + the two
// global flags. bundling them into a struct would just move the noise, so allow
// the arg count here rather than invent a one-use options type.
#[allow(clippy::too_many_arguments)]
fn cmd_triage(
    target: &str,
    vuln: &str,
    patched: &str,
    min_sim: f64,
    margin: f64,
    limit: usize,
    no_sandbox: bool,
    fmt: Format,
) -> Result<()> {
    let it = load_index(target, no_sandbox)?;
    let vdb = load_corpus(vuln, no_sandbox)?;
    let pdb = load_corpus(patched, no_sandbox)?;
    let hits = triage(&it, &vdb, &pdb, min_sim, margin)?;

    let vulns: Vec<_> = hits
        .iter()
        .filter(|h| h.verdict == Verdict::Vulnerable)
        .collect();

    if fmt == Format::Json {
        let verdict_str = |v: &Verdict| match v {
            Verdict::Vulnerable => "vulnerable",
            Verdict::Patched => "patched",
            Verdict::Inconclusive => "inconclusive",
        };
        let list: Vec<serde_json::Value> = hits
            .iter()
            .map(|h| {
                serde_json::json!({
                    "entry": format!("{:#x}", h.entry),
                    "verdict": verdict_str(&h.verdict),
                    "vuln_sim": h.vuln_sim,
                    "vuln_name": esc(&h.vuln_name),
                    "patched_sim": h.patched_sim,
                    "patched_name": esc(&h.patched_name),
                    "margin": h.margin(),
                    "coverage": h.coverage,
                })
            })
            .collect();
        return emit_json(&serde_json::json!({
            "schema_version": OUTPUT_SCHEMA_VERSION,
            "counts": {
                "vulnerable": vulns.len(),
                "patched": hits.iter().filter(|h| h.verdict == Verdict::Patched).count(),
                "inconclusive": hits.iter().filter(|h| h.verdict == Verdict::Inconclusive).count(),
            },
            "hits": list,
        }));
    }

    if fmt == Format::R2 {
        // name the vuln-leaning targets in rizin so the analyst opens them first.
        outln!("# fnprint triage: {} vuln-leaning function(s)", vulns.len());
        for h in &vulns {
            outln!("afn {} {:#x}", r2_ident(&h.vuln_name), h.entry);
        }
        return Ok(());
    }

    outln!(
        "{} functions triaged: {} look vulnerable, {} patched, {} inconclusive",
        hits.len(),
        vulns.len(),
        hits.iter()
            .filter(|h| h.verdict == Verdict::Patched)
            .count(),
        hits.iter()
            .filter(|h| h.verdict == Verdict::Inconclusive)
            .count(),
    );

    if vulns.is_empty() {
        outln!("\nno function leans vulnerable above the margin. nothing to review.");
        return Ok(());
    }
    // the review queue: strongest vulnerable lead first
    outln!("\nreview queue (vuln-leaning, strongest first):");
    outln!("   addr         vuln%  patched%  margin  cov   matches");
    let total_vulns = vulns.len();
    for h in vulns.iter().take(row_cap(limit)) {
        // advisory: flag a lead built from little observed behavior so it gets a
        // second look. not a filter, the lead still shows.
        let cov_flag = if h.coverage <= fnprint_core::LOW_COVERAGE_ADVISORY {
            "!"
        } else {
            " "
        };
        outln!(
            "   {:#010x}  {:>5.1}   {:>6.1}   {:>+5.1}  {:>3.0}%{} {} vs {}",
            h.entry,
            h.vuln_sim * 100.0,
            h.patched_sim * 100.0,
            h.margin() * 100.0,
            h.coverage * 100.0,
            cov_flag,
            esc(&h.vuln_name),
            esc(&h.patched_name),
        );
    }
    let shown = total_vulns.min(row_cap(limit));
    if shown < total_vulns {
        outln!(
            "   ... {} more (raise --limit or --limit 0 for all)",
            total_vulns - shown
        );
    }
    outln!("\ncov = fraction of the target function body microexecution observed.");
    outln!(
        "a low cov (flagged !) means the verdict rests on little behavior; give it a second look."
    );
    Ok(())
}

fn cmd_dump(binary: &str, func: &str, no_sandbox: bool, fmt: Format) -> Result<()> {
    if fmt == Format::R2 {
        bail!("r2 output is only supported for query and triage");
    }
    let bytes = read_input(binary)?;
    let lines = run_dump(&bytes, func, no_sandbox)?;
    if fmt == Format::Json {
        return emit_json(&serde_json::json!({
            "schema_version": OUTPUT_SCHEMA_VERSION,
            "func": esc(func),
            "lines": lines.iter().map(|l| esc(l)).collect::<Vec<_>>(),
        }));
    }
    for line in &lines {
        outln!("{}", esc(line));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{esc, r2_ident};

    #[test]
    fn r2_ident_strips_injection() {
        // a crafted symbol name must not be able to break out of the afn argument
        // and inject r2 commands. everything outside [A-Za-z0-9_.] becomes '_'.
        assert_eq!(r2_ident("adler32_z"), "fnp.adler32_z");
        // every char outside [A-Za-z0-9_.] (space, ;, -, /) becomes _
        assert_eq!(r2_ident("x; rm -rf /"), "fnp.x__rm__rf__");
        // no spaces, semicolons, backticks, or newlines survive
        let bad = r2_ident("a b;c`d`\ne");
        assert!(!bad.contains(' '));
        assert!(!bad.contains(';'));
        assert!(!bad.contains('`'));
        assert!(!bad.contains('\n'));
        assert!(bad.starts_with("fnp."));
    }

    #[test]
    fn shard_clamp_bounds_aggregate_memory() {
        use super::{clamp_shards_for_input, MAX_AGGREGATE_INPUT};
        // small input: the requested shard count passes through untouched
        assert_eq!(clamp_shards_for_input(8, 1024), 8);
        // zero length: no division, pass through
        assert_eq!(clamp_shards_for_input(8, 0), 8);
        // an input at half the budget allows at most 2 shards
        assert_eq!(clamp_shards_for_input(16, MAX_AGGREGATE_INPUT / 2), 2);
        // an input over the whole budget still allows 1, never 0
        assert_eq!(clamp_shards_for_input(16, MAX_AGGREGATE_INPUT + 1), 1);
    }

    #[test]
    fn read_input_rejects_non_regular_file() {
        // /dev/zero reports length 0 then streams forever; must be refused up front,
        // not read into an unbounded allocation.
        let e = super::read_input("/dev/zero")
            .err()
            .map(|e| e.to_string())
            .unwrap_or_default();
        assert!(e.contains("not a regular file"), "got: {e}");
    }

    #[test]
    fn read_input_reads_a_regular_file() {
        let mut p = std::env::temp_dir();
        p.push(format!("fnprint_ri_{}.bin", std::process::id()));
        std::fs::write(&p, b"\x7fELFhello").unwrap();
        let got = super::read_input(p.to_str().unwrap());
        let _ = std::fs::remove_file(&p);
        assert_eq!(got.unwrap(), b"\x7fELFhello");
    }

    #[test]
    fn stdout_result_maps_broken_pipe_to_quiet_marker() {
        use std::io::{Error, ErrorKind};
        assert!(super::stdout_result(Ok(())).is_ok());
        // EPIPE is the marker main() swallows into exit 0
        let closed = super::stdout_result(Err(Error::from(ErrorKind::BrokenPipe))).unwrap_err();
        assert!(closed.is::<super::StdoutClosed>());
        // anything else stays a real error
        let other =
            super::stdout_result(Err(Error::from(ErrorKind::PermissionDenied))).unwrap_err();
        assert!(!other.is::<super::StdoutClosed>());
        assert!(other.to_string().contains("writing to stdout"));
    }

    #[test]
    fn clap_command_is_valid() {
        use clap::CommandFactory;
        // catches a malformed clap derive (duplicate arg, bad default) at test time
        // instead of only at first run. also exercises the CommandFactory path the
        // completions generator relies on.
        super::Cli::command().debug_assert();
    }

    #[test]
    fn completions_generate_for_every_shell() {
        use clap::CommandFactory;
        use clap_complete::Shell;
        // generating a script for each supported shell must produce non-empty
        // output and never panic.
        for shell in [
            Shell::Bash,
            Shell::Zsh,
            Shell::Fish,
            Shell::PowerShell,
            Shell::Elvish,
        ] {
            let mut cmd = super::Cli::command();
            let mut out = Vec::new();
            clap_complete::generate(shell, &mut cmd, "fnprint", &mut out);
            assert!(!out.is_empty(), "empty completion script for {shell:?}");
        }
    }

    #[test]
    fn esc_defangs_terminal_escapes() {
        // an ansi color escape in a crafted symbol name must not survive: the
        // ESC byte becomes literal text so the terminal can't interpret it
        assert_eq!(esc("foo\x1b[31mbar"), "foo\\x1b[31mbar");
        // newline / carriage return escaped so a name can't spoof lines
        assert_eq!(esc("a\nb\r"), "a\\x0ab\\x0d");
        // plain ascii names pass through unchanged
        assert_eq!(esc("adler32_z"), "adler32_z");
        // non-ascii bytes escaped per byte
        assert_eq!(esc("é"), "\\xc3\\xa9");
    }
}