binscout 0.2.1

Headless, agent-first binary analysis: functions, CFGs, xrefs, strings, and IR over a JSON CLI or MCP server
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
#![warn(missing_docs)]
//! binscout core: headless agent-first binary analysis.

pub mod analysis;
pub mod db;
pub mod disasm;
pub mod error;
pub mod ir;
pub mod loader;
pub mod mcp;

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use crate::analysis::{Analysis, StringsFilter, Xref, XrefKind, analyze};
use crate::db::{Annotation, BinaryMeta, ProjectInfo};
use crate::disasm::{Disassembler, PartialDisasm};
use crate::error::{Error, Result};
use crate::loader::strings::StringHit;
use crate::loader::{BinaryFormat, LoadedBinary, RawOptions, load, load_raw};

/// Crate version, also served via CLI `--version` and MCP `project_info`.
pub fn version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// Filters for [`Project::functions_filtered`]: every present field must match.
///
/// `query` is a case-insensitive substring over the rename-resolved display
/// name (functions with no name never match a query). `caller` keeps the
/// functions that call the function containing that address; `callee` keeps
/// the functions called by the function containing that address. `range`
/// keeps functions whose entry lies in the inclusive bounds (normalized so
/// `lo <= hi`). An anchor address lying in no function matches nothing.
#[derive(Debug, Clone, Default)]
pub struct FunctionFilter {
    /// Case-insensitive name substring; `None` disables the filter.
    pub query: Option<String>,
    /// Keep callers of the function containing this address.
    pub caller: Option<u64>,
    /// Keep callees of the function containing this address.
    pub callee: Option<u64>,
    /// Keep functions with `entry` in `lo..=hi`.
    pub range: Option<(u64, u64)>,
}

/// Opened analysis project: binary plus its cached analysis and annotations.
///
/// The binary file is only ever read; all persistence (analysis snapshot,
/// renames, comments) goes to the `redb` sidecar at [`Project::db_path`],
/// written solely by [`Project::save`] and the annotation setters.
#[derive(Debug)]
pub struct Project {
    path: PathBuf,
    db_path: PathBuf,
    content_hash: u64,
    size: u64,
    binary: LoadedBinary,
    analysis: Analysis,
    annotations: BTreeMap<u64, Annotation>,
}

impl Project {
    /// [`Project::open`] with an optional explicit DB path (`None` = sidecar).
    ///
    /// # Errors
    /// Same as [`Project::open`].
    pub fn open_any(binary: &Path, db: Option<&Path>) -> Result<Self> {
        match db {
            Some(d) => Self::open_with_db(binary, d),
            None => Self::open(binary),
        }
    }

    /// Open a supported container binary (ELF/PE/Mach-O) with the default
    /// sidecar DB.
    ///
    /// Recognized LE images are rejected with [`Error::Unsupported`] (never
    /// mis-parsed as raw); force raw mapping of any bytes, LE included,
    /// through [`Project::open_raw`]. Unrecognized bytes fall back to raw
    /// x86-64 at base 0 so fixture blobs and shellcode open without options;
    /// explicit bases/arches go through [`Project::open_raw`]. Reads the
    /// sidecar when present: a matching content hash loads the cached
    /// snapshot, a mismatch re-analyzes while keeping stored annotations.
    /// A stale sidecar's derived rows are never decoded (only its metadata
    /// and annotations are read), so a large obsolete snapshot costs no
    /// decoding proportional to its discarded rows. Never writes; call
    /// [`Project::save`].
    ///
    /// Input policy: at most 512 MiB are read (single open, chunked with
    /// checked growth); containers with large unmapped overlays still open
    /// while mapped/name/demangled/snapshot budgets may reject with
    /// [`Error::Limit`]. Budget rejections are intentional behavior changes,
    /// never raw fallback: only [`Error::Invalid`] falls back.
    ///
    /// # Errors
    /// [`Error::NotFound`] if the path does not exist, [`Error::Unsupported`]
    /// if it is not a file, the image is LE, or the arch has no
    /// disassembler, [`Error::Invalid`] on undecodable input,
    /// [`Error::Limit`] on input/name/metadata/snapshot budget overrun,
    /// [`Error::Storage`] on DB or I/O failure.
    pub fn open(path: &Path) -> Result<Self> {
        Self::open_with_db(path, &db::default_db_path(path))
    }

    /// [`Project::open`] with an explicit DB path (keeps fixture dirs clean).
    ///
    /// # Errors
    /// Same as [`Project::open`].
    pub fn open_with_db(binary: &Path, db_path: &Path) -> Result<Self> {
        Self::open_inner(binary, db_path, None)
    }

    /// Open a raw blob with explicit mapping options plus explicit DB path.
    ///
    /// # Errors
    /// Same as [`Project::open`].
    pub fn open_raw(binary: &Path, db_path: &Path, opts: RawOptions) -> Result<Self> {
        Self::open_inner(binary, db_path, Some(opts))
    }

    fn open_inner(binary: &Path, db_path: &Path, raw: Option<RawOptions>) -> Result<Self> {
        // Single-open bounded read: one handle, chunked with checked
        // accumulation, so a growing file cannot slip past a stat cap.
        let bytes = read_input_bytes(binary)?;
        let hash = db::content_hash(&bytes);
        let size = bytes.len() as u64;

        // Metadata-first snapshot read over a read-only handle: a stale
        // sidecar yields its annotations without decoding the discarded
        // derived rows (see the stale-cache policy on `db::load_cached`),
        // and the read-only open itself costs nothing proportional to the
        // file. Reads never save and never create the sidecar.
        let cached = if db_path.exists() {
            match db::open_db_read_only(db_path) {
                Ok(db) => Some(db::load_cached(&db, hash)?),
                // Raced with a concurrent sidecar deletion: read as absent.
                Err(_) if !db_path.exists() => None,
                Err(e) => return Err(e),
            }
        } else {
            None
        };

        match cached {
            Some(db::Snapshot::Hit(hit)) => Ok(Self {
                path: binary.to_path_buf(),
                db_path: db_path.to_path_buf(),
                content_hash: hash,
                size,
                binary: reload_binary(&bytes, raw)?,
                analysis: hit.analysis,
                annotations: hit.annotations,
            }),
            Some(db::Snapshot::Stale { annotations, .. }) => {
                Self::reanalyze(binary, db_path, bytes, raw, hash, size, annotations)
            }
            Some(db::Snapshot::Miss) | None => {
                Self::reanalyze(binary, db_path, bytes, raw, hash, size, BTreeMap::new())
            }
        }
    }

    /// Re-analyze `bytes` from scratch, carrying `annotations` forward.
    ///
    /// Stale sidecars keep user renames and comments by address; the derived
    /// analysis always comes from the current bytes, never from storage.
    fn reanalyze(
        binary: &Path,
        db_path: &Path,
        bytes: Vec<u8>,
        raw: Option<RawOptions>,
        hash: u64,
        size: u64,
        annotations: BTreeMap<u64, Annotation>,
    ) -> Result<Self> {
        let loaded = match raw {
            Some(opts) => load_raw(&bytes, opts)?,
            None => load_or_raw(&bytes)?,
        };
        let analysis = analyze(&loaded)?;
        Ok(Self {
            path: binary.to_path_buf(),
            db_path: db_path.to_path_buf(),
            content_hash: hash,
            size,
            binary: loaded,
            analysis,
            annotations,
        })
    }

    /// Persist the analysis snapshot and annotations to the sidecar DB.
    ///
    /// Only ever writes [`Project::db_path`]; the binary is untouched.
    ///
    /// # Errors
    /// [`Error::Storage`] on any `redb` or encoding failure.
    pub fn save(&self) -> Result<()> {
        let db = db::open_db(&self.db_path)?;
        db::save(&db, &self.meta(), &self.analysis, &self.annotations)?;
        Ok(())
    }

    fn meta(&self) -> BinaryMeta {
        BinaryMeta {
            version: db::SCHEMA_VERSION,
            binary_path: self.path.display().to_string(),
            content_hash: self.content_hash,
            size: self.size,
            arch: db::arch_name(self.binary.arch).to_string(),
            format: db::format_name(self.binary.format).to_string(),
            entry: self.binary.entry,
            supported: true,
            reason: None,
        }
    }

    /// Persist one changed annotation row, falling back to a full snapshot.
    ///
    /// Tries [`db::save_annotation`](crate::db::save_annotation) first: when
    /// the sidecar holds a snapshot for this binary, only the `annotations`
    /// row changes. Otherwise (fresh DB or content mismatch) rewrites the
    /// full snapshot via [`Project::save`].
    fn persist_annotation(&self, addr: u64) -> Result<()> {
        let db = db::open_db(&self.db_path)?;
        let ann = self.annotations.get(&addr).filter(|a| !a.is_empty());
        match db::save_annotation(&db, &self.meta(), addr, ann)? {
            db::AnnotationSave::Fast => Ok(()),
            db::AnnotationSave::NeedsFull => {
                db::save(&db, &self.meta(), &self.analysis, &self.annotations)?;
                Ok(())
            }
        }
    }

    /// Agent-facing summary; always JSON-serializable.
    #[must_use]
    pub fn project_info(&self) -> ProjectInfo {
        let s = self.analysis.summary();
        ProjectInfo {
            binary: self.path.display().to_string(),
            db_path: self.db_path.display().to_string(),
            version: version().to_string(),
            arch: db::arch_name(self.binary.arch).to_string(),
            format: db::format_name(self.binary.format).to_string(),
            entry: self.binary.entry,
            content_hash: self.content_hash,
            size: self.size,
            supported: true,
            reason: None,
            functions: s.functions,
            blocks: s.blocks,
            insns: s.insns,
            xrefs: s.xrefs,
            strings: s.strings,
            annotations: self.annotations.values().filter(|a| !a.is_empty()).count(),
        }
    }

    /// Storage stats for the project: binary size plus sidecar DB size
    /// and the same analysis counts as [`Project::project_info`].
    ///
    /// Opens without saving like the other read paths; `db_size` is `0`
    /// when no sidecar exists yet. The `stats` CLI/MCP surface reports
    /// this verbatim so operators see the cost of a cached snapshot.
    ///
    /// # Errors
    /// [`Error::Storage`] when the sidecar exists but cannot be statted.
    pub fn stats_json(&self) -> Result<serde_json::Value> {
        let s = self.analysis.summary();
        let db_size = db::db_file_size(&self.db_path)?;
        Ok(serde_json::json!({
            "binary": self.path.display().to_string(),
            "db_path": self.db_path.display().to_string(),
            "version": version(),
            "arch": db::arch_name(self.binary.arch),
            "format": db::format_name(self.binary.format),
            "content_hash": self.content_hash,
            "size": self.size,
            "db_size": db_size,
            "functions": s.functions,
            "blocks": s.blocks,
            "insns": s.insns,
            "xrefs": s.xrefs,
            "strings": s.strings,
            "annotations": self.annotations.values().filter(|a| !a.is_empty()).count(),
        }))
    }

    /// Path of the analyzed binary.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Path of the `redb` sidecar (only file this project writes).
    #[must_use]
    pub fn db_path(&self) -> &Path {
        &self.db_path
    }

    /// Content hash the in-memory analysis was taken over.
    #[must_use]
    pub fn content_hash(&self) -> u64 {
        self.content_hash
    }

    /// Parsed binary headers, segments, and symbols.
    #[must_use]
    pub fn binary(&self) -> &LoadedBinary {
        &self.binary
    }

    /// Cached analysis (functions, CFGs, xrefs, strings).
    #[must_use]
    pub fn analysis(&self) -> &Analysis {
        &self.analysis
    }

    /// All annotations keyed by address.
    #[must_use]
    pub fn annotations(&self) -> &BTreeMap<u64, Annotation> {
        &self.annotations
    }

    /// Annotation at `addr`, if any.
    #[must_use]
    pub fn annotation(&self, addr: u64) -> Option<&Annotation> {
        self.annotations.get(&addr).filter(|a| !a.is_empty())
    }

    /// Display name of a function: annotation rename wins over export name.
    #[must_use]
    pub fn function_name(&self, entry: u64) -> Option<String> {
        if let Some(n) = self
            .annotations
            .get(&entry)
            .and_then(|a| a.name.clone())
            .filter(|n| !n.is_empty())
        {
            return Some(n);
        }
        self.analysis.functions.get(&entry)?.name.clone()
    }

    /// Rename a function in the DB only; the binary is never modified.
    ///
    /// An empty `name` clears the rename. Persists immediately via a
    /// single-row transaction when the cached snapshot matches, else a full
    /// snapshot rewrite.
    ///
    /// # Errors
    /// [`Error::NotFound`] for unknown function entries, [`Error::Limit`]
    /// when the name exceeds 8 KiB, [`Error::Storage`] when the annotation
    /// cannot be persisted.
    pub fn rename_function(&mut self, entry: u64, name: &str) -> Result<()> {
        if !self.analysis.functions.contains_key(&entry) {
            return Err(Error::NotFound(format!("function {entry:#x}")));
        }
        if name.len() > crate::db::MAX_ANNOTATION_BYTES {
            return Err(Error::Limit(format!(
                "rename of {} bytes exceeds {}",
                name.len(),
                crate::db::MAX_ANNOTATION_BYTES
            )));
        }
        let ann = self.annotations.entry(entry).or_default();
        ann.name = (!name.is_empty()).then(|| name.to_string());
        if ann.is_empty() {
            self.annotations.remove(&entry);
        }
        self.persist_annotation(entry)
    }

    /// Comment an address in the DB only; the binary is never modified.
    ///
    /// Any address is commentable (instructions, functions, strings, data).
    /// An empty `comment` clears the comment. Persists immediately via a
    /// single-row transaction when the cached snapshot matches, else a full
    /// snapshot rewrite.
    ///
    /// # Errors
    /// [`Error::Limit`] when the comment exceeds 8 KiB, [`Error::Storage`]
    /// when the annotation cannot be persisted.
    pub fn set_comment(&mut self, addr: u64, comment: &str) -> Result<()> {
        if comment.len() > crate::db::MAX_ANNOTATION_BYTES {
            return Err(Error::Limit(format!(
                "comment of {} bytes exceeds {}",
                comment.len(),
                crate::db::MAX_ANNOTATION_BYTES
            )));
        }
        let ann = self.annotations.entry(addr).or_default();
        ann.comment = (!comment.is_empty()).then(|| comment.to_string());
        if ann.is_empty() {
            self.annotations.remove(&addr);
        }
        self.persist_annotation(addr)
    }

    /// File-backed bytes mapped at `va` (zero-padded past file data).
    ///
    /// # Errors
    /// [`Error::Limit`] for empty/oversize ranges, [`Error::NotFound`] when
    /// the range is not fully mapped.
    pub fn bytes_at(&self, va: u64, len: usize) -> Result<Vec<u8>> {
        if len == 0 || len > MAX_RANGE_BYTES {
            return Err(Error::Limit(format!("range length {len} out of bounds")));
        }
        let len_u64 = len as u64;
        let seg = self
            .binary
            .segments
            .iter()
            .find(|s| {
                if va < s.vaddr {
                    return false;
                }
                let Some(off) = va.checked_sub(s.vaddr) else {
                    return false;
                };
                let Some(need) = off.checked_add(len_u64) else {
                    return false;
                };
                need <= s.mem_size
            })
            .ok_or_else(|| Error::NotFound(format!("no bytes mapped at {va:#x}")))?;
        let mut out = vec![0u8; len];
        let off = (va - seg.vaddr) as usize;
        let have = seg.data.len().saturating_sub(off).min(len);
        if have > 0 {
            out[..have].copy_from_slice(&seg.data[off..off + have]);
        }
        Ok(out)
    }

    /// Disassemble `len` bytes at `va` with the binary's architecture.
    ///
    /// Returns the valid prefix plus `error_at` for the first bad opcode
    /// (`None` when the whole range decodes); cap overruns are still
    /// errors. Serializes as `{"insns": [...], "error_at": null|{...}}`.
    ///
    /// # Errors
    /// Same as [`Project::bytes_at`], plus [`Error::Limit`] on cap overrun.
    pub fn disasm_at(&self, addr: u64, len: usize) -> Result<PartialDisasm> {
        let bytes = self.bytes_at(addr, len)?;
        self.binary
            .arch
            .disassembler()
            .disasm_range_partial(&bytes, addr)
    }

    /// Function rows with annotation renames resolved, ordered by entry.
    #[must_use]
    pub fn functions_resolved(&self, offset: usize, limit: usize) -> Vec<serde_json::Value> {
        self.functions_filtered(&FunctionFilter::default(), offset, limit)
    }

    /// Function rows with annotation renames resolved, filtered then paged.
    ///
    /// Every present [`FunctionFilter`] field must match; filtering happens
    /// before paging so `offset`/`limit` apply to the matching rows.
    #[must_use]
    pub fn functions_filtered(
        &self,
        filter: &FunctionFilter,
        offset: usize,
        limit: usize,
    ) -> Vec<serde_json::Value> {
        // Resolve anchor addresses once: None = filter disabled,
        // Some(None) = anchor lies in no function (matches nothing).
        let caller: Option<Option<u64>> =
            filter.caller.map(|a| self.analysis.containing_function(a));
        let callee_calls: Option<Option<Vec<u64>>> = filter.callee.map(|a| {
            self.analysis
                .containing_function(a)
                .map(|c| self.analysis.calls_of(c))
        });
        let range = filter
            .range
            .map(|(a, b)| if a <= b { (a, b) } else { (b, a) });
        let query = filter.query.as_deref().map(|s| s.to_lowercase());
        self.analysis
            .functions
            .values()
            .filter(|f| range.is_none_or(|(lo, hi)| f.entry >= lo && f.entry <= hi))
            .filter(|f| match caller {
                None => true,
                Some(None) => false,
                Some(Some(c)) => self.analysis.calls_of(f.entry).contains(&c),
            })
            .filter(|f| match &callee_calls {
                None => true,
                Some(None) => false,
                Some(Some(cs)) => cs.contains(&f.entry),
            })
            .filter(|f| match &query {
                Some(q) => self
                    .function_name(f.entry)
                    .is_some_and(|n| n.to_lowercase().contains(q.as_str())),
                None => true,
            })
            .skip(offset)
            .take(limit.min(MAX_ROWS))
            .map(|f| {
                let (entry, entry_hex) = addr_pair(f.entry);
                serde_json::json!({
                    "id": f.id(), "entry": entry, "entry_hex": entry_hex,
                    "name": self.function_name(f.entry),
                    "blocks": f.blocks.len(), "insns": f.insn_count(), "calls": self.analysis.calls_of(f.entry),
                })
            })
            .collect()
    }

    /// Full function detail: blocks with instructions in address order.
    ///
    /// `addr` may be any address inside the function; it snaps to the
    /// containing entry. The result carries both `entry` (the canonical
    /// function entry) and `containing_entry` (the entry containing `addr`).
    ///
    /// # Errors
    /// [`Error::NotFound`] when `addr` lies in no function.
    pub fn func_detail(&self, addr: u64) -> Result<serde_json::Value> {
        let entry = self
            .analysis
            .containing_function(addr)
            .ok_or_else(|| Error::NotFound(format!("function {addr:#x}")))?;
        let f = self
            .analysis
            .functions
            .get(&entry)
            .ok_or_else(|| Error::NotFound(format!("function {addr:#x}")))?;
        let blocks: Vec<serde_json::Value> = f
            .blocks
            .values()
            .map(|b| {
                let (start, start_hex) = addr_pair(b.start);
                let (end, end_hex) = addr_pair(b.end());
                serde_json::json!({
                    "id": b.id(entry), "start": start, "start_hex": start_hex,
                    "end": end, "end_hex": end_hex,
                    "insns": b.insns, "succs": f.successors(b.start),
                })
            })
            .collect();
        let (entry_json, entry_hex) = addr_pair(f.entry);
        let (_, containing_hex) = addr_pair(entry);
        Ok(serde_json::json!({
            "id": f.id(), "entry": entry_json, "entry_hex": entry_hex,
            "containing_entry": entry, "containing_entry_hex": containing_hex,
            "name": self.function_name(entry),
            "blocks": blocks, "edges": f.edges(),
            "calls": self.analysis.calls_of(entry),
        }))
    }

    /// CFG of one function: block nodes plus `(from, to)` block edges.
    ///
    /// `addr` may be any address inside the function; it snaps to the
    /// containing entry. The result carries both `entry` (the canonical
    /// function entry) and `containing_entry` (the entry containing `addr`).
    ///
    /// # Errors
    /// [`Error::NotFound`] when `addr` lies in no function.
    pub fn cfg_of(&self, addr: u64) -> Result<serde_json::Value> {
        let entry = self
            .analysis
            .containing_function(addr)
            .ok_or_else(|| Error::NotFound(format!("function {addr:#x}")))?;
        let f = self
            .analysis
            .functions
            .get(&entry)
            .ok_or_else(|| Error::NotFound(format!("function {addr:#x}")))?;
        let nodes: Vec<serde_json::Value> = f
            .blocks
            .values()
            .map(|b| {
                let (start, start_hex) = addr_pair(b.start);
                let (end, end_hex) = addr_pair(b.end());
                serde_json::json!({
                    "start": start, "start_hex": start_hex,
                    "end": end, "end_hex": end_hex,
                    "insns": b.insns.len(), "succs": f.successors(b.start),
                })
            })
            .collect();
        let (_, entry_hex) = addr_pair(entry);
        Ok(
            serde_json::json!({ "entry": entry, "entry_hex": entry_hex, "containing_entry": entry, "containing_entry_hex": entry_hex, "nodes": nodes, "edges": f.edges() }),
        )
    }

    /// Lift `len` bytes at `va` to IR.
    ///
    /// Lifts the valid prefix (see [`Project::disasm_at`]) and reports the
    /// first bad opcode in `error_at` (`None` on a clean range).
    ///
    /// # Errors
    /// Same as [`Project::disasm_at`].
    pub fn ir_at(&self, addr: u64, len: usize) -> Result<serde_json::Value> {
        let partial = self.disasm_at(addr, len)?;
        let lifted = crate::ir::lift_range(self.binary.arch, &partial.insns);
        let (addr_json, addr_hex) = addr_pair(addr);
        Ok(
            serde_json::json!({ "addr": addr_json, "addr_hex": addr_hex, "insns": partial.insns.len(), "ir": lifted, "error_at": partial.error_at }),
        )
    }

    /// Xrefs filtered by endpoint/kind, paged.
    #[must_use]
    pub fn query_xrefs(
        &self,
        to: Option<u64>,
        from: Option<u64>,
        kind: Option<XrefKind>,
        offset: usize,
        limit: usize,
    ) -> Vec<Xref> {
        self.xrefs_matching(to, from, kind)
            .skip(offset)
            .take(limit.min(MAX_ROWS))
            .collect()
    }

    /// Count of xrefs matching the [`Project::query_xrefs`] filters, before
    /// paging. The CLI/MCP `xrefs` envelope reports this as `total` so
    /// large result sets page without scanning blind.
    #[must_use]
    pub fn count_xrefs(&self, to: Option<u64>, from: Option<u64>, kind: Option<XrefKind>) -> usize {
        self.xrefs_matching(to, from, kind).count()
    }

    /// Xrefs matching the endpoint/kind filters, in storage order.
    fn xrefs_matching(
        &self,
        to: Option<u64>,
        from: Option<u64>,
        kind: Option<XrefKind>,
    ) -> impl Iterator<Item = Xref> + '_ {
        self.analysis
            .xrefs
            .iter()
            .copied()
            .filter(move |x| to.is_none_or(|t| x.to == t))
            .filter(move |x| from.is_none_or(|f| x.from == f))
            .filter(move |x| kind.is_none_or(|k| x.kind == k))
    }

    /// Imports plus exports for symbol views.
    ///
    /// Ordinal-only imports carry `ordinal` plus `unresolved: true`;
    /// C++ imports/exports carry `demangled` when [`crate::loader::demangle_cpp`]
    /// recognizes the mangling.
    #[must_use]
    pub fn symbols_json(&self) -> serde_json::Value {
        serde_json::json!({ "imports": self.binary.imports, "exports": self.binary.exports })
    }

    /// Section table in file order: name, virtual address, in-memory size,
    /// file offset/size of the raw bytes, and permissions.
    ///
    /// `vaddr` is the flat virtual address the loader mapped the section at
    /// (PE: `IMAGE_BASE + RVA`, so `.text` at RVA `0x1000` in a
    /// `0x400000`-based image lives at `0x401000`); `file_off` locates the
    /// section's raw bytes in the file. Raw blobs have no table and report
    /// an empty array.
    #[must_use]
    pub fn sections_json(&self) -> serde_json::Value {
        let rows: Vec<serde_json::Value> = self
            .binary
            .sections
            .iter()
            .map(|s| {
                let (vaddr, vaddr_hex) = addr_pair(s.vaddr);
                serde_json::json!({
                    "name": s.name, "vaddr": vaddr, "vaddr_hex": vaddr_hex, "size": s.size,
                    "file_off": s.file_off, "file_size": s.data.len(),
                    "readable": s.readable, "writable": s.writable,
                    "executable": s.executable,
                })
            })
            .collect();
        serde_json::Value::Array(rows)
    }

    /// Extracted strings, filtered then paged (the `strings` command query).
    ///
    /// See [`Analysis::strings_page_filtered`] for the filter semantics:
    /// executable-memory hits are hidden unless the filter opts back in.
    ///
    /// # Errors
    /// [`Error::Invalid`] when the filter pattern is overlong or a `regex:`
    /// expression fails to compile.
    pub fn query_strings(&self, filter: &StringsFilter) -> Result<Vec<StringHit>> {
        self.analysis.strings_page_filtered(filter)
    }

    /// Current annotation at `addr`.
    #[must_use]
    pub fn annotation_json(&self, addr: u64) -> serde_json::Value {
        let (addr_json, addr_hex) = addr_pair(addr);
        match self.annotation(addr) {
            Some(a) => {
                serde_json::json!({ "addr": addr_json, "addr_hex": addr_hex, "name": a.name, "comment": a.comment })
            }
            None => {
                serde_json::json!({ "addr": addr_json, "addr_hex": addr_hex, "name": null, "comment": null })
            }
        }
    }
}

/// Cap on raw bytes per [`Project::bytes_at`] call.
pub const MAX_RANGE_BYTES: usize = 1 << 20;
/// Cap on rows per paged query.
const MAX_ROWS: usize = 1024;

/// Format a virtual address as canonical `0x`-hex (`0x401000`).
///
/// Every JSON address field pairs its integer value with this string form
/// (`addr` + `addr_hex`, `entry` + `entry_hex`, `from` + `from_hex`, ...),
/// so agents can join outputs without guessing the base. Lowercase, no
/// leading zeros (except `0x0` itself).
#[must_use]
pub fn addr_hex(addr: u64) -> String {
    format!("{addr:#x}")
}

/// Dual address encoding: integer value plus canonical `0x`-hex string.
///
/// Returns `(addr, addr_hex(addr))` for spreading into JSON envelopes; the
/// integer keeps numeric range queries working, the string keeps joins
/// unambiguous.
#[must_use]
pub fn addr_pair(addr: u64) -> (u64, String) {
    (addr, addr_hex(addr))
}

/// Dual encoding for optional addresses: `(None, None)` stays null on both
/// sides instead of inventing an address.
#[must_use]
pub fn opt_addr_pair(addr: Option<u64>) -> (Option<u64>, Option<String>) {
    (addr, addr.map(addr_hex))
}

/// Parse a CLI/MCP address: `0x`-prefixed hex or plain decimal.
///
/// # Errors
/// [`Error::Invalid`] when the string is neither.
pub fn parse_addr(s: &str) -> Result<u64> {
    let s = s.trim();
    let v = if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        u64::from_str_radix(hex, 16)
    } else {
        s.parse::<u64>()
    };
    v.map_err(|_| Error::Invalid(format!("bad address: {s:?}")))
}

/// Parse an xref kind filter: `code`, `data`, or `string`.
///
/// # Errors
/// [`Error::Invalid`] for anything else.
pub fn parse_xref_kind(s: &str) -> Result<XrefKind> {
    match s.to_lowercase().as_str() {
        "code" => Ok(XrefKind::Code),
        "data" => Ok(XrefKind::Data),
        "string" => Ok(XrefKind::String),
        _ => Err(Error::Invalid(format!("bad xref kind: {s:?}"))),
    }
}

/// Re-read the binary bytes for a hash-matching cached snapshot.
///
/// Raw blobs need their mapping options again; containers re-parse.
fn reload_binary(bytes: &[u8], raw: Option<RawOptions>) -> Result<LoadedBinary> {
    match raw {
        Some(opts) => load_raw(bytes, opts),
        None => load_or_raw(bytes),
    }
}

/// Read one input file with a hard pre-parse budget.
///
/// Opens the path once and accumulates 64 KiB chunks with checked
/// arithmetic, so `stat`-then-read races and mid-read growth cannot dodge
/// [`crate::loader::MAX_INPUT_BYTES`]. Containers larger than
/// [`crate::loader::MAX_MAPPED_BYTES`] still open when their mapped bytes
/// fit: unmapped overlays/debug data are accepted up to the input cap.
/// Oversize returns [`Error::Limit`] (never `Invalid`), so
/// [`load_or_raw`] does not fall back to raw.
///
/// # Errors
/// [`Error::NotFound`] if the path does not exist, [`Error::Unsupported`]
/// if it is not a file, [`Error::Limit`] past the input cap,
/// [`Error::Storage`] on I/O failure.
fn read_input_bytes(path: &Path) -> Result<Vec<u8>> {
    let meta = std::fs::metadata(path).map_err(|e| match e.kind() {
        std::io::ErrorKind::NotFound => Error::NotFound(path.display().to_string()),
        _ => Error::Storage(format!("stat {}: {e}", path.display())),
    })?;
    if !meta.is_file() {
        return Err(Error::Unsupported(format!(
            "not a file: {}",
            path.display()
        )));
    }
    let file = std::fs::File::open(path).map_err(|e| match e.kind() {
        std::io::ErrorKind::NotFound => Error::NotFound(path.display().to_string()),
        _ => Error::Storage(format!("read {}: {e}", path.display())),
    })?;
    let cap = crate::loader::MAX_INPUT_BYTES;
    let mut reader = file;
    read_stream_capped(&mut reader, cap, &path.display().to_string())
}

/// Accumulate a stream with checked growth against `cap`.
///
/// Split from [`read_input_bytes`] so the exact/over boundary and
/// mid-read growth are unit-testable without a 512 MiB file: every chunk
/// extends the total with [`checked_add`](u64::checked_add) and rejects
/// past `cap` with [`Error::Limit`].
fn read_stream_capped(reader: &mut impl std::io::Read, cap: u64, label: &str) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    let mut chunk = [0u8; 64 * 1024];
    loop {
        let n = std::io::Read::read(reader, &mut chunk)
            .map_err(|e| Error::Storage(format!("read {label}: {e}")))?;
        if n == 0 {
            break;
        }
        let next = (out.len() as u64)
            .checked_add(n as u64)
            .filter(|m| *m <= cap)
            .ok_or_else(|| Error::Limit("input exceeds 512 MiB".to_string()))?;
        out.reserve_exact(n);
        out.extend_from_slice(&chunk[..n]);
        debug_assert_eq!(out.len() as u64, next);
    }
    Ok(out)
}

/// Container parse with raw x86-64 fallback for unrecognized bytes.
///
/// Only [`Error::Invalid`] on unrecognized input falls back; recognized
/// containers with unsupported arches still report [`Error::Unsupported`],
/// and recognized LE images are always rejected: a valid LE parse is refused
/// rather than analyzed, and a malformed-but-recognized LE stays
/// [`Error::Unsupported`] (with the parse error as detail) instead of
/// silently opening as raw x86-64.
fn load_or_raw(bytes: &[u8]) -> Result<LoadedBinary> {
    match load(bytes) {
        Ok(bin) if bin.format == BinaryFormat::Le => Err(le_unsupported(None)),
        Ok(bin) => Ok(bin),
        Err(Error::Invalid(detail)) if crate::loader::le::is_le(bytes) => {
            Err(le_unsupported(Some(detail.as_str())))
        }
        Err(Error::Invalid(_)) => load_raw(
            bytes,
            RawOptions {
                base: 0,
                arch: crate::disasm::Arch::X86_64,
                entry: None,
            },
        ),
        Err(e) => Err(e),
    }
}

/// Explicit-unsupported error for recognized LE images.
///
/// LE bytes are never analyzed and never fall back to raw x86-64, so agents
/// cannot mistake a refusal for a successful analysis.
fn le_unsupported(detail: Option<&str>) -> Error {
    let mut msg = "LE format recognized (format:le, supported:false): \
        Linear Executables are not supported for analysis"
        .to_string();
    if let Some(d) = detail {
        msg.push_str(": ");
        msg.push_str(d);
    }
    Error::Unsupported(msg)
}

#[cfg(test)]
mod tests {
    use super::{parse_addr, parse_xref_kind, read_stream_capped};
    use crate::analysis::XrefKind;
    use crate::error::Error;

    #[test]
    fn parse_addr_hex_equals_decimal() {
        assert_eq!(parse_addr("0x402100").expect("hex"), 0x402100);
        assert_eq!(parse_addr("0X402100").expect("upper hex"), 0x402100);
        assert_eq!(
            parse_addr("4202752").expect("decimal"),
            parse_addr("0x402100").expect("hex")
        );
        assert!(parse_addr("zz").is_err());
    }

    #[test]
    fn parse_xref_kind_is_case_insensitive() {
        for (s, want) in [
            ("code", XrefKind::Code),
            ("Data", XrefKind::Data),
            ("STRING", XrefKind::String),
        ] {
            assert_eq!(parse_xref_kind(s).expect("known kind"), want);
        }
        assert!(parse_xref_kind("nope").is_err());
    }

    #[test]
    fn stream_cap_exact_passes_over_fails() {
        let exact = vec![0x41u8; 16];
        let mut cur = std::io::Cursor::new(exact.clone());
        let got = read_stream_capped(&mut cur, 16, "t").expect("exact cap passes");
        assert_eq!(got, exact);
        let mut cur = std::io::Cursor::new(vec![0x41u8; 17]);
        let err = read_stream_capped(&mut cur, 16, "t").unwrap_err();
        assert!(matches!(err, Error::Limit(_)), "got {err:?}");
    }

    /// A reader that grows past its initial length must still hit the cap:
    /// the accumulator never trusts a stat size.
    #[test]
    fn stream_cap_catches_mid_read_growth() {
        struct Growing {
            left: usize,
        }
        impl std::io::Read for Growing {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                if self.left == 0 {
                    return Ok(0);
                }
                let n = buf.len().min(self.left).min(7);
                buf[..n].fill(0x42);
                self.left -= n;
                Ok(n)
            }
        }
        let mut g = Growing { left: 25 };
        let err = read_stream_capped(&mut g, 16, "g").unwrap_err();
        assert!(matches!(err, Error::Limit(_)), "got {err:?}");
        let mut g = Growing { left: 16 };
        let got = read_stream_capped(&mut g, 16, "g").expect("exact growth passes");
        assert_eq!(got.len(), 16);
    }
}