jonesy 0.7.11

Jonesy is here to help you not panic!
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
//! Binary and archive analysis functions.
//!
//! This module provides the core analysis functions for finding panic paths
//! in Mach-O binaries and library archives.

use crate::args::OutputFormat;
use crate::call_tree::{
    AnalysisSummary, CallTreeNode, CrateCodePoint, build_call_tree_parallel_filtered,
    collect_crate_code_points,
};
use crate::cargo::find_project_root;
use crate::config::Config;
use crate::heuristics::{
    ABORT_SYMBOL_PATTERNS, LIBRARY_PANIC_PATTERNS, PANIC_SYMBOL_PATTERNS,
    is_library_dependency_path, is_stdlib_function,
};
use crate::sym::{
    CallGraph, DebugInfo, LibraryCallGraph, SymbolIndex, ValidSourceFiles,
    find_all_symbols_matching, find_symbol_address, find_symbol_containing, load_debug_info,
    matches_crate_pattern_validated,
};
use dashmap::DashSet;
use goblin::mach::Mach::Binary;
use goblin::mach::MachO;
use indicatif::{ProgressBar, ProgressStyle};
use std::collections::HashSet;
use std::io::{self, IsTerminal};
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;

/// Create a spinner for long-running operations.
/// Returns None if progress display is disabled or stderr is not a terminal.
pub fn create_spinner(show_progress: bool, message: &str) -> Option<ProgressBar> {
    if !show_progress || !io::stderr().is_terminal() {
        return None;
    }
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(
        ProgressStyle::default_spinner()
            .template("  {spinner:.cyan} {msg} [{elapsed}]")
            .expect("valid template"),
    );
    spinner.set_message(message.to_string());
    spinner.enable_steady_tick(std::time::Duration::from_millis(100));
    Some(spinner)
}

/// Finish a spinner with a completion message.
pub fn finish_spinner(spinner: Option<ProgressBar>, message: &str) {
    if let Some(s) = spinner {
        s.finish_with_message(message.to_string());
    }
}

/// Result of analyzing a single binary, includes summary and optionally code points.
pub struct BinaryAnalysisResult {
    pub summary: AnalysisSummary,
    pub code_points: Vec<CrateCodePoint>,
}

impl BinaryAnalysisResult {
    pub fn empty() -> Self {
        Self {
            summary: AnalysisSummary::default(),
            code_points: Vec::new(),
        }
    }

    /// Merge another result into this one, combining code points.
    /// Code points at the same location have their causes merged.
    pub fn merge(&mut self, other: BinaryAnalysisResult) {
        use std::collections::HashMap;

        // Build a map of existing code points by (file, line)
        let mut points_map: HashMap<(String, u32), CrateCodePoint> = self
            .code_points
            .drain(..)
            .map(|cp| ((cp.file.clone(), cp.line), cp))
            .collect();

        // Merge other's code points
        for cp in other.code_points {
            let key = (cp.file.clone(), cp.line);
            if let Some(existing) = points_map.get_mut(&key) {
                // Merge causes (HashSet handles dedup)
                existing.causes.extend(cp.causes);
            } else {
                points_map.insert(key, cp);
            }
        }

        // Collect back to vec and sort
        self.code_points = points_map.into_values().collect();
        self.code_points
            .sort_by(|a, b| a.file.cmp(&b.file).then_with(|| a.line.cmp(&b.line)));

        // Recalculate summary from merged code points
        let points: HashSet<_> = self
            .code_points
            .iter()
            .map(|cp| (cp.file.clone(), cp.line))
            .collect();
        let files: HashSet<_> = self.code_points.iter().map(|cp| cp.file.clone()).collect();
        self.summary = AnalysisSummary::from_points(points, files);
    }
}

/// Represents a panic caller location for library analysis.
#[derive(Hash, Eq, PartialEq)]
struct PanicCaller {
    file: String,
    name: String,
    line: u32,
    column: Option<u32>,
    /// The panic symbol being called (e.g., "core::option::unwrap_failed")
    target: String,
}

/// Analyze a single MachO binary/object for panic points.
/// Returns a summary of panic code points found, plus code points.
#[allow(clippy::too_many_arguments)]
pub fn analyze_macho(
    macho: &MachO,
    buffer: &[u8],
    binary_path: &Path,
    crate_src_path: Option<&str>,
    show_timings: bool,
    config: &Config,
    output: &OutputFormat,
) -> BinaryAnalysisResult {
    let show_progress = output.show_progress();
    let total_start = Instant::now();

    // Build set of valid source files for single-crate project filtering
    // This prevents false positives from dependencies with relative src/ paths
    let project_root = find_project_root(binary_path);
    let valid_files = project_root
        .as_ref()
        .map(|root| ValidSourceFiles::from_project_root(root));

    // Find all entry points: panic symbols + abort symbols
    if show_progress {
        eprintln!("  Finding entry points...");
    }
    let step_start = Instant::now();

    // Collect all entry points with their addresses
    let mut entry_points: Vec<(String, String, u64)> = Vec::new(); // (mangled, demangled, addr)

    // Find panic entry points (first match from PANIC_SYMBOL_PATTERNS)
    for pattern in PANIC_SYMBOL_PATTERNS {
        if let Ok(Some((sym, dem))) = find_symbol_containing(macho, pattern)
            && let Some(addr) = find_symbol_address(macho, &sym)
        {
            entry_points.push((sym, dem, addr));
            break; // Only need one panic entry point
        }
    }

    // Find abort entry points
    if let Ok(abort_symbols) = find_all_symbols_matching(macho, ABORT_SYMBOL_PATTERNS) {
        for (sym, dem) in abort_symbols {
            if let Some(addr) = find_symbol_address(macho, &sym) {
                // Avoid duplicates
                if !entry_points.iter().any(|(_, _, a)| *a == addr) {
                    entry_points.push((sym, dem, addr));
                }
            }
        }
    }

    if show_timings {
        eprintln!("  [timing] Find entry points: {:?}", step_start.elapsed());
    }

    if entry_points.is_empty() {
        // No entry points found in this object
        return BinaryAnalysisResult::empty();
    }

    if show_progress && entry_points.len() > 1 {
        eprintln!(
            "  Found {} entry points (panic + abort)",
            entry_points.len()
        );
    }

    if show_progress {
        eprintln!("  Loading debug information...");
    }
    let step_start = Instant::now();
    let debug_info = load_debug_info(macho, binary_path, !show_progress);
    if show_timings {
        eprintln!("  [timing] Load debug info: {:?}", step_start.elapsed());
    }

    // Pre-compute the call graph by scanning all instructions once
    // Use debug info variant for source file/line enrichment
    let spinner = create_spinner(show_progress, "Scanning for function calls...");
    let step_start = Instant::now();

    // Create SymbolIndex once - CallGraph borrows from it to avoid allocations in hot path
    let symbol_index = SymbolIndex::new(macho);

    let call_graph = match &debug_info {
        DebugInfo::Embedded => {
            CallGraph::build_with_debug_info(
                macho,
                buffer,
                macho,
                buffer,
                crate_src_path,
                show_timings,
                symbol_index.as_ref(),
            )
            .or_else(|e| {
                eprintln!("Warning: debug-enriched call graph failed: {e}. Falling back to symbol-only graph.");
                CallGraph::build(macho, buffer, symbol_index.as_ref())
            })
            .unwrap_or_else(|e| {
                eprintln!("Error: call graph build failed: {e}");
                CallGraph::empty()
            })
        }
        DebugInfo::DSym(dsym_info) => dsym_info.with_debug_macho(|debug_macho| {
            if let Binary(debug_mach) = debug_macho {
                CallGraph::build_with_debug_info(
                    macho,
                    buffer,
                    debug_mach,
                    dsym_info.borrow_debug_buffer(),
                    crate_src_path,
                    show_timings,
                    symbol_index.as_ref(),
                )
                .or_else(|e| {
                    eprintln!("Warning: debug-enriched call graph failed: {e}. Falling back to symbol-only graph.");
                    CallGraph::build(macho, buffer, symbol_index.as_ref())
                })
                .unwrap_or_else(|e| {
                    eprintln!("Error: call graph build failed: {e}");
                    CallGraph::empty()
                })
            } else {
                CallGraph::build(macho, buffer, symbol_index.as_ref()).unwrap_or_else(|e| {
                    eprintln!("Error: call graph build failed: {e}");
                    CallGraph::empty()
                })
            }
        }),
        DebugInfo::DebugMap(_) | DebugInfo::None => {
            CallGraph::build(macho, buffer, symbol_index.as_ref()).unwrap_or_else(|e| {
                eprintln!("Error: call graph build failed: {e}");
                CallGraph::empty()
            })
        }
    };
    finish_spinner(spinner, "Scanning complete");
    if show_timings {
        eprintln!("  [timing] Build call graph: {:?}", step_start.elapsed());
    }

    // Build call trees for all entry points and merge results
    let mut final_result = BinaryAnalysisResult::empty();

    // Track visited addresses across all entry points to avoid redundant work
    let visited = Arc::new(DashSet::new());

    let spinner = create_spinner(show_progress, "Building call trees...");
    let step_start = Instant::now();

    for (_mangled, demangled, target_addr) in &entry_points {
        // Skip if we've already visited this address from another entry point
        if !visited.insert(*target_addr) {
            continue;
        }

        // Create root node for this entry point
        let mut root = CallTreeNode::new_root(demangled.clone());

        // Build the call tree for this entry point
        root.callers = build_call_tree_parallel_filtered(
            &call_graph,
            *target_addr,
            &visited,
            crate_src_path,
            valid_files.as_ref(),
        );

        // Collect code points from this tree
        if let Some(crate_path) = crate_src_path {
            let (code_points, _summary) = collect_crate_code_points(
                &root,
                crate_path,
                config,
                valid_files.as_ref(),
                project_root.as_deref(),
            );
            let entry_result = BinaryAnalysisResult {
                summary: AnalysisSummary::default(),
                code_points,
            };
            final_result.merge(entry_result);
        }
    }

    let total_nodes = visited.len();
    finish_spinner(
        spinner,
        &format!(
            "Built call trees ({} nodes from {} entry points)",
            total_nodes,
            entry_points.len()
        ),
    );
    if show_timings {
        eprintln!(
            "  [timing] Build call trees (with pruning): {:?}",
            step_start.elapsed()
        );
        eprintln!("  [timing] TOTAL: {:?}", total_start.elapsed());
    }

    final_result
}

/// Analyze an archive (rlib/staticlib) for panic points using relocation-based call graph.
/// This works for library-only crates that don't have binary entry points.
pub fn analyze_archive(
    archive: &goblin::archive::Archive,
    buffer: &[u8],
    binary_path: &Path,
    crate_src_path: Option<&str>,
    show_timings: bool,
    config: &Config,
    output: &OutputFormat,
) -> BinaryAnalysisResult {
    // Build set of valid source files for single-crate project filtering
    let project_root = find_project_root(binary_path);
    let valid_files = project_root
        .as_ref()
        .map(|root| ValidSourceFiles::from_project_root(root));

    // Helper to check if a file path is within the crate/workspace scope
    // Uses ValidSourceFiles for single-crate validation to prevent dependency false positives
    let file_in_scope = |file: &str| {
        crate_src_path.is_none_or(|paths| {
            let file = file.replace('\\', "/");
            // Use the same validated matching as binary analysis
            matches_crate_pattern_validated(&file, paths, valid_files.as_ref())
        })
    };

    let show_progress = output.show_progress();
    let total_start = Instant::now();

    if show_progress {
        eprintln!("  Building library call graph from relocations...");
    }
    let step_start = Instant::now();

    // Build a merged call graph from all .o files in the archive
    let mut merged_graph = LibraryCallGraph::empty();

    for member_name in archive.members() {
        // Skip non-object files (like .rmeta)
        if !member_name.ends_with(".o") {
            continue;
        }

        // Extract the member data
        let member_data = match archive.extract(member_name, buffer) {
            Ok(data) => data,
            Err(e) => {
                if show_progress {
                    eprintln!("  Warning: Failed to extract {}: {}", member_name, e);
                }
                continue;
            }
        };

        // Parse the object file as Mach-O and build its call graph
        match MachO::parse(member_data, 0) {
            Ok(obj_macho) => {
                match LibraryCallGraph::build_from_object(&obj_macho, member_data, crate_src_path) {
                    Ok(obj_graph) => merged_graph.merge(obj_graph),
                    Err(e) => {
                        if show_progress {
                            eprintln!(
                                "  Warning: Failed to build call graph for {}: {}",
                                member_name, e
                            );
                        }
                    }
                }
            }
            Err(e) => {
                if show_progress {
                    eprintln!(
                        "  Warning: Failed to parse {} as Mach-O: {}",
                        member_name, e
                    );
                }
            }
        }
    }

    if show_timings {
        eprintln!(
            "  [timing] Build library call graph: {:?}",
            step_start.elapsed()
        );
    }

    if merged_graph.is_empty() {
        if show_progress {
            println!("\nNo call graph data found in archive");
        }
        return BinaryAnalysisResult::empty();
    }

    // Find all callers of panic-related functions
    if show_progress {
        eprintln!("  Finding panic callers...");
    }
    let step_start = Instant::now();

    let mut panic_callers: HashSet<PanicCaller> = HashSet::new();

    // Search for callers of panic-related symbols
    for target_sym in merged_graph.target_symbols() {
        // Check if this is a panic-related symbol
        // Note: be careful with std::panicking:: - set_hook/take_hook are NOT panic functions
        let is_panic_symbol = LIBRARY_PANIC_PATTERNS
            .iter()
            .any(|p| target_sym.contains(p))
            || target_sym.contains("core::panicking::")
            || (target_sym.contains("std::panicking::")
                && !target_sym.contains("set_hook")
                && !target_sym.contains("take_hook"));

        if !is_panic_symbol {
            continue;
        }

        for caller_info in merged_graph.get_callers(target_sym) {
            // Skip standard library functions - we only want user code
            if is_stdlib_function(&caller_info.caller_name) {
                continue;
            }

            // Get file from DWARF info, filtering out library code paths
            let dwarf_file = caller_info
                .caller_file
                .as_ref()
                .filter(|f| !is_library_dependency_path(f));

            // Only include entries with proper DWARF file/line info from user code
            // Skip entries without valid line numbers (would show confusing ":0" in output)
            // Also filter by crate_src_path if provided (for workspace scoping)
            if let Some(file) = dwarf_file
                && file_in_scope(file)
                && let Some(line) = caller_info.line
            {
                panic_callers.insert(PanicCaller {
                    file: file.clone(),
                    name: caller_info.caller_name.to_string(),
                    line,
                    column: caller_info.column,
                    target: target_sym.to_string(),
                });
            }
        }
    }

    if show_timings {
        eprintln!("  [timing] Find panic callers: {:?}", step_start.elapsed());
    }

    // Report results
    if panic_callers.is_empty() {
        if show_progress {
            println!("\nNo panics in crate");
        }
        return BinaryAnalysisResult::empty();
    }

    // Convert PanicCaller to CrateCodePoint
    // Sort for deterministic output
    let mut sorted_callers: Vec<_> = panic_callers.into_iter().collect();
    sorted_callers.sort_by(|a, b| (&a.file, a.line, &a.name).cmp(&(&b.file, b.line, &b.name)));

    // Convert to CrateCodePoint structures with panic cause detection
    let mut code_points: Vec<CrateCodePoint> = sorted_callers
        .into_iter()
        .map(|caller| {
            let mut causes = std::collections::HashSet::new();
            // Detect panic cause from the panic symbol being called (target),
            // not from the user's function name (caller.name)
            if let Some(cause) =
                crate::heuristics::detect_panic_cause(&caller.target, Some(&caller.file))
            {
                causes.insert(cause);
            }
            CrateCodePoint {
                name: caller.name,
                file: caller.file,
                line: caller.line,
                column: caller.column,
                causes,
                children: Vec::new(),  // Archives don't have call tree hierarchy
                is_direct_panic: true, // Archive analysis detects direct panic calls
                called_function: None, // Direct panics don't need called function name
            }
        })
        .collect();

    // Assign Unknown cause to points without identified causes (archives have no hierarchy)
    for point in &mut code_points {
        if point.causes.is_empty() {
            point.causes.insert(crate::panic_cause::PanicCause::Unknown);
        }
    }

    // Filter out code points whose causes are ALL allowed (not denied) by config
    // Use is_denied_at to support scoped rules based on file/function patterns
    code_points.retain(|point| {
        // Keep points with any denied cause
        // Check both the containing function and the called function (for indirect panics)
        point.causes.iter().any(|c| {
            let denied_in_func = config.is_denied_at(c, Some(&point.file), Some(&point.name));
            let denied_in_called = point
                .called_function
                .as_ref()
                .map(|cf| config.is_denied_at(c, Some(&point.file), Some(cf)))
                .unwrap_or(true);
            denied_in_func && denied_in_called
        })
    });

    // Remove allowed causes, keeping only denied ones
    for point in &mut code_points {
        let file = point.file.clone();
        let name = point.name.clone();
        let called = point.called_function.clone();
        point.causes.retain(|c| {
            let denied_in_func = config.is_denied_at(c, Some(&file), Some(&name));
            let denied_in_called = called
                .as_ref()
                .map(|cf| config.is_denied_at(c, Some(&file), Some(cf)))
                .unwrap_or(true);
            denied_in_func && denied_in_called
        });
    }

    // Deduplicate by (file, line)
    let mut seen: std::collections::HashMap<(String, u32), usize> =
        std::collections::HashMap::new();
    let mut deduped: Vec<CrateCodePoint> = Vec::new();
    for point in code_points {
        let key = (point.file.clone(), point.line);
        if let Some(&idx) = seen.get(&key) {
            // Merge causes into existing point
            deduped[idx].causes.extend(point.causes);
        } else {
            seen.insert(key, deduped.len());
            deduped.push(point);
        }
    }

    if show_timings {
        eprintln!("  [timing] TOTAL: {:?}", total_start.elapsed());
    }

    // Build summary from code points
    let mut points: HashSet<(String, u32)> = HashSet::new();
    let mut files_affected: HashSet<String> = HashSet::new();
    for point in &deduped {
        points.insert((point.file.clone(), point.line));
        files_affected.insert(point.file.clone());
    }

    BinaryAnalysisResult {
        summary: AnalysisSummary::from_points(points, files_affected),
        code_points: deduped,
    }
}

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

    // ========================================================================
    // BinaryAnalysisResult tests
    // ========================================================================

    #[test]
    fn test_binary_analysis_result_empty() {
        let result = BinaryAnalysisResult::empty();
        assert!(result.code_points.is_empty());
        assert_eq!(result.summary.panic_points(), 0);
        assert_eq!(result.summary.files_affected(), 0);
    }

    fn make_code_point(file: &str, line: u32, cause: PanicCause) -> CrateCodePoint {
        let mut causes = HashSet::new();
        causes.insert(cause);
        CrateCodePoint {
            name: "test_func".to_string(),
            file: file.to_string(),
            line,
            column: None,
            causes,
            children: Vec::new(),
            is_direct_panic: true,
            called_function: None,
        }
    }

    #[test]
    fn test_binary_analysis_result_merge_disjoint() {
        let mut result1 = BinaryAnalysisResult {
            summary: AnalysisSummary::default(),
            code_points: vec![make_code_point("src/a.rs", 10, PanicCause::UnwrapNone)],
        };

        let result2 = BinaryAnalysisResult {
            summary: AnalysisSummary::default(),
            code_points: vec![make_code_point("src/b.rs", 20, PanicCause::UnwrapErr)],
        };

        result1.merge(result2);

        assert_eq!(result1.code_points.len(), 2);
        assert_eq!(result1.summary.panic_points(), 2);
        assert_eq!(result1.summary.files_affected(), 2);
    }

    #[test]
    fn test_binary_analysis_result_merge_same_location() {
        let mut result1 = BinaryAnalysisResult {
            summary: AnalysisSummary::default(),
            code_points: vec![make_code_point("src/main.rs", 10, PanicCause::UnwrapNone)],
        };

        let result2 = BinaryAnalysisResult {
            summary: AnalysisSummary::default(),
            code_points: vec![make_code_point("src/main.rs", 10, PanicCause::ExpectNone)],
        };

        result1.merge(result2);

        // Same file:line should be merged, causes combined
        assert_eq!(result1.code_points.len(), 1);
        assert_eq!(result1.code_points[0].causes.len(), 2);
        assert!(
            result1.code_points[0]
                .causes
                .contains(&PanicCause::UnwrapNone)
        );
        assert!(
            result1.code_points[0]
                .causes
                .contains(&PanicCause::ExpectNone)
        );
    }

    #[test]
    fn test_binary_analysis_result_merge_sorted() {
        let mut result1 = BinaryAnalysisResult {
            summary: AnalysisSummary::default(),
            code_points: vec![make_code_point("src/z.rs", 100, PanicCause::UnwrapNone)],
        };

        let result2 = BinaryAnalysisResult {
            summary: AnalysisSummary::default(),
            code_points: vec![
                make_code_point("src/a.rs", 10, PanicCause::UnwrapErr),
                make_code_point("src/a.rs", 5, PanicCause::ExplicitPanic),
            ],
        };

        result1.merge(result2);

        // Should be sorted by file, then line
        assert_eq!(result1.code_points.len(), 3);
        assert_eq!(result1.code_points[0].file, "src/a.rs");
        assert_eq!(result1.code_points[0].line, 5);
        assert_eq!(result1.code_points[1].file, "src/a.rs");
        assert_eq!(result1.code_points[1].line, 10);
        assert_eq!(result1.code_points[2].file, "src/z.rs");
        assert_eq!(result1.code_points[2].line, 100);
    }

    #[test]
    fn test_binary_analysis_result_merge_empty() {
        let mut result1 = BinaryAnalysisResult {
            summary: AnalysisSummary::default(),
            code_points: vec![make_code_point("src/main.rs", 10, PanicCause::UnwrapNone)],
        };

        let result2 = BinaryAnalysisResult::empty();

        result1.merge(result2);

        assert_eq!(result1.code_points.len(), 1);
    }
}