oinkie 0.7.0

Detects software theft by comparing birthmarks extracted from binaries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
use std::path::Path;

use rustc_hash::FxHashMap;

use crate::birthmarks::{Birthmark, BirthmarkType, Data, Elements, Kgram, Metadata};
use crate::program::{Function, Program};
use crate::{Error, Iterable, Result};

/// Number of hex characters kept from the SHA-256 digest. 16 characters
/// is 64 bits, which puts the birthday bound around 5 billion files;
/// 8 characters (32 bits) collided at roughly 77,000.
const HASH_PREFIX_LEN: usize = 16;

/// Generates the file name for the extracted birthmark JSON file.
/// The format of resultant file name is `{original_file_stem}_{hash}.json`,
/// where `original_file_stem` is the stem of the input source file and
/// `hash` is a hash value generated from the content of the source file
/// to ensure uniqueness and avoid overwriting files with the same name.
pub fn dest_file_name(program_path: &Path) -> Result<String> {
    let file_name = program_path
        .file_stem()
        .ok_or_else(|| {
            Error::Parse(format!(
                "{}: cannot determine the file stem",
                program_path.display()
            ))
        })?
        .to_string_lossy();
    let hash = get_hash(program_path);
    let new_filename = format!("{file_name}_{}.json", hash?);
    Ok(new_filename)
}

fn get_hash(path: &Path) -> Result<String> {
    use sha2::Digest;
    use std::io::{Read, Seek};
    let pbuf = path.to_path_buf();

    let mut file = std::fs::File::open(path).map_err(|e| Error::Io(pbuf.clone(), e))?;
    let len = file
        .metadata()
        .map_err(|e| Error::Io(pbuf.clone(), e))?
        .len();

    let mut hasher = sha2::Sha256::new();
    // the file length participates in the hash so that same-prefix/suffix
    // files of different sizes never collide
    hasher.update(len.to_le_bytes());

    // Read the first 4KB of the file for hashing
    let mut head = vec![0; 4096.min(len as usize)];
    file.read_exact(&mut head)
        .map_err(|e| Error::Io(pbuf.clone(), e))?;
    hasher.update(&head);

    if len > 4096 {
        // Read the last (up to) 4KB of the file, without overlapping the head
        let tail_len = 4096.min(len as usize - 4096);
        let mut tail = vec![0; tail_len];
        file.seek(std::io::SeekFrom::End(-(tail_len as i64)))
            .map_err(|e| Error::Io(pbuf.clone(), e))?;
        file.read_exact(&mut tail)
            .map_err(|e| Error::Io(pbuf.clone(), e))?;
        hasher.update(&tail);
    }
    let hash = hasher.finalize();
    // Written out rather than `format!("{:x}")`: sha2 0.11 returns an
    // `Output` that does not implement `LowerHex`. Only the prefix is kept, so
    // only that many bytes are rendered.
    Ok(hash
        .iter()
        .take(HASH_PREFIX_LEN.div_ceil(2))
        .map(|b| format!("{b:02x}"))
        .collect::<String>()[..HASH_PREFIX_LEN]
        .to_string())
}

pub struct Extractor {
    bt: BirthmarkType,
}

impl Extractor {
    pub fn new(bt: BirthmarkType) -> Self {
        Self { bt }
    }

    pub fn extract<T: crate::Op>(&self, args: Vec<&Program<T>>) -> Result<Vec<Birthmark>> {
        let result = args
            .iter()
            .map(|p| extract_birthmark_op(p, &self.bt))
            .collect::<Vec<_>>();
        Error::vec_result_to_result_vec(result)
    }

    pub fn extract_each<T: crate::Op>(&self, p: &Program<T>) -> Result<Birthmark> {
        extract_birthmark_op(p, &self.bt)
    }

    /// Extracts from a program read without naming its operation type.
    ///
    /// The birthmark is the same either way; this only spares the caller from
    /// deciding which lifter produced the file, which the file already says.
    pub fn extract_any(&self, p: &crate::program::AnyProgram) -> Result<Birthmark> {
        use crate::program::AnyProgram;
        match p {
            AnyProgram::GhidraPcode(p) => self.extract_each(p),
            AnyProgram::BinaryNinjaLlil(p) => self.extract_each(p),
            AnyProgram::BinaryNinjaMlil(p) => self.extract_each(p),
            AnyProgram::BinaryNinjaHlil(p) => self.extract_each(p),
            AnyProgram::IdaMicrocode(p) => self.extract_each(p),
        }
    }
}

fn extract_birthmark_op<T: crate::Op>(p: &Program<T>, bt: &BirthmarkType) -> Result<Birthmark> {
    let now = std::time::Instant::now();
    // An empty fc-* birthmark is a measurement, not a failure: a program that
    // calls nothing is a program that calls nothing, and the family simply does
    // not distinguish it. Said rather than refused, because the two empty
    // birthmarks it produces will score 1.0 against each other and the reader
    // should know which of those two things they are looking at.
    if matches!(
        bt,
        BirthmarkType::FcSeq | BirthmarkType::FcSet | BirthmarkType::FcFreq
    ) && let Some(reason) = empty_family(p)
    {
        log::warn!("{}", reason.message(p.path(), p.ir()));
    }
    let elements = p
        .iter()
        .map(|f| {
            let name = f.name().to_string();
            let data = match bt {
                BirthmarkType::FcFreq => Data::Freq(extract_function_calls_freq(f, p)),
                BirthmarkType::FcSet => {
                    Data::Set(extract_function_calls_freq(f, p).into_keys().collect())
                }
                BirthmarkType::FcSeq => Data::Seq(extract_function_calls(f, p)),
                BirthmarkType::OpFreq => Data::Freq(f.ops_freq()),
                BirthmarkType::OpSet => Data::Set(f.ops_freq().into_keys().collect()),
                BirthmarkType::OpSeq => Data::Seq(f.ops().map(|s| s.into()).collect()),
                BirthmarkType::OpKgramSeq(k) => Data::KgramSeq(extract_op_kgram_seq(f, *k)),
                BirthmarkType::OpKgramFreq(k) => Data::KgramFreq(extract_op_kgram_freq(f, *k)),
                BirthmarkType::OpKgramSet(k) => {
                    Data::KgramSet(extract_op_kgram_seq(f, *k).into_iter().collect())
                }
            };
            Elements { name, data }
        })
        .collect::<Vec<_>>();
    let metadata = build_metadata(p, bt.clone(), now);
    Ok(Birthmark {
        metadata,
        elements,
        json_path: None,
    })
}

fn build_metadata<T>(
    p: &Program<T>,
    bt: BirthmarkType,
    start_time: std::time::Instant,
) -> Metadata {
    let extracted_at = chrono::Utc::now();
    let duration = start_time.elapsed();
    let path = p.path().to_path_buf();
    let name = path
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string();
    Metadata {
        file_name: name,
        path,
        extracted_at,
        duration,
        birthmark_type: bt,
        ir: p.ir(),
    }
}

fn extract_op_kgram_seq<T: crate::Op>(f: &Function<T>, k: usize) -> Vec<Kgram> {
    f.ops()
        .map(|s| s.into())
        .collect::<Vec<_>>()
        .windows(k)
        .map(|w| Kgram::new(w.to_vec()))
        .collect()
}

fn extract_op_kgram_freq<T: crate::Op>(f: &Function<T>, k: usize) -> FxHashMap<Kgram, usize> {
    seq_to_freq(extract_op_kgram_seq(f, k).into_iter())
}

pub(crate) fn seq_to_freq<T>(seq: impl Iterator<Item = T>) -> FxHashMap<T, usize>
where
    T: std::hash::Hash + Eq,
{
    seq.into_iter().fold(FxHashMap::default(), |mut acc, item| {
        *acc.entry(item).or_insert(0) += 1;
        acc
    })
}

/// Why every `fc-*` birthmark of a program would be empty, or `None` when one
/// of them would not be.
///
/// Returned rather than logged so that the decision can be tested without a
/// logger, and so that the caller owns how loudly it is said.
///
/// The two cases are kept apart because they send the reader somewhere else.
/// Nothing being a call is `is_call`; calls that resolve to nothing is the
/// symbol table or `symbol_key`. Both were reached by a real lifter during
/// v0.6.0 -- the Hex-Rays microcode writes a global as `$name` and the table
/// was keyed by the resolved name, and the optimiser folds a call into another
/// instruction's operand, which a reader walking only the block's list misses.
#[derive(Debug, PartialEq, Eq)]
enum EmptyFamily {
    /// No operation in the program is a call.
    NoCalls,
    /// There are calls, and none of them names anything the symbol table holds.
    NoneResolve(usize),
}

impl EmptyFamily {
    fn message(&self, path: &std::path::Path, ir: crate::lift::Ir) -> String {
        let path = path.display();
        match self {
            Self::NoCalls => format!(
                "{path}: no operation is a call, so every fc-* birthmark of it is empty -- and \
                 two empty birthmarks score as a perfect match. Either the program really calls \
                 nothing, or oinkie's reader for {ir} does not recognise that representation's \
                 call operations"
            ),
            Self::NoneResolve(calls) => format!(
                "{path}: calls were found ({calls} in total), but none of them names anything in \
                 the symbol table, so every fc-* birthmark of it is empty -- and two empty \
                 birthmarks score as a perfect match. Either every call is indirect, or oinkie's \
                 reader for {ir} keys the symbol table differently from the way that \
                 representation renders a callee"
            ),
        }
    }
}

/// Decides which, if either, applies.
///
/// One pass, returning at the first call that resolves. The count is only read
/// when none did, and reaching that answer means the whole program was walked
/// anyway -- so counting here costs an extraction that has calls nothing, where
/// counting first cost it a full traversal for a number it threw away.
fn empty_family<T: crate::Op>(p: &Program<T>) -> Option<EmptyFamily> {
    let mut calls = 0usize;
    for function in p.iter() {
        for op in function.iter() {
            if !op.is_call() {
                continue;
            }
            calls += 1;
            if op.symbol_key().and_then(|key| p.symbol(&key)).is_some() {
                return None;
            }
        }
    }
    Some(if calls == 0 {
        EmptyFamily::NoCalls
    } else {
        EmptyFamily::NoneResolve(calls)
    })
}

fn extract_function_calls<T: crate::Op>(f: &Function<T>, p: &Program<T>) -> Vec<String> {
    f.iter()
        .filter(|op| op.is_call())
        .filter_map(|op| op.symbol_key())
        .filter_map(|key| p.symbol(&key))
        .map(|s| s.to_string())
        .collect()
}

fn extract_function_calls_freq<T: crate::Op>(
    f: &Function<T>,
    p: &Program<T>,
) -> FxHashMap<String, usize> {
    extract_function_calls(f, p)
        .into_iter()
        .fold(FxHashMap::default(), |mut acc, call| {
            *acc.entry(call).or_insert(0) += 1;
            acc
        })
}

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

    /// A program whose calls resolve to nothing, written by hand rather than
    /// lifted: the reader does not care where the JSON came from, and no real
    /// binary is needed to describe a call through a register.
    fn a_program_whose_calls_resolve_to_nothing() -> crate::program::AnyProgram {
        let dir = tempdir().unwrap();
        let path = dir.path().join("indirect.json");
        // CALLIND is a call, and `symbol_key` yields nothing for one: its
        // target lives in a register, resolved at run time.
        std::fs::write(
            &path,
            r#"{"program":"indirect","path":"bin/indirect","ir":"ghidra-pcode",
                "symbols":{"0x1000": "_printf"},
                "functions":[{"name":"main","ops":[
                  {"op":"CALLIND","inputs":["(register, 0x20, 8)"]},
                  {"op":"CALLIND","inputs":["(register, 0x28, 8)"]}]}]}"#,
        )
        .unwrap();
        crate::program::AnyProgram::load(&path).unwrap()
    }

    /// An empty family is returned rather than refused. A program that calls
    /// nothing is a program that calls nothing, and `fc-*` simply does not
    /// distinguish it -- which is a property of the measure, not a failure.
    #[test]
    fn test_calls_that_resolve_to_nothing_give_an_empty_birthmark() {
        let p = a_program_whose_calls_resolve_to_nothing();
        for bt in ["fc-set", "fc-seq", "fc-freq"] {
            let b = Extractor::new(BirthmarkType::try_from(bt).unwrap())
                .extract_any(&p)
                .unwrap_or_else(|e| panic!("{bt} was refused: {e}"));
            assert_eq!(b.len(), 1, "{bt}: one function was expected");
            let calls: Vec<String> = b.iter().flat_map(|e| e.ops().map(String::from)).collect();
            assert!(calls.is_empty(), "{bt}: expected nothing, got {calls:?}");
        }
    }

    /// One program that cannot answer does not stop the others.
    ///
    /// It used to: the refusal was an `Err`, and a corpus with a single
    /// call-less binary in it lost every birthmark after that one.
    #[test]
    fn test_a_program_that_calls_nothing_does_not_stop_the_rest() {
        let dir = tempdir().unwrap();
        let mut programs = Vec::new();
        for (name, ops) in [
            ("calls", r#"{"op":"CALL","inputs":["(ram, 0x1000, 8)"]}"#),
            (
                "pure",
                r#"{"op":"COPY","out":"(register, 0x0, 8)","inputs":["(const, 0x1, 8)"]}"#,
            ),
            (
                "calls_too",
                r#"{"op":"CALL","inputs":["(ram, 0x1000, 8)"]}"#,
            ),
        ] {
            let path = dir.path().join(format!("{name}.json"));
            std::fs::write(
                &path,
                format!(
                    r#"{{"program":"{name}","path":"bin/{name}","ir":"ghidra-pcode",
                        "symbols":{{"0x1000":"_printf"}},
                        "functions":[{{"name":"main","ops":[{ops}]}}]}}"#
                ),
            )
            .unwrap();
            programs.push(crate::program::AnyProgram::load(&path).unwrap());
        }
        let extractor = Extractor::new(BirthmarkType::try_from("fc-set").unwrap());
        let sizes: Vec<usize> = programs
            .iter()
            .map(|p| {
                extractor
                    .extract_any(p)
                    .unwrap_or_else(|e| panic!("{e}"))
                    .iter()
                    .flat_map(|e| e.ops())
                    .count()
            })
            .collect();
        assert_eq!(
            sizes,
            vec![1, 0, 1],
            "the middle one should be empty, not fatal"
        );
    }

    /// Which of the two emptied the family, and that neither fires when one
    /// call resolves.
    ///
    /// This is the part worth keeping from the old refusal: the two send the
    /// reader somewhere else, and both were reached by a real lifter during
    /// v0.6.0.
    #[test]
    fn test_the_two_ways_of_emptying_a_family_are_told_apart() {
        let unresolved = a_program_whose_calls_resolve_to_nothing();
        assert!(matches!(
            any_empty_family(&unresolved),
            Some(EmptyFamily::NoneResolve(2))
        ));

        let dir = tempdir().unwrap();
        let path = dir.path().join("callless.json");
        std::fs::write(
            &path,
            r#"{"program":"callless","path":"bin/callless","ir":"ghidra-pcode",
                "symbols":{},
                "functions":[{"name":"main","ops":[
                  {"op":"COPY","out":"(register, 0x0, 8)","inputs":["(const, 0x1, 8)"]}]}]}"#,
        )
        .unwrap();
        let callless = crate::program::AnyProgram::load(&path).unwrap();
        assert_eq!(any_empty_family(&callless), Some(EmptyFamily::NoCalls));

        let fine = crate::program::AnyProgram::load(std::path::Path::new(
            "testdata/lifted/pcodes/hello_clang.json",
        ))
        .unwrap();
        assert_eq!(any_empty_family(&fine), None);
    }

    /// The messages say which case they are, and name the file and the
    /// representation -- the two things that tell a lifter bug from a program
    /// that really calls nothing.
    #[test]
    fn test_each_message_names_the_file_the_representation_and_the_cause() {
        let path = std::path::Path::new("bin/sample");
        let ir = crate::lift::Ir::GhidraPcode;

        let none = EmptyFamily::NoCalls.message(path, ir);
        assert!(
            none.contains("bin/sample") && none.contains("ghidra-pcode"),
            "{none}"
        );
        assert!(none.contains("no operation is a call"), "{none}");

        let some = EmptyFamily::NoneResolve(1).message(path, ir);
        assert!(some.contains("symbol table"), "{some}");
        assert!(
            !some.contains("1 operations"),
            "reads as a plural for one: {some}"
        );
        assert!(some.contains("(1 in total)"), "{some}");
    }

    /// `empty_family` is generic over the operation type, and the tests hold an
    /// `AnyProgram`. This is the one place that has to know which it is.
    fn any_empty_family(p: &crate::program::AnyProgram) -> Option<EmptyFamily> {
        match p {
            crate::program::AnyProgram::GhidraPcode(p) => empty_family(p),
            _ => unreachable!("the fixtures here are all P-Code"),
        }
    }

    /// The op-* families say nothing about calls, so neither warning applies
    /// to them. A program of unresolvable calls still has operations.
    #[test]
    fn test_the_op_families_are_not_refused_for_unresolvable_calls() {
        let p = a_program_whose_calls_resolve_to_nothing();
        let b = Extractor::new(BirthmarkType::try_from("op-set").unwrap())
            .extract_any(&p)
            .expect("op-set does not depend on symbols");
        assert_eq!(b.len(), 1);
    }

    use std::io::Write;
    use tempfile::tempdir;

    #[test]
    fn test_dest_file_name_small_file() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("small_test.txt");
        let mut file = std::fs::File::create(&file_path).unwrap();
        file.write_all(b"hello world").unwrap();

        let name = dest_file_name(&file_path).unwrap();
        assert!(name.starts_with("small_test_"));
        assert!(name.ends_with(".json"));
    }

    #[test]
    fn test_dest_file_name_large_file() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("large_test.txt");
        let mut file = std::fs::File::create(&file_path).unwrap();

        // Write 10KB of data
        let data = vec![0u8; 10240];
        file.write_all(&data).unwrap();

        let name = dest_file_name(&file_path).unwrap();
        assert!(name.starts_with("large_test_"));
        assert!(name.ends_with(".json"));
    }

    #[test]
    fn test_get_hash_reflects_tail_difference() {
        // Two files sharing the same first 4KB but differing after it must
        // yield different hashes; otherwise their birthmark files collide.
        let dir = tempdir().unwrap();
        let path1 = dir.path().join("a.bin");
        let path2 = dir.path().join("b.bin");
        let mut data1 = vec![0u8; 5000];
        let mut data2 = vec![0u8; 5000];
        data1[4500] = 1;
        data2[4500] = 2;
        std::fs::write(&path1, &data1).unwrap();
        std::fs::write(&path2, &data2).unwrap();
        assert_ne!(get_hash(&path1).unwrap(), get_hash(&path2).unwrap());
    }

    /// The exact hash of a known input.
    ///
    /// The other hash tests say it is deterministic, that different bytes give
    /// different answers, that it is sixteen hexadecimal characters. All of
    /// those pass if the bytes come out reversed, or upper-cased, or from a
    /// different slice of the digest -- and any of those renames every
    /// birthmark ever written, which silently defeats `--skip` and orphans a
    /// directory of results.
    ///
    /// sha2 0.11 is what made that a live question: its `Output` does not
    /// implement `LowerHex`, so the hex is written out here rather than by the
    /// formatter. This is the assertion that says the rewrite kept the answer.
    ///
    /// The expected value was computed outside this crate, by hashing the same
    /// bytes with Python's hashlib, so it is not this implementation agreeing
    /// with itself.
    #[test]
    fn test_get_hash_of_a_known_input_is_exactly_this() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("fixture.txt");
        std::fs::write(&path, b"oinkie hash fixture\n").unwrap();
        assert_eq!(get_hash(&path).unwrap(), "1a22831efd6c8d6e");
    }

    #[test]
    fn test_get_hash_is_deterministic() {
        let dir = tempdir().unwrap();
        let path1 = dir.path().join("a.bin");
        let path2 = dir.path().join("b.bin");
        let data = vec![7u8; 10240];
        std::fs::write(&path1, &data).unwrap();
        std::fs::write(&path2, &data).unwrap();
        assert_eq!(get_hash(&path1).unwrap(), get_hash(&path2).unwrap());
    }

    #[test]
    fn test_get_hash_io_error() {
        // Test with a non-existent file
        let path = Path::new("non_existent_file.xyz");
        let result = get_hash(path);
        assert!(result.is_err());
    }

    /// The fc-* family is built from the symbols a function calls. The call
    /// operand names its target in the lifter's own notation, which is not the
    /// form the symbol table is keyed by, so the two have to be reconciled
    /// before the lookup — otherwise every call is discarded and the birthmark
    /// comes out empty.
    #[test]
    fn test_extract_function_calls_resolves_the_symbol() {
        let program: Program<crate::ghidra::Op> =
            std::path::Path::new("testdata/lifted/pcodes/hello_clang.json")
                .try_into()
                .expect("failed to load the fixture");
        let function = program.iter().next().expect("fixture has no function");

        let calls = extract_function_calls(function, &program);
        assert_eq!(
            calls,
            vec!["_printf".to_string()],
            "the fixture calls _printf exactly once"
        );
    }

    /// Two empty sets are identical, so an fc-* birthmark that resolves nothing
    /// makes unrelated programs look like a perfect match. Guard the property
    /// that makes the emptiness dangerous, not just the emptiness.
    #[test]
    fn test_fc_birthmarks_are_not_empty() {
        for fixture in [
            "testdata/lifted/pcodes/hello_clang.json",
            "testdata/lifted/pcodes/hello_gcc.json",
        ] {
            let program: Program<crate::ghidra::Op> = std::path::Path::new(fixture)
                .try_into()
                .unwrap_or_else(|e| panic!("{fixture}: {e}"));
            let birthmark = Extractor::new(BirthmarkType::FcSet)
                .extract_each(&program)
                .unwrap_or_else(|e| panic!("{fixture}: {e}"));
            assert!(
                birthmark.elements.iter().any(|e| !e.is_empty()),
                "{fixture}: every fc-set element is empty"
            );
        }
    }

    /// A leaf function calls nothing, so its fc-* birthmark is empty. That is
    /// the measurement, and it is handed back.
    ///
    /// It used to be refused. Two empty birthmarks score as a perfect match,
    /// and in a theft-detection tool that reads as a positive -- but the answer
    /// to that is to say so, not to decide on the caller's behalf that the
    /// question cannot be asked. `empty_family` is what says so.
    #[test]
    fn test_fc_extraction_of_a_program_without_calls_is_empty_not_refused() {
        let json = r#"{
            "program": "callless",
            "path": "bin/callless",
            "ir": "ghidra-pcode",
            "symbols": {"0x100000480": "_printf"},
            "functions": [
                {"name": "leaf", "ops": [
                    {"op": "COPY", "out": "(register, 0x4000, 8)", "inputs": ["(const, 0x0, 8)"]},
                    {"op": "RETURN", "inputs": ["(const, 0x0, 8)"]}
                ]}
            ]
        }"#;
        let program: Program<crate::ghidra::Op> = serde_json::from_str(json).unwrap();

        for bt in [
            BirthmarkType::FcSeq,
            BirthmarkType::FcSet,
            BirthmarkType::FcFreq,
        ] {
            let b = Extractor::new(bt.clone())
                .extract_each(&program)
                .unwrap_or_else(|e| panic!("{bt} was refused: {e}"));
            assert!(
                b.iter().flat_map(|e| e.ops()).next().is_none(),
                "{bt}: a leaf function calls nothing, so this should be empty"
            );
        }
    }

    /// The op-* families do not read calls at all, so the refusal above must
    /// not spread to them.
    #[test]
    fn test_op_extraction_accepts_a_program_without_calls() {
        let json = r#"{
            "program": "callless",
            "path": "bin/callless",
            "symbols": {},
            "functions": [
                {"name": "leaf", "ops": [
                    {"op": "RETURN", "inputs": ["(const, 0x0, 8)"]}
                ]}
            ]
        }"#;
        let program: Program<crate::ghidra::Op> = serde_json::from_str(json).unwrap();
        assert!(
            Extractor::new(BirthmarkType::OpSeq)
                .extract_each(&program)
                .is_ok()
        );
    }

    #[test]
    fn test_extractor_extract_multiple() {
        // We'll just test that Extractor::extract doesn't panic on empty input
        let extractor = Extractor::new(BirthmarkType::OpSeq);
        // Create dummy programs if possible, or just pass empty vec
        // We cannot easily create a Program here without parsing JSON, but passing empty vec works to cover line 58.
        let empty_args: Vec<&crate::program::Program<crate::ghidra::Op>> = vec![];
        let result = extractor.extract(empty_args);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    /// Pins the generated file-name layout: `{stem}_{hash}.json` with the
    /// digest truncated to a fixed width. The strip_prefix/strip_suffix pair
    /// fails if the layout changes, and the length is checked against a
    /// literal rather than HASH_PREFIX_LEN so that widening the prefix trips
    /// this test — changing it renames every birthmark file and breaks
    /// `--skip` against existing directories, which should never happen
    /// silently.
    #[test]
    fn test_dest_file_name_hash_length() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("sample.bin");
        std::fs::write(&file_path, b"contents").unwrap();

        let name = dest_file_name(&file_path).unwrap();
        let hash = name
            .strip_prefix("sample_")
            .and_then(|s| s.strip_suffix(".json"))
            .expect("unexpected file name layout");
        assert_eq!(hash.len(), 16);
        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
    }
}