reknife 1.2.0

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

mod render;

use crate::analysis::engine::{self, Analysis};
use crate::analysis::strings::Located;
use crate::db::Db;
use crate::listing::{self, Line};
use crate::model::Binary;
use anyhow::Result;
use ratatui::crossterm::event::{
    self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
    MouseEventKind,
};
use std::collections::BTreeMap;
use std::io::stdout;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Focus {
    Functions,
    Listing,
    Xrefs,
}

/// What a prompt at the bottom of the screen is collecting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ask {
    Filter,
    Name,
    Note,
    Goto,
}

impl Ask {
    fn label(self) -> &'static str {
        match self {
            Ask::Filter => "filter",
            Ask::Name => "name",
            Ask::Note => "note",
            Ask::Goto => "goto",
        }
    }
}

pub struct Prompt {
    pub ask: Ask,
    pub input: String,
    /// The address a name or note will attach to.
    pub at: u64,
}

pub struct App {
    // ── the target ──
    pub bin: Binary,
    pub bytes: Vec<u8>,
    pub db: Db,
    pub an: Analysis,
    /// Converts a displayed address into the space the database stores.
    pub base: u64,
    pub title: String,

    // ── function list ──
    /// Indices into `an.functions`, after filtering.
    pub order: Vec<usize>,
    pub sel: usize,
    pub filter: String,

    // ── listing ──
    pub cur: Option<u64>,
    pub lines: Vec<Line>,
    pub cursor: usize,

    // ── the rest ──
    pub focus: Focus,
    pub prompt: Option<Prompt>,
    pub history: Vec<(u64, usize)>,
    pub status: String,
    pub help: bool,
    pub quit: bool,
    /// Cursor into the cross-reference list (a separate list pane, so it has a
    /// selection of its own like the other two).
    pub xsel: usize,
    /// Terminal size, refreshed before each frame so mouse coordinates from
    /// events can be mapped onto the panes without guessing.
    pub dims: (u16, u16),
    /// The image's literals keyed by virtual address, built once: bytes never
    /// change while the view is open, and rebuilding per navigation is the
    /// kind of cost a big binary makes obvious.
    pub strings: BTreeMap<u64, Located>,
}

impl App {
    pub fn new(bin: Binary, bytes: Vec<u8>, db: Db, an: Analysis, title: String) -> App {
        let base = engine::display_base(&bin);
        let strings = listing::string_map(&bin, &bytes, base);
        let mut app = App {
            bin,
            bytes,
            db,
            an,
            base,
            title,
            order: Vec::new(),
            sel: 0,
            filter: String::new(),
            cur: None,
            lines: Vec::new(),
            cursor: 0,
            focus: Focus::Functions,
            prompt: None,
            history: Vec::new(),
            status: String::new(),
            help: false,
            quit: false,
            xsel: 0,
            dims: (0, 0),
            strings,
        };
        app.refilter();
        // Open something immediately: an empty right-hand pane makes the tool
        // look broken rather than ready.
        if let Some(&i) = app.order.first() {
            let addr = app.an.functions[i].addr;
            app.open(addr, false);
        }
        app
    }

    // ── function list ──

    /// Rebuild the visible list from the filter, keeping the selected function
    /// selected when it survives the filter.
    pub fn refilter(&mut self) {
        let keep = self.selected_addr();
        let f = self.filter.to_lowercase();
        self.order = self
            .an
            .functions
            .iter()
            .enumerate()
            .filter(|(_, fun)| f.is_empty() || fun.name.to_lowercase().contains(&f))
            .map(|(i, _)| i)
            .collect();
        self.sel = keep
            .and_then(|a| {
                self.order
                    .iter()
                    .position(|&i| self.an.functions[i].addr == a)
            })
            .unwrap_or(0);
    }

    pub fn selected_addr(&self) -> Option<u64> {
        self.order.get(self.sel).map(|&i| self.an.functions[i].addr)
    }

    pub fn move_sel(&mut self, delta: isize) {
        if self.order.is_empty() {
            return;
        }
        let last = self.order.len() - 1;
        self.sel = self.sel.saturating_add_signed(delta).min(last);
    }

    // ── listing ──

    /// Show a function. `push` records where we were, so `Backspace` returns.
    /// An address that is not inside a recovered function opens as a data
    /// dump instead, which is how following a string operand lands somewhere
    /// you can actually look at its bytes.
    pub fn open(&mut self, addr: u64, push: bool) {
        let target = self
            .an
            .find_function(addr)
            .or_else(|| self.an.function_at(addr))
            .map(|f| f.addr);

        let Some(faddr) = target else {
            if self.an.xrefs_from.contains_key(&addr) || self.is_mapped(addr) {
                if push {
                    if let Some(prev) = self.cur {
                        self.history.push((prev, self.cursor));
                    }
                }
                self.lines = listing::data_view(&self.bin, self.base, &self.bytes, addr);
                self.cur = Some(addr);
                self.cursor = 0;
                self.clamp_xsel();
                return;
            }
            self.status = format!(
                "0x{:x} is not inside a recovered function",
                addr + self.base
            );
            return;
        };

        if push {
            if let Some(prev) = self.cur {
                self.history.push((prev, self.cursor));
            }
        }

        let f = self.an.find_function(faddr).expect("just resolved");
        self.lines = listing::function(&self.an, f, &self.db, self.base, &self.strings);
        self.cur = Some(faddr);
        self.clamp_xsel();
        // Land on the requested address, not merely the top of the function.
        self.cursor = self
            .lines
            .iter()
            .position(|l| l.addr() == addr)
            .unwrap_or(0);
        if let Some(p) = self
            .order
            .iter()
            .position(|&i| self.an.functions[i].addr == faddr)
        {
            self.sel = p;
        }
    }

    /// Does the address lie inside a mapped section? The data-view entry
    /// test, kept separate from the function-lookup so the two never blur.
    fn is_mapped(&self, addr: u64) -> bool {
        engine::va_to_off(&self.bin, self.base, addr).is_some()
    }

    pub fn back(&mut self) {
        let Some((addr, cursor)) = self.history.pop() else {
            self.status = "nothing to go back to".into();
            return;
        };
        self.open(addr, false);
        self.cursor = cursor.min(self.lines.len().saturating_sub(1));
    }

    pub fn move_cursor(&mut self, delta: isize) {
        if self.lines.is_empty() {
            return;
        }
        let last = self.lines.len() - 1;
        self.cursor = self.cursor.saturating_add_signed(delta).min(last);
    }

    /// The address the cursor is on, which is what a name, note, or
    /// cross-reference lookup applies to.
    pub fn cursor_addr(&self) -> Option<u64> {
        match self.focus {
            Focus::Listing => self.lines.get(self.cursor).map(Line::addr),
            Focus::Functions => self.selected_addr(),
            // Naming/noting want the address of interest; the xrefs pane
            // selection is a *reference away*, so it reports nothing here.
            Focus::Xrefs => None,
        }
    }

    /// Follow the call or branch under the cursor; an instruction with no
    /// control-flow target falls back to its data operand, opening the
    /// referenced bytes when they are not code.
    pub fn follow(&mut self) {
        let line = self.lines.get(self.cursor);
        if let Some(t) = line.and_then(Line::target) {
            // An import slot has a name but no body; say so rather than failing.
            if self.an.find_function(t).is_none() && self.an.function_at(t).is_none() {
                self.status = match self.an.imports.get(&t) {
                    Some(n) => format!("{n} is imported; there is no body to show"),
                    None => format!("0x{:x} is not a recovered function", t + self.base),
                };
                return;
            }
            self.open(t, true);
            self.focus = Focus::Listing;
            return;
        }

        // No control-flow target: a data operand, if the engine found one.
        let at = line.map(Line::addr).unwrap_or(0);
        let to = match self.an.xrefs_from.get(&at).map(|r| r.first().map(|r| r.to)) {
            Some(Some(t)) => t,
            _ => {
                self.status = "nothing to follow here".into();
                return;
            }
        };
        self.open(to, true);
        self.focus = Focus::Listing;
    }

    /// Cross-references to whatever is under the cursor.
    pub fn xrefs(&self) -> (u64, &[engine::Xref]) {
        let at = self.cursor_addr().or(self.cur).unwrap_or(0);
        (
            at,
            self.an.xrefs_to.get(&at).map(Vec::as_slice).unwrap_or(&[]),
        )
    }

    /// The reference the cursor in the xrefs pane is on.
    pub fn selected_xref(&self) -> Option<engine::Xref> {
        let (_, refs) = self.xrefs();
        refs.get(self.xsel).copied()
    }

    pub fn clamp_xsel(&mut self) {
        let n = self.xrefs().1.len();
        if n == 0 {
            self.xsel = 0;
        } else {
            self.xsel = self.xsel.min(n - 1);
        }
    }

    pub fn move_xsel(&mut self, delta: isize) {
        let n = self.xrefs().1.len();
        if n == 0 {
            self.xsel = 0;
            return;
        }
        let last = n - 1;
        self.xsel = self.xsel.saturating_add_signed(delta).min(last);
    }

    /// Follow the xref under the cursor: jump to wherever it points.
    pub fn jump_xref(&mut self) {
        let Some(x) = self.selected_xref() else {
            self.status = "no reference under the cursor".into();
            return;
        };
        if self.an.function_at(x.from).is_none() && self.an.find_function(x.from).is_none() {
            self.status = format!("0x{:x} is not in a recovered function", x.from + self.base);
            return;
        }
        self.open(x.from, true);
        self.focus = Focus::Listing;
    }

    // ── annotations ──

    fn commit(&mut self, ask: Ask, at: u64, text: String) {
        let stored = at.wrapping_sub(self.base);
        match ask {
            Ask::Filter => {
                self.filter = text;
                self.refilter();
            }
            Ask::Goto => {
                match parse_addr(&text)
                    .map(|v| vec![v])
                    .filter(|v| !v.is_empty())
                    .or_else(|| Some(self.an.resolve(&text, None)))
                    .filter(|v| !v.is_empty())
                {
                    Some(v) => self.open(v[0], true),
                    None => self.status = format!("no symbol or address '{text}'"),
                }
            }
            Ask::Name => {
                if text.is_empty() {
                    let (n, _) = self.db.clear(stored);
                    self.status = match n {
                        Some(old) => format!("cleared the name {old}"),
                        None => "nothing to clear".into(),
                    };
                } else {
                    self.db.set_name(stored, &text);
                    self.status = format!("named 0x{at:x} {text}");
                }
                self.save();
                self.rename_in_place(at);
            }
            Ask::Note => {
                if text.is_empty() {
                    self.db.clear(stored);
                    self.status = "cleared the note".into();
                } else {
                    self.db.set_note(stored, &text);
                    self.status = format!("noted 0x{at:x}");
                }
                self.save();
                self.relist();
            }
        }
    }

    fn save(&mut self) {
        if let Err(e) = self.db.save() {
            self.status = format!("could not save: {e:#}");
        }
    }

    /// Apply a rename without re-running the engine when we can, because a full
    /// re-analysis of a large image is slow enough to feel like a hang.
    fn rename_in_place(&mut self, at: u64) {
        let name = self.db.names.get(&at.wrapping_sub(self.base)).cloned();
        let known = self.an.find_function(at).is_some();

        match (name, known) {
            (Some(n), true) => {
                self.an.names.insert(at, n.clone());
                if let Some(f) = self.an.functions.iter_mut().find(|f| f.addr == at) {
                    f.name = n;
                    f.named = true;
                }
            }
            (None, true) => {
                self.an.names.remove(&at);
                if let Some(f) = self.an.functions.iter_mut().find(|f| f.addr == at) {
                    f.name = format!("sub_{at:x}");
                    f.named = false;
                }
            }
            // Naming an address with no function there is a request to find
            // one, and only the engine can do that.
            _ => self.reanalyze(),
        }
        self.refilter();
        self.relist();
    }

    fn relist(&mut self) {
        if let Some(addr) = self.cur {
            if let Some(f) = self.an.find_function(addr) {
                self.lines = listing::function(&self.an, f, &self.db, self.base, &self.strings);
                self.cursor = self.cursor.min(self.lines.len().saturating_sub(1));
            } else if engine::va_to_off(&self.bin, self.base, addr).is_some() {
                self.lines = listing::data_view(&self.bin, self.base, &self.bytes, addr);
                self.cursor = self.cursor.min(self.lines.len().saturating_sub(1));
            }
        }
    }

    pub fn reanalyze(&mut self) {
        self.an = engine::analyze(&self.bin, &self.bytes, 2_000_000, &self.db);
        self.refilter();
        self.relist();
    }

    // ── input ──

    pub fn on_key(&mut self, key: KeyEvent) {
        if key.kind != KeyEventKind::Press {
            return; // Windows reports releases too; acting on both double-fires
        }

        if let Some(p) = &mut self.prompt {
            match key.code {
                KeyCode::Esc => self.prompt = None,
                KeyCode::Enter => {
                    let p = self.prompt.take().expect("checked above");
                    self.commit(p.ask, p.at, p.input);
                }
                KeyCode::Backspace => {
                    p.input.pop();
                    // A filter should react as it is typed.
                    if p.ask == Ask::Filter {
                        let text = p.input.clone();
                        self.filter = text;
                        self.refilter();
                    }
                }
                KeyCode::Char(c) => {
                    p.input.push(c);
                    if p.ask == Ask::Filter {
                        let text = p.input.clone();
                        self.filter = text;
                        self.refilter();
                    }
                }
                _ => {}
            }
            return;
        }

        if self.help {
            self.help = false;
            return;
        }

        self.status.clear();
        let page = 20isize;
        match key.code {
            KeyCode::Char('q') | KeyCode::Esc => self.quit = true,
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => self.quit = true,
            KeyCode::Char('?') => self.help = true,
            KeyCode::Tab => {
                self.focus = match self.focus {
                    Focus::Functions => Focus::Listing,
                    Focus::Listing => Focus::Xrefs,
                    Focus::Xrefs => Focus::Functions,
                }
            }
            KeyCode::Down | KeyCode::Char('j') => self.step(1),
            KeyCode::Up | KeyCode::Char('k') => self.step(-1),
            KeyCode::PageDown => self.step(page),
            KeyCode::PageUp => self.step(-page),
            KeyCode::Home => self.step(isize::MIN / 2),
            KeyCode::End => self.step(isize::MAX / 2),
            KeyCode::Enter => match self.focus {
                Focus::Functions => {
                    if let Some(a) = self.selected_addr() {
                        self.open(a, true);
                        self.focus = Focus::Listing;
                    }
                }
                Focus::Listing => self.follow(),
                Focus::Xrefs => self.jump_xref(),
            },
            KeyCode::Backspace => self.back(),
            KeyCode::Char('/') => self.ask(Ask::Filter),
            KeyCode::Char('g') => self.ask(Ask::Goto),
            KeyCode::Char('n') => self.ask(Ask::Name),
            KeyCode::Char('c') => self.ask(Ask::Note),
            KeyCode::Char('r') => {
                self.reanalyze();
                self.status = "re-analysed".into();
            }
            _ => {}
        }
    }

    fn step(&mut self, delta: isize) {
        match self.focus {
            Focus::Functions => self.move_sel(delta),
            Focus::Listing => self.move_cursor(delta),
            Focus::Xrefs => self.move_xsel(delta),
        }
    }

    fn ask(&mut self, ask: Ask) {
        let at = self.cursor_addr().unwrap_or(0);
        // Editing an existing value should start from it rather than blank.
        let stored = at.wrapping_sub(self.base);
        let input = match ask {
            Ask::Filter => self.filter.clone(),
            Ask::Name => self.db.names.get(&stored).cloned().unwrap_or_default(),
            Ask::Note => self.db.notes.get(&stored).cloned().unwrap_or_default(),
            Ask::Goto => String::new(),
        };
        self.prompt = Some(Prompt { ask, input, at });
    }

    // ── mouse ──

    /// The pane a terminal position belongs to, given the size stored before
    /// the last frame. The layout mirrors `render::draw`, kept in one place so
    /// the two cannot disagree.
    pub fn pane_at(&self, column: u16, row: u16) -> Option<(Focus, usize)> {
        let (w, h) = self.dims;
        if w == 0 || h == 0 {
            return None;
        }
        // header at row 0, footer at h-1; body is rows 1..h-2.
        if row < 1 || row >= h.saturating_sub(1) {
            return None;
        }
        let body_h = h.saturating_sub(2);
        let fns_w = 34.min(w);
        let xrefs_h = 8u16.min(body_h);
        let (focus, list_len, pane_row) = if column < fns_w {
            (Focus::Functions, self.order.len(), row)
        } else if row + xrefs_h < h.saturating_sub(1) {
            (Focus::Listing, self.lines.len(), row)
        } else {
            (
                Focus::Xrefs,
                self.xrefs().1.len(),
                row - (h.saturating_sub(1) - xrefs_h),
            )
        };
        // row 0 of the pane is the border, row 1 the title; items start there.
        let idx = pane_row.saturating_sub(2) as usize;
        Some((
            focus,
            if list_len == 0 {
                0
            } else {
                idx.min(list_len - 1)
            },
        ))
    }

    pub fn on_mouse(&mut self, m: MouseEvent) {
        match m.kind {
            MouseEventKind::ScrollUp => self.step(-1),
            MouseEventKind::ScrollDown => self.step(1),
            MouseEventKind::Down(MouseButton::Left) => {
                let Some((focus, idx)) = self.pane_at(m.column, m.row) else {
                    return;
                };
                self.focus = focus;
                match focus {
                    Focus::Functions => {
                        self.sel = idx;
                        if let Some(a) = self.selected_addr() {
                            self.open(a, false);
                        }
                    }
                    Focus::Listing => self.cursor = idx.min(self.lines.len().saturating_sub(1)),
                    Focus::Xrefs => self.xsel = idx,
                }
            }
            _ => {}
        }
    }
}

fn parse_addr(s: &str) -> Option<u64> {
    let t = s.trim();
    t.strip_prefix("0x")
        .or_else(|| t.strip_prefix("0X"))
        .and_then(|h| u64::from_str_radix(h, 16).ok())
}

/// Run the interactive view until the user quits.
pub fn run(mut app: App) -> Result<()> {
    // `try_init` rather than `init`, so running this with output piped fails
    // with a sentence instead of a panic. It installs a panic hook that
    // restores the terminal, so a crash cannot leave the shell in raw mode.
    let mut term = ratatui::try_init()
        .map_err(|e| anyhow::anyhow!("cannot start the interactive view: {e}"))?;
    let _ = ratatui::crossterm::execute!(&mut stdout(), event::EnableMouseCapture);
    let res = loop {
        if let Ok(area) = term.size() {
            app.dims = (area.width, area.height);
        }
        if let Err(e) = term.draw(|f| render::draw(f, &app)) {
            break Err(e.into());
        }
        match event::read() {
            Ok(Event::Key(k)) => app.on_key(k),
            Ok(Event::Mouse(m)) => app.on_mouse(m),
            Ok(_) => {}
            Err(e) => break Err(e.into()),
        }
        if app.quit {
            break Ok(());
        }
    };
    let _ = ratatui::crossterm::execute!(&mut stdout(), event::DisableMouseCapture);
    ratatui::restore();
    res
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Arch, Format, Section};

    fn app_with(code: &[u8], vaddr: u64) -> App {
        let mut bin = Binary::stub(Format::Elf, Arch::X86_64);
        bin.entry = vaddr;
        bin.sections = vec![Section {
            name: ".text".into(),
            vaddr,
            vsize: code.len() as u64,
            file_off: vaddr,
            file_size: code.len() as u64,
            entropy: 0.0,
            read: true,
            write: false,
            exec: true,
        }];
        let mut bytes = vec![0u8; vaddr as usize];
        bytes.extend_from_slice(code);
        let db = Db::default();
        let an = engine::analyze(&bin, &bytes, 10_000, &db);
        App::new(bin, bytes, db, an, "t".into())
    }

    /// entry calls sub, both return.
    fn two_functions() -> App {
        // 0x1000: e8 06 00 00 00   call 0x100b
        // 0x1005: c3               ret
        // ...pad...
        // 0x100b: c3               ret
        let mut code = vec![0u8; 12];
        code[0] = 0xe8;
        code[1..5].copy_from_slice(&6i32.to_le_bytes());
        code[5] = 0xc3;
        code[11] = 0xc3;
        app_with(&code, 0x1000)
    }

    #[test]
    fn opens_something_on_start() {
        let app = two_functions();
        assert!(app.cur.is_some(), "a pane should never start empty");
        assert!(!app.lines.is_empty());
    }

    #[test]
    fn filtering_keeps_the_selection_when_it_survives() {
        let mut app = two_functions();
        let before = app.selected_addr();
        app.filter = "entry".into();
        app.refilter();
        assert_eq!(app.selected_addr(), before);
        assert_eq!(app.order.len(), 1);
    }

    #[test]
    fn filtering_that_matches_nothing_leaves_an_empty_list() {
        let mut app = two_functions();
        app.filter = "nothing_matches_this".into();
        app.refilter();
        assert!(app.order.is_empty());
        assert_eq!(app.selected_addr(), None);
        // and navigation on an empty list must not panic
        app.move_sel(1);
        app.move_sel(-1);
    }

    #[test]
    fn following_a_call_pushes_history_and_back_returns() {
        let mut app = two_functions();
        app.open(0x1000, false);
        app.focus = Focus::Listing;
        // the call is the first instruction
        app.cursor = 0;
        app.follow();
        assert_eq!(app.cur, Some(0x100b), "followed into the callee");

        app.back();
        assert_eq!(app.cur, Some(0x1000), "and came back");
        assert!(app.history.is_empty());
    }

    #[test]
    fn back_with_no_history_says_so_instead_of_panicking() {
        let mut app = two_functions();
        app.history.clear();
        app.back();
        assert!(app.status.contains("nothing to go back to"));
    }

    #[test]
    fn naming_updates_the_list_and_the_database() {
        let mut app = two_functions();
        app.open(0x100b, false);
        app.commit(Ask::Name, 0x100b, "parse_header".into());

        assert_eq!(app.an.label(0x100b), "parse_header");
        assert_eq!(
            app.db.names.get(&0x100b).map(String::as_str),
            Some("parse_header")
        );
        assert!(app
            .order
            .iter()
            .any(|&i| app.an.functions[i].name == "parse_header"));
    }

    #[test]
    fn an_empty_name_clears_it() {
        let mut app = two_functions();
        app.commit(Ask::Name, 0x100b, "tmp".into());
        assert_eq!(app.an.label(0x100b), "tmp");
        app.commit(Ask::Name, 0x100b, String::new());
        assert_eq!(app.an.label(0x100b), "sub_100b");
        assert!(app.db.names.is_empty());
    }

    #[test]
    fn a_note_shows_up_in_the_listing() {
        let mut app = two_functions();
        app.open(0x1000, false);
        app.commit(Ask::Note, 0x1000, "starts here".into());
        let annotated = app.lines.iter().any(|l| {
            matches!(l, Line::Insn { annot: Some(crate::listing::Annot::Note(n)), .. } if n == "starts here")
        });
        assert!(annotated, "the note should appear against the instruction");
    }

    #[test]
    fn goto_accepts_a_symbol_or_an_address() {
        let mut app = two_functions();
        app.commit(Ask::Goto, 0, "0x100b".into());
        assert_eq!(app.cur, Some(0x100b));

        app.commit(Ask::Goto, 0, "entry".into());
        assert_eq!(app.cur, Some(0x1000));

        app.commit(Ask::Goto, 0, "no_such_thing".into());
        assert!(app.status.contains("no symbol or address"));
    }

    #[test]
    fn opening_an_address_inside_a_function_lands_on_that_line() {
        let mut app = two_functions();
        app.open(0x1005, false); // the `ret`, not the function head
        assert_eq!(app.cur, Some(0x1000), "resolves to the containing function");
        assert_eq!(
            app.lines.get(app.cursor).map(Line::addr),
            Some(0x1005),
            "and puts the cursor on the requested address"
        );
    }

    /// Draw the whole interface into an off-screen buffer and return its text.
    /// This is the only automated check that rendering does not panic, which
    /// matters because a layout mistake shows up as a crash, not a wrong pixel.
    fn rendered(app: &App, w: u16, h: u16) -> String {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;
        let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
        term.draw(|f| render::draw(f, app)).unwrap();
        term.backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect()
    }

    #[test]
    fn the_interface_renders() {
        let app = two_functions();
        let out = rendered(&app, 110, 30);
        assert!(out.contains("functions"), "the function list is drawn");
        assert!(out.contains("entry"), "and lists what was recovered");
        assert!(out.contains("xrefs"), "the xref pane is drawn");
        assert!(out.contains("open/follow"), "the key hints are drawn");
    }

    #[test]
    fn it_renders_in_a_very_small_terminal() {
        // Layout arithmetic that underflows shows up here as a panic.
        let app = two_functions();
        for (w, h) in [(20u16, 6u16), (40, 10), (1, 1), (200, 60)] {
            let _ = rendered(&app, w, h);
        }
    }

    #[test]
    fn the_help_overlay_and_prompt_render() {
        let mut app = two_functions();
        app.help = true;
        assert!(rendered(&app, 110, 30).contains("re-analyse"));

        app.help = false;
        app.prompt = Some(Prompt {
            ask: Ask::Name,
            input: "parse_header".into(),
            at: 0x1000,
        });
        let out = rendered(&app, 110, 30);
        assert!(out.contains("name:"), "the prompt shows what it wants");
        assert!(out.contains("parse_header"), "and what has been typed");
    }

    #[test]
    fn typing_in_a_prompt_edits_it_and_escape_abandons_it() {
        let mut app = two_functions();
        app.on_key(KeyEvent::from(KeyCode::Char('n')));
        assert!(app.prompt.is_some());

        for c in "abc".chars() {
            app.on_key(KeyEvent::from(KeyCode::Char(c)));
        }
        app.on_key(KeyEvent::from(KeyCode::Backspace));
        assert_eq!(app.prompt.as_ref().unwrap().input, "ab");

        app.on_key(KeyEvent::from(KeyCode::Esc));
        assert!(app.prompt.is_none(), "escape abandons without saving");
        assert!(app.db.names.is_empty());
        assert!(!app.quit, "escape closed the prompt, it did not quit");
    }

    #[test]
    fn key_releases_are_ignored() {
        // Windows delivers press and release; acting on both moves twice.
        let mut app = two_functions();
        app.focus = Focus::Functions;
        let before = app.sel;
        app.on_key(KeyEvent::new_with_kind(
            KeyCode::Down,
            KeyModifiers::NONE,
            KeyEventKind::Release,
        ));
        assert_eq!(app.sel, before);
    }

    // ── xrefs pane ──

    #[test]
    fn tab_cycles_through_three_panes() {
        let mut app = two_functions();
        assert_eq!(app.focus, Focus::Functions);
        for _ in 0..2 {
            app.on_key(KeyEvent::from(KeyCode::Tab));
        }
        assert_eq!(app.focus, Focus::Xrefs);
        app.on_key(KeyEvent::from(KeyCode::Tab));
        assert_eq!(app.focus, Focus::Functions);
    }

    #[test]
    fn the_xref_cursor_jumps_to_the_reference_site() {
        let mut app = two_functions();
        // sub_100b is called once, from 0x1000.
        app.open(0x100b, false);
        assert_eq!(app.xrefs().1.len(), 1);
        app.focus = Focus::Xrefs;
        app.on_key(KeyEvent::from(KeyCode::Enter));
        assert_eq!(app.cur, Some(0x1000), "jumped to the call site");
        assert_eq!(app.focus, Focus::Listing, "and landed in the listing");
    }

    #[test]
    fn xsel_is_clamped_when_the_target_changes() {
        let mut app = two_functions();
        app.open(0x100b, false); // one reference
        app.focus = Focus::Xrefs;
        app.xsel = 5;
        app.open(0x1000, false); // entry has no references
        assert_eq!(app.xsel, 0);
    }

    #[test]
    fn nothing_to_jump_to_says_so_instead_of_panicking() {
        let mut app = two_functions();
        app.open(0x1000, false); // entry has no incoming references
        app.focus = Focus::Xrefs;
        app.on_key(KeyEvent::from(KeyCode::Enter));
        assert!(app.status.contains("no reference"));
    }

    // ── data refs ──

    /// entry lea's the string and returns; the literal sits in .rodata.
    fn data_ref_app() -> App {
        // lea rax, [rip+0x15] at 0x1000: ends at 0x1007, targets 0x101c.
        let mut bytes = vec![0x48, 0x8d, 0x05, 0x15, 0x00, 0x00, 0x00, 0xc3];
        bytes.extend_from_slice(b"hi there");
        let mut bin = Binary::stub(Format::Elf, Arch::X86_64);
        bin.entry = 0x1000;
        bin.sections = vec![
            Section {
                name: ".text".into(),
                vaddr: 0x1000,
                vsize: 8,
                file_off: 0,
                file_size: 8,
                entropy: 0.0,
                read: true,
                write: false,
                exec: true,
            },
            Section {
                name: ".rodata".into(),
                vaddr: 0x101c,
                vsize: 8,
                file_off: 8,
                file_size: 8,
                entropy: 0.0,
                read: true,
                write: false,
                exec: false,
            },
        ];
        let db = Db::default();
        let an = engine::analyze(&bin, &bytes, 10_000, &db);
        App::new(bin, bytes, db, an, "t".into())
    }

    #[test]
    fn the_literal_is_annotated_in_the_listing() {
        let app = data_ref_app();
        assert!(
            app.lines.iter().any(|l| matches!(
                l,
                Line::Insn {
                    annot: Some(crate::listing::Annot::Text(t)),
                    ..
                } if t == "hi there"
            )),
            "the lea should be annotated with the literal"
        );
    }

    #[test]
    fn following_a_string_operand_opens_its_bytes() {
        let mut app = data_ref_app();
        app.focus = Focus::Listing;
        app.cursor = 0; // the lea
        app.follow();
        assert_eq!(app.cur, Some(0x101c), "followed the data ref");
        assert!(
            app.lines.iter().all(|l| matches!(l, Line::Data { .. })),
            "a string opens as a hex dump, not as code"
        );

        app.back();
        assert_eq!(app.cur, Some(0x1000), "and back returns to the lea");
        assert_eq!(app.cursor, 0);
    }

    // ── mouse ──

    fn mouse(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent {
        MouseEvent {
            kind,
            column,
            row,
            modifiers: KeyModifiers::NONE,
        }
    }

    #[test]
    fn the_wheel_scrolls_the_focused_pane() {
        let mut app = data_ref_app();
        app.focus = Focus::Listing;
        app.cursor = 0;
        app.on_mouse(mouse(MouseEventKind::ScrollDown, 0, 0));
        assert_eq!(app.cursor, 1, "wheel scrolls the listing");

        app.focus = Focus::Functions;
        let before = app.sel;
        app.on_mouse(mouse(MouseEventKind::ScrollUp, 0, 0));
        assert_eq!(app.sel, before.saturating_sub(1), "and the function list");
    }

    #[test]
    fn a_click_focuses_that_pane_and_selects_the_row() {
        let mut app = data_ref_app();
        app.dims = (110, 30);
        // A click in the left pane lands on the function list; with a single
        // recovered function the row index clamps to it.
        app.on_mouse(mouse(MouseEventKind::Down(MouseButton::Left), 5, 4));
        assert_eq!(app.focus, Focus::Functions);
        assert_eq!(app.selected_addr(), Some(0x1000));

        // A click in the bottom-right corner lands in the xrefs pane.
        app.on_mouse(mouse(MouseEventKind::Down(MouseButton::Left), 60, 26));
        assert_eq!(app.focus, Focus::Xrefs);
    }
}