rch-common 1.0.26

Shared types and utilities for Remote Compilation Helper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! Binary hash computation utility for verifying remote compilation correctness.
//!
//! This module provides deterministic hashing of compiled binaries by focusing on
//! code sections (.text, .rodata) while ignoring non-deterministic metadata like
//! timestamps and paths.

use anyhow::{Context, Result, anyhow};
use blake3::Hasher;
use object::read::macho::{FatArch, MachOFatFile32, MachOFatFile64};
use object::{Architecture, Object, ObjectSection};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
use tracing::info;

/// Result of computing hashes for a binary file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryHashResult {
    /// Hash of the entire binary file (includes non-deterministic elements).
    pub full_hash: String,
    /// Hash of only code sections (.text, .rodata) - deterministic across builds.
    pub code_hash: String,
    /// Size of the .text section in bytes.
    pub text_section_size: u64,
    /// Whether the binary contains debug information.
    pub is_debug: bool,
}

/// Compute hash of the entire binary file using BLAKE3.
///
/// This hash includes all non-deterministic elements (timestamps, paths, etc.)
/// and will differ between builds even of identical source code.
fn compute_full_hash(path: &Path) -> Result<String> {
    let file = File::open(path).with_context(|| format!("Failed to open binary: {:?}", path))?;
    let mut reader = BufReader::new(file);
    let mut hasher = Hasher::new();
    let mut buffer = [0u8; 65536];

    loop {
        let bytes_read = reader.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        hasher.update(&buffer[..bytes_read]);
    }

    Ok(hasher.finalize().to_hex().to_string())
}

/// Get the current architecture for selecting the right slice from a fat binary.
#[cfg(target_arch = "x86_64")]
fn native_architecture() -> Architecture {
    Architecture::X86_64
}

#[cfg(target_arch = "aarch64")]
fn native_architecture() -> Architecture {
    Architecture::Aarch64
}

#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
fn native_architecture() -> Architecture {
    Architecture::Unknown
}

/// Try to extract a slice from a fat binary using the given arch list.
fn try_extract_from_fat<'a, F: FatArch>(
    data: &'a [u8],
    arches: &[F],
    native_arch: Architecture,
) -> Option<&'a [u8]> {
    // First try to find a slice matching our native architecture
    for arch in arches {
        if arch.architecture() == native_arch
            && let Ok(slice) = arch.data(data)
        {
            info!("Extracted {:?} slice from fat binary", native_arch);
            return Some(slice);
        }
    }

    // No exact match found, use the first valid slice
    if let Some(arch) = arches.first()
        && let Ok(slice) = arch.data(data)
    {
        info!("Using first available slice from fat binary");
        return Some(slice);
    }

    None
}

/// Extract the appropriate binary slice from a fat/universal binary.
///
/// macOS universal binaries (fat binaries) contain multiple architecture slices.
/// This function extracts the slice matching the current native architecture,
/// or the first available slice if no exact match is found.
///
/// For non-fat binaries, returns the original data unchanged.
fn extract_binary_slice(data: &[u8]) -> Result<&[u8]> {
    // Try parsing as 32-bit fat binary first (more common)
    if let Ok(fat) = MachOFatFile32::parse(data) {
        let arches = fat.arches();
        if arches.is_empty() {
            return Err(anyhow!("Fat binary contains no architecture slices"));
        }

        let native_arch = native_architecture();
        if let Some(slice) = try_extract_from_fat(data, arches, native_arch) {
            return Ok(slice);
        }
        return Err(anyhow!("Failed to extract any valid slice from fat binary"));
    }

    // Try parsing as 64-bit fat binary
    if let Ok(fat) = MachOFatFile64::parse(data) {
        let arches = fat.arches();
        if arches.is_empty() {
            return Err(anyhow!("Fat64 binary contains no architecture slices"));
        }

        let native_arch = native_architecture();
        if let Some(slice) = try_extract_from_fat(data, arches, native_arch) {
            return Ok(slice);
        }
        return Err(anyhow!(
            "Failed to extract any valid slice from fat64 binary"
        ));
    }

    // Not a fat binary, return as-is
    Ok(data)
}

/// Check if a section name represents code or read-only data.
///
/// Supports both ELF (.text, .rodata) and Mach-O (__text, __const) section names.
fn is_code_section(name: &str) -> bool {
    // ELF section names
    name == ".text"
        || name == ".rodata"
        || name.starts_with(".text.")
        || name.starts_with(".rodata.")
        // Mach-O section names (lowercase, within __TEXT segment)
        || name == "__text"
        || name == "__const"
        || name == "__cstring"
        || name == "__stubs"
        || name == "__stub_helper"
}

/// Compute hash of code sections only using BLAKE3.
///
/// This hash focuses on executable code and read-only data sections,
/// ignoring non-deterministic metadata. This provides a more reliable
/// comparison between builds of the same source code.
///
/// Supports both ELF (Linux) and Mach-O (macOS) binary formats,
/// including macOS universal (fat) binaries.
fn compute_code_hash(data: &[u8]) -> Result<String> {
    // Handle fat/universal binaries by extracting the appropriate slice
    let binary_data = extract_binary_slice(data)?;
    let file = object::File::parse(binary_data).context("Failed to parse binary format")?;
    let mut hasher = Hasher::new();
    let mut sections_hashed = 0;

    // Hash only executable code and read-only data sections
    for section in file.sections() {
        let name = section.name().unwrap_or("");

        // Include code sections from both ELF and Mach-O formats
        if is_code_section(name)
            && let Ok(section_data) = section.data()
        {
            hasher.update(section_data);
            sections_hashed += 1;
        }
    }

    if sections_hashed == 0 {
        return Err(anyhow!("No code sections found in binary"));
    }

    Ok(hasher.finalize().to_hex().to_string())
}

/// Check if a section name represents the main text/code section.
fn is_text_section(name: &str) -> bool {
    // ELF and Mach-O text sections
    name == ".text" || name == "__text"
}

/// Check if a section name represents debug information.
fn is_debug_section(name: &str) -> bool {
    // ELF debug sections
    name.starts_with(".debug")
        // Mach-O debug sections (DWARF)
        || name.starts_with("__debug")
        || name == "__DWARF"
}

/// Extract metadata about the binary.
///
/// Returns (text_section_size, has_debug_info).
/// Supports both ELF (Linux) and Mach-O (macOS) binary formats,
/// including macOS universal (fat) binaries.
fn extract_metadata(data: &[u8]) -> Result<(u64, bool)> {
    // Handle fat/universal binaries by extracting the appropriate slice
    let binary_data = extract_binary_slice(data)?;
    let file = object::File::parse(binary_data).context("Failed to parse binary for metadata")?;

    let text_size: u64 = file
        .sections()
        .filter(|s| is_text_section(s.name().unwrap_or("")))
        .map(|s| s.size())
        .sum();

    let has_debug = file
        .sections()
        .any(|s| is_debug_section(s.name().unwrap_or("")));

    Ok((text_size, has_debug))
}

/// Compute comprehensive hash information for a binary file.
///
/// This function returns both a full file hash and a deterministic code hash
/// that can be used to verify remote compilation correctness.
///
/// # Arguments
/// * `path` - Path to the binary file
///
/// # Returns
/// A `BinaryHashResult` containing:
/// - `full_hash`: Complete file hash (non-deterministic)
/// - `code_hash`: Hash of code sections only (deterministic)
/// - `text_section_size`: Size of executable code
/// - `is_debug`: Whether debug symbols are present
pub fn compute_binary_hash(path: &Path) -> Result<BinaryHashResult> {
    info!("Computing binary hash for {:?}", path);

    // Compute full file hash
    let full_hash = compute_full_hash(path)?;
    info!("Full hash computed: {}", &full_hash[..16]);

    // Read file for section analysis
    let data = std::fs::read(path).with_context(|| format!("Failed to read binary: {:?}", path))?;

    // Compute code-only hash
    let code_hash = compute_code_hash(&data)?;
    info!("Code hash computed: {}", &code_hash[..16]);

    // Extract metadata
    let (text_section_size, is_debug) = extract_metadata(&data)?;
    info!(
        "Metadata: text_size={}, is_debug={}",
        text_section_size, is_debug
    );

    Ok(BinaryHashResult {
        full_hash,
        code_hash,
        text_section_size,
        is_debug,
    })
}

/// Check if a binary contains a specific marker string.
///
/// This is used to verify that the remote worker actually compiled the code
/// by checking for a unique test marker that was added to the source.
///
/// # Arguments
/// * `path` - Path to the binary file
/// * `marker` - The marker string to search for
///
/// # Returns
/// `true` if the marker is found in the binary's string data
pub fn binary_contains_marker(path: &Path, marker: &str) -> Result<bool> {
    info!("Searching for marker '{}' in {:?}", marker, path);

    // Empty marker is trivially contained in any file (consistent with str::contains(""))
    if marker.is_empty() {
        return Ok(true);
    }

    let data = std::fs::read(path).with_context(|| format!("Failed to read binary: {:?}", path))?;

    // Search for the marker in the raw binary data
    // The marker should appear as a string literal in .rodata or similar sections
    let marker_bytes = marker.as_bytes();
    let contains = data
        .windows(marker_bytes.len())
        .any(|window| window == marker_bytes);

    info!("Marker search result: found={}", contains);
    Ok(contains)
}

/// Compare two binaries for functional equivalence.
///
/// Two binaries are considered equivalent if they have:
/// - Matching code hashes (same executable code)
/// - Matching text section sizes
/// - Matching debug status
///
/// The full hash may differ due to timestamps and paths, so it is not used
/// for equivalence checking.
///
/// # Arguments
/// * `local` - Hash result from local build
/// * `remote` - Hash result from remote build
///
/// # Returns
/// `true` if the binaries are functionally equivalent
pub fn binaries_equivalent(local: &BinaryHashResult, remote: &BinaryHashResult) -> bool {
    // Code hash must match exactly
    if local.code_hash != remote.code_hash {
        info!(
            "Code hash mismatch: local={}, remote={}",
            &local.code_hash[..local.code_hash.len().min(16)],
            &remote.code_hash[..remote.code_hash.len().min(16)]
        );
        return false;
    }

    // Text section size should match
    if local.text_section_size != remote.text_section_size {
        info!(
            "Text section size mismatch: local={}, remote={}",
            local.text_section_size, remote.text_section_size
        );
        return false;
    }

    // Debug status should match
    if local.is_debug != remote.is_debug {
        info!(
            "Debug status mismatch: local={}, remote={}",
            local.is_debug, remote.is_debug
        );
        return false;
    }

    true
}

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

    fn init_test_logging() {
        let _ = tracing_subscriber::fmt()
            .with_test_writer()
            .with_max_level(tracing::Level::INFO)
            .try_init();
    }

    /// Find a binary in the project for testing
    fn find_test_binary() -> Option<PathBuf> {
        // Try release binary first, then debug
        let candidates = [
            "target/release/rch",
            "target/debug/rch",
            "target/release/rchd",
            "target/debug/rchd",
            "/bin/ls",  // Fallback to system binary
            "/bin/cat", // Another fallback
            "/usr/bin/ls",
        ];

        for candidate in candidates {
            let path = PathBuf::from(candidate);
            if path.exists() {
                return Some(path);
            }
        }
        None
    }

    #[test]
    fn test_hash_same_binary_twice() {
        init_test_logging();
        info!("TEST START: test_hash_same_binary_twice");

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => {
                info!("SKIP: No test binary found");
                return;
            }
        };

        info!("INPUT: compute_binary_hash({:?}) twice", binary_path);

        let hash1 = compute_binary_hash(&binary_path).unwrap();
        let hash2 = compute_binary_hash(&binary_path).unwrap();

        info!(
            "RESULT: hash1.code_hash={}, hash2.code_hash={}",
            &hash1.code_hash[..16],
            &hash2.code_hash[..16]
        );

        assert_eq!(hash1.code_hash, hash2.code_hash, "Code hash should match");
        assert_eq!(hash1.full_hash, hash2.full_hash, "Full hash should match");
        assert_eq!(
            hash1.text_section_size, hash2.text_section_size,
            "Text section size should match"
        );
        assert_eq!(hash1.is_debug, hash2.is_debug, "Debug status should match");

        info!("VERIFY: Same binary produces identical hashes");
        info!("TEST PASS: test_hash_same_binary_twice");
    }

    #[test]
    fn test_binaries_equivalent_matching() {
        init_test_logging();
        info!("TEST START: test_binaries_equivalent_matching");

        let local = BinaryHashResult {
            full_hash: "abc123def456".into(),
            code_hash: "xyz789abc".into(),
            text_section_size: 12345,
            is_debug: false,
        };
        let remote = BinaryHashResult {
            full_hash: "different_full_hash".into(), // Full hash may differ
            code_hash: "xyz789abc".into(),           // Code hash matches
            text_section_size: 12345,
            is_debug: false,
        };

        info!(
            "INPUT: local.code_hash={}, remote.code_hash={}",
            local.code_hash, remote.code_hash
        );

        let result = binaries_equivalent(&local, &remote);
        info!("RESULT: binaries_equivalent = {}", result);

        assert!(
            result,
            "Binaries with matching code hash should be equivalent"
        );
        info!("VERIFY: Binaries with matching code hash are equivalent");
        info!("TEST PASS: test_binaries_equivalent_matching");
    }

    #[test]
    fn test_binaries_not_equivalent_different_code_hash() {
        init_test_logging();
        info!("TEST START: test_binaries_not_equivalent_different_code_hash");

        let local = BinaryHashResult {
            full_hash: "abc123".into(),
            code_hash: "hash_v1".into(),
            text_section_size: 12345,
            is_debug: false,
        };
        let remote = BinaryHashResult {
            full_hash: "abc123".into(),
            code_hash: "hash_v2".into(), // Different code hash
            text_section_size: 12345,
            is_debug: false,
        };

        info!(
            "INPUT: local.code_hash={}, remote.code_hash={}",
            local.code_hash, remote.code_hash
        );

        let result = binaries_equivalent(&local, &remote);
        info!("RESULT: binaries_equivalent = {}", result);

        assert!(
            !result,
            "Binaries with different code hash should not be equivalent"
        );
        info!("VERIFY: Different code hash makes binaries non-equivalent");
        info!("TEST PASS: test_binaries_not_equivalent_different_code_hash");
    }

    #[test]
    fn test_binaries_not_equivalent_different_size() {
        init_test_logging();
        info!("TEST START: test_binaries_not_equivalent_different_size");

        let local = BinaryHashResult {
            full_hash: "abc123".into(),
            code_hash: "same_hash".into(),
            text_section_size: 12345,
            is_debug: false,
        };
        let remote = BinaryHashResult {
            full_hash: "abc123".into(),
            code_hash: "same_hash".into(),
            text_section_size: 54321, // Different size
            is_debug: false,
        };

        info!(
            "INPUT: local.text_size={}, remote.text_size={}",
            local.text_section_size, remote.text_section_size
        );

        let result = binaries_equivalent(&local, &remote);
        info!("RESULT: binaries_equivalent = {}", result);

        assert!(
            !result,
            "Binaries with different text size should not be equivalent"
        );
        info!("VERIFY: Different text section size makes binaries non-equivalent");
        info!("TEST PASS: test_binaries_not_equivalent_different_size");
    }

    #[test]
    fn test_binaries_not_equivalent_different_debug_status() {
        init_test_logging();
        info!("TEST START: test_binaries_not_equivalent_different_debug_status");

        let local = BinaryHashResult {
            full_hash: "abc123".into(),
            code_hash: "same_hash".into(),
            text_section_size: 12345,
            is_debug: false,
        };
        let remote = BinaryHashResult {
            full_hash: "abc123".into(),
            code_hash: "same_hash".into(),
            text_section_size: 12345,
            is_debug: true, // Different debug status
        };

        info!(
            "INPUT: local.is_debug={}, remote.is_debug={}",
            local.is_debug, remote.is_debug
        );

        let result = binaries_equivalent(&local, &remote);
        info!("RESULT: binaries_equivalent = {}", result);

        assert!(
            !result,
            "Binaries with different debug status should not be equivalent"
        );
        info!("VERIFY: Different debug status makes binaries non-equivalent");
        info!("TEST PASS: test_binaries_not_equivalent_different_debug_status");
    }

    #[test]
    fn test_compute_binary_hash_nonexistent_file() {
        init_test_logging();
        info!("TEST START: test_compute_binary_hash_nonexistent_file");

        let path = Path::new("/nonexistent/path/to/binary");
        info!("INPUT: compute_binary_hash({:?})", path);

        let result = compute_binary_hash(path);
        info!("RESULT: is_err = {}", result.is_err());

        assert!(result.is_err(), "Should fail for nonexistent file");
        info!("VERIFY: Nonexistent file returns error");
        info!("TEST PASS: test_compute_binary_hash_nonexistent_file");
    }

    #[test]
    fn test_compute_binary_hash_invalid_file() {
        init_test_logging();
        info!("TEST START: test_compute_binary_hash_invalid_file");

        // Try to hash a text file which is not a valid binary
        let path = Path::new("Cargo.toml");
        if !path.exists() {
            info!("SKIP: Cargo.toml not found");
            return;
        }

        info!("INPUT: compute_binary_hash({:?}) on text file", path);

        let result = compute_binary_hash(path);
        info!("RESULT: is_err = {}", result.is_err());

        assert!(result.is_err(), "Should fail for non-binary file");
        info!("VERIFY: Non-binary file returns error");
        info!("TEST PASS: test_compute_binary_hash_invalid_file");
    }

    #[test]
    fn test_binary_hash_result_fields() {
        init_test_logging();
        info!("TEST START: test_binary_hash_result_fields");

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => {
                info!("SKIP: No test binary found");
                return;
            }
        };

        info!("INPUT: compute_binary_hash({:?})", binary_path);

        let result = compute_binary_hash(&binary_path).unwrap();

        info!("RESULT: full_hash_len={}", result.full_hash.len());
        info!("RESULT: code_hash_len={}", result.code_hash.len());
        info!("RESULT: text_section_size={}", result.text_section_size);
        info!("RESULT: is_debug={}", result.is_debug);

        // BLAKE3 produces 64-character hex string
        assert_eq!(
            result.full_hash.len(),
            64,
            "Full hash should be 64 hex chars"
        );
        assert_eq!(
            result.code_hash.len(),
            64,
            "Code hash should be 64 hex chars"
        );
        assert!(
            result.text_section_size > 0,
            "Text section should have content"
        );

        info!("VERIFY: All fields have valid values");
        info!("TEST PASS: test_binary_hash_result_fields");
    }

    #[test]
    fn test_binary_contains_marker_found() {
        init_test_logging();
        info!("TEST START: test_binary_contains_marker_found");

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => {
                info!("SKIP: No test binary found");
                return;
            }
        };

        // Look for a common string that should exist in any binary
        // ELF binaries contain "ELF", Mach-O binaries don't have that marker
        // so we test for common strings that appear in most system binaries
        #[cfg(target_os = "linux")]
        let marker = "ELF";
        #[cfg(target_os = "macos")]
        let marker = "__TEXT"; // Mach-O segment name commonly found in binaries
        #[cfg(target_os = "windows")]
        let marker = "PE"; // PE header marker (though this test may be skipped on Windows)
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let marker = "ELF";

        info!(
            "INPUT: binary_contains_marker({:?}, '{}')",
            binary_path, marker
        );

        let result = binary_contains_marker(&binary_path, marker).unwrap();
        info!("RESULT: contains_marker = {}", result);

        // The marker should be found in the binary
        assert!(result, "Binary should contain '{}' string", marker);
        info!("VERIFY: Marker '{}' found in binary", marker);
        info!("TEST PASS: test_binary_contains_marker_found");
    }

    #[test]
    fn test_binary_contains_marker_not_found() {
        init_test_logging();
        info!("TEST START: test_binary_contains_marker_not_found");

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => {
                info!("SKIP: No test binary found");
                return;
            }
        };

        // Look for a unique string that should NOT exist in any binary
        let marker = "RCH_TEST_MARKER_UNIQUE_12345_XYZ";
        info!(
            "INPUT: binary_contains_marker({:?}, '{}')",
            binary_path, marker
        );

        let result = binary_contains_marker(&binary_path, marker).unwrap();
        info!("RESULT: contains_marker = {}", result);

        assert!(!result, "Binary should not contain made-up marker");
        info!("VERIFY: Unique marker not found in binary");
        info!("TEST PASS: test_binary_contains_marker_not_found");
    }

    #[test]
    fn test_binary_contains_marker_nonexistent_file() {
        init_test_logging();
        info!("TEST START: test_binary_contains_marker_nonexistent_file");

        let path = Path::new("/nonexistent/path/to/binary");
        let marker = "test";
        info!("INPUT: binary_contains_marker({:?}, '{}')", path, marker);

        let result = binary_contains_marker(path, marker);
        info!("RESULT: is_err = {}", result.is_err());

        assert!(result.is_err(), "Should fail for nonexistent file");
        info!("VERIFY: Nonexistent file returns error");
        info!("TEST PASS: test_binary_contains_marker_nonexistent_file");
    }

    // ===================================================================
    // Empty / non-binary file edge cases
    // ===================================================================

    #[test]
    fn test_compute_binary_hash_empty_file() {
        init_test_logging();
        info!("TEST START: test_compute_binary_hash_empty_file");

        let dir = std::env::temp_dir().join("rch-binary-hash-test-empty");
        let _ = std::fs::create_dir_all(&dir);
        let empty_path = dir.join("empty_binary");
        std::fs::write(&empty_path, b"").unwrap();

        let result = compute_binary_hash(&empty_path);
        assert!(
            result.is_err(),
            "empty file should fail binary hash (not a valid binary format)"
        );

        let _ = std::fs::remove_dir_all(&dir);
        info!("TEST PASS: test_compute_binary_hash_empty_file");
    }

    #[test]
    fn test_compute_binary_hash_text_file() {
        init_test_logging();
        info!("TEST START: test_compute_binary_hash_text_file");

        let dir = std::env::temp_dir().join("rch-binary-hash-test-text");
        let _ = std::fs::create_dir_all(&dir);
        let text_path = dir.join("not_a_binary.txt");
        std::fs::write(&text_path, b"Hello, this is not a binary file.").unwrap();

        let result = compute_binary_hash(&text_path);
        assert!(
            result.is_err(),
            "text file should fail binary hash computation"
        );

        let _ = std::fs::remove_dir_all(&dir);
        info!("TEST PASS: test_compute_binary_hash_text_file");
    }

    #[test]
    fn test_compute_binary_hash_truncated_elf_header() {
        init_test_logging();
        info!("TEST START: test_compute_binary_hash_truncated_elf_header");

        let dir = std::env::temp_dir().join("rch-binary-hash-test-truncated");
        let _ = std::fs::create_dir_all(&dir);
        let trunc_path = dir.join("truncated_elf");
        // ELF magic followed by truncated header
        std::fs::write(&trunc_path, b"\x7fELF\x02\x01\x01\x00").unwrap();

        let result = compute_binary_hash(&trunc_path);
        assert!(
            result.is_err(),
            "truncated ELF should fail binary hash computation"
        );

        let _ = std::fs::remove_dir_all(&dir);
        info!("TEST PASS: test_compute_binary_hash_truncated_elf_header");
    }

    // ===================================================================
    // BinaryHashResult equivalence edge cases
    // ===================================================================

    #[test]
    fn test_binaries_equivalent_ignores_full_hash() {
        init_test_logging();

        let result1 = BinaryHashResult {
            full_hash: "aaaa".to_string(),
            code_hash: "same_code".to_string(),
            text_section_size: 1024,
            is_debug: false,
        };
        let result2 = BinaryHashResult {
            full_hash: "bbbb".to_string(), // different full hash
            code_hash: "same_code".to_string(),
            text_section_size: 1024,
            is_debug: false,
        };

        assert!(
            binaries_equivalent(&result1, &result2),
            "equivalence should only consider code_hash, text_section_size, is_debug"
        );
    }

    #[test]
    fn test_binaries_not_equivalent_debug_vs_release() {
        init_test_logging();

        let debug = BinaryHashResult {
            full_hash: "a".to_string(),
            code_hash: "same".to_string(),
            text_section_size: 1024,
            is_debug: true,
        };
        let release = BinaryHashResult {
            full_hash: "a".to_string(),
            code_hash: "same".to_string(),
            text_section_size: 1024,
            is_debug: false,
        };

        assert!(
            !binaries_equivalent(&debug, &release),
            "debug vs release should not be equivalent"
        );
    }

    #[test]
    fn test_binaries_not_equivalent_different_text_size() {
        init_test_logging();

        let small = BinaryHashResult {
            full_hash: "a".to_string(),
            code_hash: "same".to_string(),
            text_section_size: 1024,
            is_debug: false,
        };
        let large = BinaryHashResult {
            full_hash: "a".to_string(),
            code_hash: "same".to_string(),
            text_section_size: 2048,
            is_debug: false,
        };

        assert!(
            !binaries_equivalent(&small, &large),
            "different text section sizes should not be equivalent"
        );
    }

    // ===================================================================
    // BinaryHashResult serialization
    // ===================================================================

    #[test]
    fn test_binary_hash_result_serialization_round_trip() {
        let result = BinaryHashResult {
            full_hash: "abc123def456".to_string(),
            code_hash: "789ghi012".to_string(),
            text_section_size: 65536,
            is_debug: true,
        };

        let json = serde_json::to_string(&result).expect("should serialize");
        let deserialized: BinaryHashResult =
            serde_json::from_str(&json).expect("should deserialize");
        assert_eq!(result, deserialized);
    }

    // ===================================================================
    // Marker search edge cases
    // ===================================================================

    #[test]
    fn test_binary_contains_marker_empty_marker() {
        init_test_logging();

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => {
                info!("SKIP: No test binary found");
                return;
            }
        };

        // Empty marker is trivially contained (consistent with str::contains(""))
        let result = binary_contains_marker(&binary_path, "");
        assert!(result.is_ok(), "empty marker should not panic");
        assert!(result.unwrap(), "empty marker should be trivially found");
    }

    #[test]
    fn test_binary_contains_marker_very_long_marker() {
        init_test_logging();

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => {
                info!("SKIP: No test binary found");
                return;
            }
        };

        // Very long marker that surely doesn't exist
        let marker = "X".repeat(1024);
        let result = binary_contains_marker(&binary_path, &marker).unwrap();
        assert!(
            !result,
            "very long marker should not be found in any binary"
        );
    }

    // ===================================================================
    // Hash determinism verification
    // ===================================================================

    #[test]
    fn test_full_hash_determinism() {
        init_test_logging();

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => return,
        };

        let result1 = compute_binary_hash(&binary_path).unwrap();
        let result2 = compute_binary_hash(&binary_path).unwrap();

        assert_eq!(
            result1.full_hash, result2.full_hash,
            "full_hash must be deterministic"
        );
        assert_eq!(
            result1.code_hash, result2.code_hash,
            "code_hash must be deterministic"
        );
        assert_eq!(
            result1.text_section_size, result2.text_section_size,
            "text_section_size must be deterministic"
        );
        assert_eq!(
            result1.is_debug, result2.is_debug,
            "is_debug must be deterministic"
        );
    }

    #[test]
    fn test_code_hash_differs_from_full_hash() {
        init_test_logging();

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => return,
        };

        let result = compute_binary_hash(&binary_path).unwrap();
        assert_ne!(
            result.code_hash, result.full_hash,
            "code_hash should differ from full_hash (unless binary has only code sections)"
        );
    }

    #[test]
    fn test_text_section_size_nonzero_for_real_binary() {
        init_test_logging();

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => return,
        };

        let result = compute_binary_hash(&binary_path).unwrap();
        assert!(
            result.text_section_size > 0,
            "real binary should have non-zero text section"
        );
    }

    #[test]
    fn test_hash_format_is_hex_string() {
        init_test_logging();

        let binary_path = match find_test_binary() {
            Some(p) => p,
            None => return,
        };

        let result = compute_binary_hash(&binary_path).unwrap();
        assert!(
            result.full_hash.chars().all(|c| c.is_ascii_hexdigit()),
            "full_hash should be hex string"
        );
        assert!(
            result.code_hash.chars().all(|c| c.is_ascii_hexdigit()),
            "code_hash should be hex string"
        );
        // BLAKE3 produces 64-char hex (256 bits)
        assert_eq!(
            result.full_hash.len(),
            64,
            "BLAKE3 hash should be 64 hex chars"
        );
        assert_eq!(
            result.code_hash.len(),
            64,
            "BLAKE3 hash should be 64 hex chars"
        );
    }
}