1#![allow(clippy::unwrap_used, reason = "a command-line example fails loudly")]
9
10use std::time::Instant;
11
12use binbun::Database;
13use binbun::analysis::Seeds;
14use binbun::listing::{LineKind, Listing, Options, Role};
15use binbun_loader::Image;
16
17fn status_kib(field: &str) -> u64 {
19 std::fs::read_to_string("/proc/self/status")
20 .ok()
21 .and_then(|s| {
22 s.lines()
23 .find(|l| l.starts_with(field))
24 .and_then(|l| l.split_whitespace().nth(1)?.parse().ok())
25 })
26 .unwrap_or(0)
27}
28
29fn resident_kib() -> u64 {
30 status_kib("VmRSS:")
31}
32
33fn main() {
34 let args: Vec<String> = std::env::args().collect();
35 let path = args
36 .get(1)
37 .expect("usage: listing FILE [ADDRESS [LINES] | --all]");
38 let data = std::fs::read(path).unwrap();
39 let image = Image::parse(&data).unwrap();
40 let db = Database::new(&image, Seeds::ALL).unwrap();
41 let references = Instant::now();
42 db.references();
43 let references = references.elapsed();
44 let before = resident_kib();
45 let start = Instant::now();
46 let listing = Listing::build(&db, &Options::default());
47 let built = start.elapsed();
48 let after = resident_kib();
49 match args.get(2).map(String::as_str) {
50 Some("--all") => {
51 for n in 0..listing.len() {
52 println!("{}", listing.render(&db, n).text());
53 }
54 }
55 Some(address) => {
56 let address = u64::from_str_radix(address.trim_start_matches("0x"), 16).unwrap();
57 let count: u64 = args.get(3).map_or(40, |n| n.parse().unwrap());
58 let first = listing.line_of(address);
59 let head = listing.line(first).unwrap().address;
61 let mut n = first;
62 while n > 0 && listing.line(n - 1).is_some_and(|l| l.address == head) {
63 n -= 1;
64 }
65 for n in n..(n + count).min(listing.len()) {
66 println!("{}", listing.render(&db, n).text());
67 }
68 }
69 None => {
70 let render = Instant::now();
71 let (mut symbolised, mut instructions) = (0u64, 0u64);
72 for n in 0..listing.len() {
73 let rendered = listing.render(&db, n);
74 if listing.line(n).unwrap().kind == LineKind::Instruction {
75 instructions += 1;
76 symbolised += rendered
77 .tokens
78 .iter()
79 .filter(|t| {
80 matches!(
81 t.role,
82 Role::CodeName
83 | Role::DataName
84 | Role::ImportName
85 | Role::LocalName
86 )
87 })
88 .count() as u64;
89 }
90 }
91 let stats = listing.stats();
92 println!(
93 "{path}: references {:.2} s; line space {:.3} s, RSS +{} MiB ({} MiB, peak {} MiB); \
94 {} lines, {} instructions, {} data items, {} dummy names, {} string names; \
95 rendering every line {:.2} s: {} operands symbolised in {} instructions",
96 references.as_secs_f64(),
97 built.as_secs_f64(),
98 after.saturating_sub(before) / 1024,
99 after / 1024,
100 status_kib("VmHWM:") / 1024,
101 stats.lines,
102 stats.instructions,
103 stats.data_items,
104 stats.dummy_names,
105 stats.string_names,
106 render.elapsed().as_secs_f64(),
107 symbolised,
108 instructions,
109 );
110 }
111 }
112}