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
use std::path::PathBuf;
use std::sync::mpsc;
use crate::error::{Error, Result};
use crate::prelude::Analyzer;
use crate::tui::command::*;
use crate::tui::event::Event;
use crate::tui::ui::{Tab, ELF_INFO_TABS, MAIN_TABS};
use crate::tui::widgets::list::SelectableList;
use crate::tui::widgets::logo::Logo;
use ansi_to_tui::IntoText;
use heh::windows::Window;
use ratatui::style::Color;
use tui_input::backend::crossterm::EventHandler;
use tui_input::Input;
/// Application state.
#[derive(Debug)]
pub struct State<'a> {
/// Is the application running?
pub running: bool,
/// Binary analyzer.
pub analyzer: Analyzer<'a>,
/// Selected tab.
pub tab: Tab,
/// Elf info.
pub info_index: usize,
/// Selected block in static analysis.
pub block_index: usize,
/// List items.
pub list: SelectableList<Vec<String>>,
/// Show heh.
pub show_heh: bool,
/// Show details.
pub show_details: bool,
/// Input.
pub input: Input,
/// Enable input.
pub input_mode: bool,
/// Strings call completed.
pub strings_loaded: bool,
/// System calls completed.
pub system_calls_loaded: bool,
/// System calls scroll index.
pub dynamic_scroll_index: usize,
/// File info scroll index.
pub general_scroll_index: usize,
/// Notes scroll index.
pub notes_scroll_index: usize,
/// File headers scroll index.
pub headers_scroll_index: usize,
/// Terminal accent color.
pub accent_color: Color,
/// Logo widget.
pub logo: Logo,
}
impl<'a> State<'a> {
/// Constructs a new instance of [`State`].
pub fn new(analyzer: Analyzer<'a>, accent_color: Option<Color>) -> Result<Self> {
let mut state = Self {
running: true,
tab: Tab::default(),
info_index: 0,
block_index: 2,
list: SelectableList::default(),
analyzer,
show_heh: false,
show_details: false,
input: Input::default(),
input_mode: false,
strings_loaded: false,
system_calls_loaded: false,
dynamic_scroll_index: 0,
general_scroll_index: 0,
notes_scroll_index: 0,
headers_scroll_index: 0,
accent_color: accent_color.unwrap_or(Color::White),
logo: Logo::default(),
};
state.handle_tab()?;
Ok(state)
}
/// Runs a command and updates the state.
pub fn run_command(
&mut self,
command: Command,
event_sender: mpsc::Sender<Event>,
) -> Result<()> {
match command {
Command::Input(command) => {
match command {
InputCommand::Handle(event) => {
self.input.handle_event(&event);
if self.tab == Tab::DynamicAnalysis {
self.dynamic_scroll_index = 0;
}
}
InputCommand::Enter => {
if self.tab != Tab::DynamicAnalysis || self.system_calls_loaded {
self.input_mode = true;
}
}
InputCommand::Confirm => {
self.input_mode = false;
}
InputCommand::Resume(event) => {
if self.tab == Tab::General {
event_sender
.send(Event::Restart(None))
.expect("failed to send restart event");
return Ok(());
}
if !self.input.value().is_empty() {
self.input_mode = true;
self.input.handle_event(&event);
}
}
InputCommand::Exit => {
self.input = Input::default();
self.input_mode = false;
}
}
self.handle_tab()?;
}
Command::Hexdump(command) => match command {
HexdumpCommand::Handle(event) => {
self.analyzer
.heh
.handle_input(&event)
.map_err(|e| Error::HexdumpError(e.to_string()))?;
}
HexdumpCommand::HandleCustom(event, original_event) => {
self.analyzer
.heh
.handle_input(
&if self.analyzer.heh.key_handler.is_focusing(Window::Search)
|| self
.analyzer
.heh
.key_handler
.is_focusing(Window::JumpToByte)
{
original_event
} else {
event
},
)
.map_err(|e| Error::HexdumpError(e.to_string()))?;
}
HexdumpCommand::Warn(message, event) => {
if self.analyzer.heh.key_handler.is_focusing(Window::Search)
|| self
.analyzer
.heh
.key_handler
.is_focusing(Window::JumpToByte)
{
self.analyzer
.heh
.handle_input(&event)
.map_err(|e| Error::HexdumpError(e.to_string()))?;
} else {
self.analyzer.heh.labels.notification = message;
}
}
HexdumpCommand::CancelNext => {
self.tab = ((self.tab as usize + 1) % MAIN_TABS.len()).into();
self.handle_tab()?;
}
HexdumpCommand::CancelPrevious => {
self.tab = (self.tab as usize)
.checked_sub(1)
.unwrap_or(MAIN_TABS.len() - 1)
.into();
self.handle_tab()?;
}
HexdumpCommand::Exit(event) => {
if self.analyzer.heh.key_handler.is_focusing(Window::Search)
|| self
.analyzer
.heh
.key_handler
.is_focusing(Window::JumpToByte)
{
self.analyzer
.heh
.handle_input(&event)
.map_err(|e| Error::HexdumpError(e.to_string()))?;
} else {
self.running = false;
}
}
},
Command::ShowDetails => {
if self.tab == Tab::General {
if let Some(path) = self.list.selected().map(|v| PathBuf::from(v[1].clone())) {
event_sender
.send(Event::Restart(Some(path)))
.expect("failed to send trace event");
}
return Ok(());
} else if self.tab == Tab::DynamicAnalysis && !self.system_calls_loaded {
event_sender
.send(Event::Trace)
.expect("failed to send trace event");
return Ok(());
} else {
self.show_details = !self.show_details;
}
}
Command::OpenRepo => {
if self.tab == Tab::General {
webbrowser::open(env!("CARGO_PKG_HOMEPAGE"))?;
}
}
Command::TraceCalls => {
if self.tab == Tab::DynamicAnalysis {
event_sender
.send(Event::Trace)
.expect("failed to send trace event");
}
}
Command::Next(scroll_type, amount) => match scroll_type {
ScrollType::Tab => {
self.tab = (((self.tab as usize).checked_add(amount).unwrap_or_default())
% MAIN_TABS.len())
.into();
self.handle_tab()?;
}
ScrollType::Table => {
if self.tab == Tab::StaticAnalysis {
self.info_index = (self.info_index.checked_add(amount).unwrap_or_default())
% ELF_INFO_TABS.len();
self.handle_tab()?;
} else if self.tab == Tab::General {
self.general_scroll_index =
self.general_scroll_index.saturating_add(amount);
}
}
ScrollType::List => {
if self.tab == Tab::DynamicAnalysis {
self.dynamic_scroll_index =
self.dynamic_scroll_index.saturating_add(amount);
} else if self.tab == Tab::StaticAnalysis {
match self.block_index {
0 => {
self.headers_scroll_index =
self.headers_scroll_index.saturating_add(amount);
}
1 => {
self.notes_scroll_index =
self.notes_scroll_index.saturating_add(amount);
}
_ => self.list.next(amount),
}
} else {
self.list.next(amount)
}
}
ScrollType::Block => {
if self.tab == Tab::StaticAnalysis {
self.block_index = (self.block_index.saturating_add(1)) % 3;
}
}
},
Command::Previous(scroll_type, amount) => match scroll_type {
ScrollType::Tab => {
self.tab = (self.tab as usize)
.checked_sub(amount)
.unwrap_or(MAIN_TABS.len() - 1)
.into();
self.handle_tab()?;
}
ScrollType::Table => {
if self.tab == Tab::StaticAnalysis {
self.info_index = self
.info_index
.checked_sub(amount)
.unwrap_or(ELF_INFO_TABS.len() - 1);
self.handle_tab()?;
} else if self.tab == Tab::General {
self.general_scroll_index =
self.general_scroll_index.saturating_sub(amount);
}
}
ScrollType::List => {
if self.tab == Tab::DynamicAnalysis {
self.dynamic_scroll_index =
self.dynamic_scroll_index.saturating_sub(amount);
} else if self.tab == Tab::StaticAnalysis {
match self.block_index {
0 => {
self.headers_scroll_index =
self.headers_scroll_index.saturating_sub(amount);
}
1 => {
self.notes_scroll_index =
self.notes_scroll_index.saturating_sub(amount);
}
_ => self.list.previous(amount),
}
} else {
self.list.previous(amount)
}
}
ScrollType::Block => {
if self.tab == Tab::StaticAnalysis {
self.block_index = self.block_index.checked_sub(1).unwrap_or(2);
}
}
},
Command::Top => {
if self.tab == Tab::DynamicAnalysis {
self.dynamic_scroll_index = 0;
} else {
self.list.first();
}
}
Command::Bottom => {
if self.tab == Tab::DynamicAnalysis {
self.dynamic_scroll_index = self
.analyzer
.tracer
.syscalls
.into_text()
.unwrap_or_default()
.lines
.len();
} else {
self.list.last();
}
}
Command::Increment => {
if self.tab == Tab::Strings {
self.analyzer.strings_len = self
.analyzer
.strings_len
.checked_add(1)
.unwrap_or(self.analyzer.strings_len);
self.strings_loaded = false;
self.analyzer.extract_strings(event_sender.clone());
}
}
Command::Decrement => {
if self.tab == Tab::Strings {
if self.analyzer.strings_len > 1 {
self.analyzer.strings_len =
self.analyzer.strings_len.checked_sub(1).unwrap_or_default();
}
self.strings_loaded = false;
self.analyzer.extract_strings(event_sender.clone());
}
}
Command::Exit => {
if self.show_details {
self.show_details = false;
} else {
self.running = false;
}
}
Command::HumanReadable => {
if self.tab == Tab::StaticAnalysis {
self.analyzer.elf.program_headers.toggle_readability();
self.analyzer.elf.section_headers.toggle_readability();
self.handle_tab()?;
}
}
Command::Nothing => {}
}
Ok(())
}
/// Update the state based on selected tab.
pub fn handle_tab(&mut self) -> Result<()> {
self.show_heh = false;
match self.tab {
Tab::General => {
self.list = SelectableList::with_items(
self.analyzer
.dependencies
.clone()
.into_iter()
.map(|(name, lib)| vec![name, lib])
.collect(),
);
}
Tab::StaticAnalysis => {
self.list = SelectableList::with_items(
self.analyzer
.elf
.info(&ELF_INFO_TABS[self.info_index])
.items()
.into_iter()
.filter(|items| {
self.input.value().is_empty()
|| items.iter().any(|item| {
item.to_lowercase()
.contains(&self.input.value().to_lowercase())
})
})
.collect(),
);
}
Tab::DynamicAnalysis => {
self.analyzer.system_calls = self
.analyzer
.tracer
.syscalls
.into_text()
.unwrap_or_else(|_| "ANSI error occurred".into())
.lines
.into_iter()
.filter(|line| {
self.input.value().is_empty()
|| line
.clone()
.reset_style()
.to_string()
.to_lowercase()
.contains(&self.input.value().to_lowercase())
})
.collect();
}
Tab::Strings => {
self.list = SelectableList::with_items(
self.analyzer
.strings
.clone()
.unwrap_or_default()
.iter()
.map(|(v, i)| vec![v.to_string(), i.to_string()])
.filter(|items| {
self.input.value().is_empty()
|| items.iter().any(|item| {
item.to_lowercase()
.contains(&self.input.value().to_lowercase())
})
})
.collect(),
)
}
Tab::Hexdump => {
self.show_heh = true;
}
}
Ok(())
}
/// Returns the key bindings.
pub fn get_key_bindings(&self) -> Vec<(&'a str, &'a str)> {
match self.tab {
Tab::General => {
vec![
("o", "Open docs"),
("⏎ ", "Analyze lib"),
("h/j/k/l", "Scroll"),
("Tab", "Next"),
("⇧+Tab", "Previous"),
("Bksp", "Back"),
("q", "Quit"),
]
}
Tab::StaticAnalysis => vec![
("Enter", "Details"),
("/", "Search"),
("h/j/k/l", "Scroll"),
("n/p", "Toggle"),
("s", "Readability"),
("Tab", "Next"),
("q", "Quit"),
],
Tab::DynamicAnalysis => {
if self.system_calls_loaded {
vec![
("Enter", "Details"),
("r", "Re-run"),
("/", "Search"),
("h/j/k/l", "Scroll"),
("Tab", "Next"),
("q", "Quit"),
]
} else {
vec![
("Enter", "Run"),
("/", "Search"),
("h/j/k/l", "Scroll"),
("Tab", "Next"),
("q", "Quit"),
]
}
}
Tab::Strings => vec![
("Enter", "Details"),
("+", "Increment"),
("-", "Decrement"),
("/", "Search"),
("h/j/k/l", "Scroll"),
("Tab", "Next"),
("q", "Quit"),
],
Tab::Hexdump => vec![
("s", "Save"),
("g", "Jump"),
("/", "Search"),
("n", "Endianness"),
("h/j/k/l", "Scroll"),
("Tab", "Next"),
("q", "Quit"),
],
}
}
/// Changes the tab
pub fn set_tab(&mut self, tab: Tab) {
self.tab = tab;
}
}