From d7e6cc39f64fa5269e5b527962ed8ee262fd656c Mon Sep 17 00:00:00 2001 From: Aditya Gupta Date: Mon, 30 Nov 2026 13:47:30 +0530 Subject: [PATCH] fix(inspect): make the default symbols view readable `fat inspect symbols --file app.elf` printed every symbol sorted by address. On an ESP32-C6 application ELF that was 4,841 lines: 2,837 zero-size labels and 1,616 absolute symbols (register offsets, peripheral bases, ROM functions) before the first real symbol, followed by a single-line alias warning naming ~130 symbols. The total also summed aliased ranges and ROM functions, overstating image bytes by 23% (215,966 vs 175,738). - Sort by size, largest first, and cap tables at 25 rows (`--limit N`, `--limit 0`); CSV, JSONL and `--json` stay complete unless limited. - Hide zero-size, absolute and undefined symbols by default and report how many were hidden; `--all` or exact `--name` selections include them. - Lead a truncated table with a bytes-by-section summary. - Count each covered address range once per section, so aliases no longer double-count; report the overlap and up to three short alias examples. - Show only the legend letters that appear, and drop the long "N sizes summed" line. - List only changed, added and removed rows in text diffs. - Document the previously undescribed flags in `--help`. The JSON schema moves to elf-symbols/v3: `total_size` is now covered bytes, and `overlap_size`, `sections`, `hidden` and `omitted_count` are new. --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- crates/fat_cli/src/inspect_cmd.rs | 35 ++- crates/fat_cli/src/main.rs | 33 ++- crates/fat_cli/src/symbol_diff.rs | 36 ++- crates/fat_cli/src/symbol_format.rs | 323 +++++++++++++++++++---- crates/fat_cli/src/symbol_model.rs | 41 ++- crates/fat_cli/src/symbol_selection.rs | 348 ++++++++++++++++++++++--- 8 files changed, 724 insertions(+), 96 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d0fb868..36048c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,7 +60,7 @@ Avoid generic proof disclaimers such as "presence is not established"; use preci ## ELF symbol inspection -`fat_cli` shares one `st_shndx`-based ELF section reader (`symbol_elf`) between symbol discovery (`elf_symbols`) and enrichment (`symbol_enrich`); never infer sections from virtual addresses. Section and region labels come from section flags, and `--in-flash` includes read-only and executable sections. Demangling keeps raw names for selection and drains `c++filt` concurrently so large symbol tables cannot deadlock. Diff reports use their own schema version, and selection, rendering, and diffing remain separate modules. +`fat_cli` shares one `st_shndx`-based ELF section reader (`symbol_elf`) between symbol discovery (`elf_symbols`) and enrichment (`symbol_enrich`); never infer sections from virtual addresses. Section and region labels come from section flags, and `--in-flash` includes read-only and executable sections. Demangling keeps raw names for selection and drains `c++filt` concurrently so large symbol tables cannot deadlock. Diff reports use their own schema version, and selection, rendering, and diffing remain separate modules. Totals are the union of symbol ranges per section, so aliases count once; the default table is capped at 25 rows and hides symbols that occupy no image bytes, while CSV, JSONL, and `--json` stay complete unless `--limit` is given. ## Decompilation diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c7cb96..a52677e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ `inspect layout`, including custom table locations, optional MD5 validation, legacy tables, and separate file offsets and flash addresses. -- `inspect symbols` lists ELF symbols with byte sizes, section and region filters, batched name input, bounded hex previews, demangling, text/CSV/JSON output, and two-file symbol diffs. +- `inspect symbols` lists ELF symbols with byte sizes, section and region filters, batched name input, bounded hex previews, demangling, text/CSV/JSON output, and two-file symbol diffs. The default table shows the 25 largest symbols with a bytes-by-section summary, hides zero-size, absolute, and undefined symbols (`--all` restores them, `--limit N` changes the row count), and counts aliased address ranges once in the total. Text diffs list only changed, added, and removed symbols. ## [2.1.0] diff --git a/crates/fat_cli/src/inspect_cmd.rs b/crates/fat_cli/src/inspect_cmd.rs index ab466a1..3207f4a 100644 --- a/crates/fat_cli/src/inspect_cmd.rs +++ b/crates/fat_cli/src/inspect_cmd.rs @@ -209,10 +209,12 @@ pub struct SymbolsArgs<'a> { pub writable: bool, pub in_ram: bool, pub in_flash: bool, - pub sort: &'a str, + pub sort: Option<&'a str>, pub reverse: bool, pub requested_order: bool, pub no_requested_order: bool, + pub limit: Option, + pub all: bool, pub format: &'a str, pub no_color: bool, pub preview: usize, @@ -234,6 +236,9 @@ fn emit(text: &str) -> DynResult<()> { } } +/// Rows shown by `fat inspect symbols` tables when no --limit is given. +const DEFAULT_SYMBOL_ROWS: usize = 25; + pub fn run_symbols(args: SymbolsArgs<'_>) -> DynResult<()> { use crate::symbol_model::SelectionInfo; use std::io::IsTerminal; @@ -254,10 +259,12 @@ pub fn run_symbols(args: SymbolsArgs<'_>) -> DynResult<()> { ("--writable", args.writable), ("--in-ram", args.in_ram), ("--in-flash", args.in_flash), - ("--sort", args.sort != "address"), + ("--sort", args.sort.is_some()), ("--reverse", args.reverse), ("--requested-order", args.requested_order), ("--no-requested-order", args.no_requested_order), + ("--limit", args.limit.is_some()), + ("--all", args.all), ("--format", args.format != "table"), ("--no-color", args.no_color), ("--preview", args.preview != 0), @@ -324,9 +331,9 @@ pub fn run_symbols(args: SymbolsArgs<'_>) -> DynResult<()> { Some(raw) => Some(crate::symbol_selection::parse_symbol_type(raw)?), None => None, }; - let sort = crate::symbol_selection::parse_sort(args.sort)?; + let sort = crate::symbol_selection::parse_sort(args.sort.unwrap_or_default())?; let requested_order = args.requested_order - || (!args.no_requested_order && sort == "address" && !names.is_empty()); + || (!args.no_requested_order && args.sort.is_none() && !names.is_empty()); let selection = SelectionInfo { names, filter: args.filter.map(str::to_string), @@ -341,9 +348,11 @@ pub fn run_symbols(args: SymbolsArgs<'_>) -> DynResult<()> { sort, reverse: args.reverse, requested_order, + include_all: args.all, }; + let requested_names = !selection.names.is_empty(); - let selected = crate::symbol_selection::select(&base, &selection); + let mut selected = crate::symbol_selection::select(&base, &selection); if args.fail_on_missing && !selected.missing_names.is_empty() { let messages: Vec = selected .missing_names @@ -352,10 +361,24 @@ pub fn run_symbols(args: SymbolsArgs<'_>) -> DynResult<()> { .collect(); return Err(messages.join("; ").into()); } + // Only human-facing tables are capped by default; machine formats stay + // complete unless a limit is asked for. + let format = crate::symbol_format::parse_format(args.format)?; + let tabular = !args.json + && matches!( + format, + crate::symbol_format::OutputFormat::Table + | crate::symbol_format::OutputFormat::Markdown + ); + let limit = match args.limit { + Some(limit) => limit, + None if args.all || requested_names || !tabular => 0, + None => DEFAULT_SYMBOL_ROWS, + }; + crate::symbol_selection::truncate(&mut selected, limit); if args.json { emit(&format!("{}\n", serde_json::to_string_pretty(&selected)?))?; } else { - let format = crate::symbol_format::parse_format(args.format)?; let color = !args.no_color && std::io::stdout().is_terminal(); let width = args.width.unwrap_or_else(|| { std::env::var("COLUMNS") diff --git a/crates/fat_cli/src/main.rs b/crates/fat_cli/src/main.rs index cc31f4b..20a7f6b 100644 --- a/crates/fat_cli/src/main.rs +++ b/crates/fat_cli/src/main.rs @@ -2170,6 +2170,11 @@ enum InspectCommand { json: bool, }, /// List ELF symbols with their sizes in hex and decimal, and total the matched bytes. + /// + /// By default the table shows the largest symbols first, capped at 25 rows, + /// with a per-section byte summary when rows are left out. Zero-size, + /// absolute and undefined symbols occupy no bytes in the image and are + /// hidden unless --all or exact --name selections are given. Symbols { /// ELF file to inspect; repeat with --diff to compare two files. #[arg(long = "file")] @@ -2199,6 +2204,7 @@ enum InspectCommand { /// Only include this ELF symbol type: object, func, or any. symbol_type: Option, #[arg(long)] + /// Restrict to writable sections (.data, .bss). writable: bool, #[arg(long = "in-ram")] /// Restrict to writable RAM regions. @@ -2206,31 +2212,48 @@ enum InspectCommand { #[arg(long = "in-flash")] /// Restrict to flash-backed read-only and executable regions. in_flash: bool, - #[arg(long, default_value = "address")] - sort: String, #[arg(long)] + /// Sort key: size (largest first, the default), address, or name. + sort: Option, + #[arg(long)] + /// Reverse the sort order. reverse: bool, #[arg(long = "requested-order")] + /// Keep --name/--names-file order (the default when --sort is not given). requested_order: bool, #[arg(long = "no-requested-order")] + /// Sort --name/--names-file results instead of keeping their order. no_requested_order: bool, + #[arg(long)] + /// Show at most N rows; 0 shows every row. Tables default to 25 unless + /// exact names are requested; csv, jsonl, and --json default to all. + limit: Option, + #[arg(long)] + /// Include zero-size, absolute, and undefined symbols, and show every row. + all: bool, #[arg(long, default_value = "table")] + /// Output format: table, markdown, csv, or jsonl. format: String, #[arg(long = "no-color")] + /// Disable ANSI color in table output. no_color: bool, #[arg(long, default_value_t = 0)] /// Include up to N leading file bytes per symbol as hex; 0 disables (max 64). preview: usize, #[arg(long)] + /// Demangle C++ names with c++filt; selection still matches raw names. demangle: bool, #[arg(long)] /// Prefer .dynsym over .symtab when both symbol tables exist. dynsym: bool, #[arg(long = "fail-on-missing")] + /// Exit with an error when a requested --name is not found. fail_on_missing: bool, #[arg(long)] + /// Compare symbol sizes between two --file arguments. diff: bool, #[arg(long)] + /// Emit the full selection report as JSON. json: bool, #[arg(long)] /// Terminal width used for table output. @@ -3145,6 +3168,8 @@ fn run() -> DynResult<()> { reverse, requested_order, no_requested_order, + limit, + all, format, no_color, preview, @@ -3167,10 +3192,12 @@ fn run() -> DynResult<()> { writable, in_ram, in_flash, - sort: &sort, + sort: sort.as_deref(), reverse, requested_order, no_requested_order, + limit, + all, format: &format, no_color, preview, diff --git a/crates/fat_cli/src/symbol_diff.rs b/crates/fat_cli/src/symbol_diff.rs index 2ad8499..18ae21a 100644 --- a/crates/fat_cli/src/symbol_diff.rs +++ b/crates/fat_cli/src/symbol_diff.rs @@ -153,7 +153,14 @@ pub fn render(report: &DiffReport) -> String { report.unchanged ); - if report.rows.is_empty() { + // Unchanged rows are counted in the summary and kept in JSON; listing + // them would bury the differences. + let differing: Vec<_> = report + .rows + .iter() + .filter(|row| row.status != "same") + .collect(); + if differing.is_empty() { return format!("{summary}\n"); } @@ -166,8 +173,7 @@ pub fn render(report: &DiffReport) -> String { "Address A".to_string(), "Address B".to_string(), ]; - let body: Vec<[String; 7]> = report - .rows + let body: Vec<[String; 7]> = differing .iter() .map(|row| { [ @@ -394,6 +400,30 @@ mod tests { assert!(lines.iter().any(|line| line.contains("gone"))); } + #[test] + fn render_lists_only_differences() { + let a = report( + "a.elf", + vec![symbol("keep", 0x10, 10), symbol("grow", 0x40, 40)], + ); + let b = report( + "b.elf", + vec![symbol("keep", 0x10, 10), symbol("grow", 0x40, 45)], + ); + let result = diff(&a, &b); + assert_eq!(result.rows.len(), 2, "JSON keeps unchanged rows"); + let text = render(&result); + assert!(text.contains("grow"), "{text}"); + assert!(!text.contains("keep"), "{text}"); + assert!( + text.ends_with("1 changed, 0 added, 0 removed, 1 unchanged\n"), + "{text}" + ); + + let identical = render(&diff(&a, &a)); + assert_eq!(identical, "0 changed, 0 added, 0 removed, 2 unchanged\n"); + } + #[test] fn same_requires_matching_size_and_address() { let a = report( diff --git a/crates/fat_cli/src/symbol_format.rs b/crates/fat_cli/src/symbol_format.rs index a654304..44552fc 100644 --- a/crates/fat_cli/src/symbol_format.rs +++ b/crates/fat_cli/src/symbol_format.rs @@ -5,7 +5,9 @@ //! CSV, or JSONL output. Borders and rule lines are drawn regardless of color. use crate::style::Palette; -use crate::symbol_model::{SelectedSymbols, SymbolRow, SCHEMA_VERSION}; +use crate::symbol_model::{ + group_digits, human_size, percent, SelectedSymbols, SymbolRow, SCHEMA_VERSION, +}; use serde_json::json; const HEADERS: [&str; 7] = [ @@ -18,7 +20,18 @@ const NAME_INDEX: usize = 6; const PREVIEW_INDEX: usize = 7; const MIN_CELL: usize = 4; const MAX_TERMS: usize = 8; -const LEGEND: &str = "B = writable .bss, D = writable .data, r = read-only, T = code, U = undefined, A = absolute, C = common, ? = unknown"; +const LEGEND: [(&str, &str); 8] = [ + ("B", "writable .bss"), + ("D", "writable .data"), + ("r", "read-only"), + ("T", "code"), + ("U", "undefined"), + ("A", "absolute"), + ("C", "common"), + ("?", "unknown"), +]; +const SECTION_HEADERS: [&str; 4] = ["Section", "Symbols", "Bytes", "Share"]; +const SECTION_ALIGN: [bool; 4] = [false, true, true, true]; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OutputFormat { @@ -76,9 +89,21 @@ fn render_table( if selected.symbols.is_empty() { lines.push("No matching symbols.".to_string()); push_warnings(&mut lines, selected, palette); + push_hidden(&mut lines, selected, palette); return finish(lines); } + // A truncated listing hides most of the selection, so lead with where + // the bytes are before showing the largest individual symbols. + if selected.omitted_count > 0 { + if selected.sections.len() > 1 { + lines.push(palette.heading("Bytes by section")); + lines.extend(section_table(selected, width, markdown)); + lines.push(String::new()); + } + lines.push(palette.heading(listing_heading(selected))); + } + let show_preview = selected.symbols.iter().any(|row| row.preview.is_some()); let mut rows: Vec> = selected .symbols @@ -98,36 +123,158 @@ fn render_table( for (index, header) in headers.iter_mut().enumerate() { *header = truncate_cell(header, widths[index]); } - if markdown { - lines.push(table_row(&headers, &widths, '|')); - lines.push(markdown_separator(&widths)); - } else { - lines.push(box_border(&widths, "┌", "┬", "┐")); - lines.push(table_row(&headers, &widths, '│')); - lines.push(box_border(&widths, "├", "┼", "┤")); - } - for row in &rows { - lines.push(table_row(row, &widths, if markdown { '|' } else { '│' })); - } - if !markdown { - lines.push(box_border(&widths, "└", "┴", "┘")); - } + lines.extend(grid(&headers, &rows, &widths, &RIGHT_ALIGN, markdown)); lines.push(String::new()); + if selected.omitted_count > 0 { + lines.push(palette.muted(format!( + "… {} more not shown; --limit N shows more, --limit 0 or --all shows every row", + group_digits(selected.omitted_count as u64) + ))); + } push_warnings(&mut lines, selected, palette); - lines.push(LEGEND.to_string()); + push_hidden(&mut lines, selected, palette); + lines.push(legend(selected)); if let Some(arithmetic) = arithmetic_footer(selected) { lines.push(arithmetic); } - let total = selected.total_size.to_string(); - lines.push(format!( - "Total matched bytes: {} ({})", + let total = group_digits(selected.total_size); + let mut total_line = format!( + "Total matched bytes: {} ({}) in {} symbol{}", palette.good(total.as_str()), - selected.total_size_hex - )); + selected.total_size_hex, + group_digits(selected.symbol_count as u64), + if selected.symbol_count == 1 { "" } else { "s" } + ); + if selected.overlap_size > 0 { + total_line.push_str(&format!( + "; {} B of aliased ranges counted once", + group_digits(selected.overlap_size) + )); + } + lines.push(total_line); finish(lines) } +fn listing_heading(selected: &SelectedSymbols) -> String { + let shown = group_digits(selected.symbols.len() as u64); + let count = group_digits(selected.symbol_count as u64); + let selection = &selected.selection; + if selection.requested_order { + return format!("First {shown} of {count} symbols in requested order"); + } + match (selection.sort.as_str(), selection.reverse) { + ("size", false) => format!("Largest {shown} of {count} symbols"), + ("size", true) => format!("Smallest {shown} of {count} symbols"), + (key, false) => format!("First {shown} of {count} symbols by {key}"), + (key, true) => format!("Last {shown} of {count} symbols by {key}"), + } +} + +fn section_table(selected: &SelectedSymbols, width: usize, markdown: bool) -> Vec { + let mut rows: Vec> = selected + .sections + .iter() + .map(|section| { + let name = if section.section.is_empty() { + "(no section)".to_string() + } else { + section.section.clone() + }; + vec![ + name, + group_digits(section.symbol_count as u64), + human_size(section.size), + format!("{:.1}%", percent(section.size, selected.total_size)), + ] + }) + .collect(); + let headers: Vec = SECTION_HEADERS.iter().map(|h| (*h).to_string()).collect(); + let mut widths: Vec = headers.iter().map(|h| h.chars().count()).collect(); + for row in &rows { + for (index, cell) in row.iter().enumerate() { + widths[index] = widths[index].max(cell.chars().count()); + } + } + let natural = 3 * widths.len() + 1 + widths.iter().sum::(); + widths[0] = widths[0] + .saturating_sub(natural.saturating_sub(width)) + .max(MIN_CELL); + for row in &mut rows { + row[0] = truncate_cell(&row[0], widths[0]); + } + grid(&headers, &rows, &widths, &SECTION_ALIGN, markdown) +} + +fn grid( + headers: &[String], + rows: &[Vec], + widths: &[usize], + align: &[bool], + markdown: bool, +) -> Vec { + let mut lines = Vec::with_capacity(rows.len() + 4); + if markdown { + lines.push(table_row(headers, widths, align, '|')); + lines.push(markdown_separator(widths, align)); + } else { + lines.push(box_border(widths, "┌", "┬", "┐")); + lines.push(table_row(headers, widths, align, '│')); + lines.push(box_border(widths, "├", "┼", "┤")); + } + for row in rows { + lines.push(table_row( + row, + widths, + align, + if markdown { '|' } else { '│' }, + )); + } + if !markdown { + lines.push(box_border(widths, "└", "┴", "┘")); + } + lines +} + +fn push_hidden(lines: &mut Vec, selected: &SelectedSymbols, palette: &Palette) { + let hidden = selected.hidden; + if hidden.total() == 0 { + return; + } + let parts: Vec = [ + (hidden.zero_size, "zero-size"), + (hidden.absolute, "absolute"), + (hidden.undefined, "undefined"), + ] + .iter() + .filter(|(count, _)| *count > 0) + .map(|(count, label)| format!("{} {label}", group_digits(*count as u64))) + .collect(); + lines.push(palette.muted(format!( + "Hidden: {} symbol{} that occupy no bytes in this image; --all includes them", + parts.join(", "), + if hidden.total() == 1 { "" } else { "s" } + ))); +} + +/// Legend for the type letters that appear in the shown rows. +fn legend(selected: &SelectedSymbols) -> String { + let entries: Vec = LEGEND + .iter() + .filter(|(kind, _)| selected.symbols.iter().any(|row| row.kind == *kind)) + .map(|(kind, meaning)| format!("{kind} = {meaning}")) + .collect(); + entries.join(", ") +} + +fn full_legend() -> String { + LEGEND + .iter() + .map(|(kind, meaning)| format!("{kind} = {meaning}")) + .collect::>() + .join(", ") +} + fn push_warnings(lines: &mut Vec, selected: &SelectedSymbols, palette: &Palette) { for warning in &selected.warnings { lines.push(format!("{} {}", palette.warn("!"), warning)); @@ -225,12 +372,12 @@ fn pad(cell: &str, width: usize, right: bool) -> String { } } -fn table_row(cells: &[String], widths: &[usize], pipe: char) -> String { +fn table_row(cells: &[String], widths: &[usize], align: &[bool], pipe: char) -> String { let mut line = String::new(); line.push(pipe); for (index, cell) in cells.iter().enumerate() { line.push(' '); - line.push_str(&pad(cell, widths[index], RIGHT_ALIGN[index])); + line.push_str(&pad(cell, widths[index], align[index])); line.push(' '); line.push(pipe); } @@ -249,12 +396,12 @@ fn box_border(widths: &[usize], left: &str, joint: &str, right: &str) -> String line } -fn markdown_separator(widths: &[usize]) -> String { +fn markdown_separator(widths: &[usize], align: &[bool]) -> String { let mut line = String::from("|"); for (index, cell_width) in widths.iter().enumerate() { let dashes = (*cell_width).max(3); line.push(' '); - if RIGHT_ALIGN[index] { + if align[index] { line.push_str(&"-".repeat(dashes - 1)); line.push(':'); } else { @@ -267,30 +414,28 @@ fn markdown_separator(widths: &[usize]) -> String { line } +/// Spell out the sum for small, complete selections. Large, truncated or +/// alias-overlapping selections rely on the total line alone, since a long +/// or partial sum would not match it. fn arithmetic_footer(selected: &SelectedSymbols) -> Option { - if selected.symbols.is_empty() || selected.total_size == 0 { + if selected.symbols.len() < 2 + || selected.symbols.len() > MAX_TERMS + || selected.total_size == 0 + || selected.omitted_count > 0 + || selected.overlap_size > 0 + { return None; } const MAX_TERM_NAME: usize = 24; - let count = selected.symbols.len(); - if count > MAX_TERMS { - let names: Vec = selected - .symbols - .iter() - .take(3) - .map(|row| truncate_cell(&row.name, MAX_TERM_NAME)) - .collect(); - return Some(format!( - "{count} sizes summed: {} … = {}", - names.join(", "), - selected.total_size - )); - } let terms: Vec = selected .symbols .iter() + .filter(|row| row.size > 0) .map(|row| format!("{} ({})", row.size, truncate_cell(&row.name, MAX_TERM_NAME))) .collect(); + if terms.len() < 2 { + return None; + } Some(format!("{} = {}", terms.join(" + "), selected.total_size)) } @@ -333,9 +478,13 @@ fn render_jsonl(selected: &SelectedSymbols) -> String { "symbol_count": selected.symbol_count, "total_size": selected.total_size, "total_size_hex": selected.total_size_hex.as_str(), + "overlap_size": selected.overlap_size, + "sections": &selected.sections, + "hidden": selected.hidden, + "omitted_count": selected.omitted_count, "missing_names": &selected.missing_names, "warnings": &selected.warnings, - "legend": LEGEND, + "legend": full_legend(), "arithmetic": arithmetic_footer(selected), }); lines.push(summary.to_string()); @@ -345,7 +494,7 @@ fn render_jsonl(selected: &SelectedSymbols) -> String { #[cfg(test)] mod tests { use super::*; - use crate::symbol_model::SelectionInfo; + use crate::symbol_model::{HiddenCounts, SectionTotal, SelectionInfo}; fn row(name: &str, size: u64, section: &str) -> SymbolRow { SymbolRow { @@ -377,6 +526,10 @@ mod tests { symbol_count, total_size, total_size_hex: format!("0x{total_size:x}"), + overlap_size: 0, + sections: Vec::new(), + hidden: HiddenCounts::default(), + omitted_count: 0, missing_names: Vec::new(), warnings: Vec::new(), } @@ -453,16 +606,88 @@ mod tests { } #[test] - fn arithmetic_caps_at_eight_terms() { + fn arithmetic_only_for_small_complete_selections() { + let small = selection(vec![row("a", 1, ".data"), row("b", 2, ".data")]); + let out = render(&small, OutputFormat::Table, false, 400); + assert!(out.contains("1 (a) + 2 (b) = 3"), "{out}"); + let rows: Vec = (1..=9) .map(|index| row(&format!("n{index}"), index, ".data")) .collect(); - let selected = selection(rows); - let out = render(&selected, OutputFormat::Table, false, 400); - assert!(out.contains("9 sizes summed:"), "{out}"); - assert!(out.contains("…"), "{out}"); - assert!(out.contains("= 45"), "{out}"); + let large = selection(rows); + let out = render(&large, OutputFormat::Table, false, 400); assert!(!out.contains(" + "), "{out}"); + assert!(!out.contains("sizes summed"), "{out}"); + assert!( + out.contains("Total matched bytes: 45 (0x2d) in 9 symbols"), + "{out}" + ); + + let mut aliased = selection(vec![row("a", 4, ".data"), row("b", 4, ".data")]); + aliased.total_size = 4; + aliased.total_size_hex = "0x4".into(); + aliased.overlap_size = 4; + let out = render(&aliased, OutputFormat::Table, false, 400); + assert!(!out.contains(" + "), "{out}"); + assert!(out.contains("4 B of aliased ranges counted once"), "{out}"); + } + + #[test] + fn truncated_listing_leads_with_sections_and_says_what_is_hidden() { + let mut selected = selection(vec![row("big", 64, ".bss"), row("mid", 32, ".text")]); + selected.selection.sort = "size".into(); + selected.symbol_count = 40; + selected.total_size = 200; + selected.omitted_count = 38; + selected.sections = vec![ + SectionTotal { + section: ".text".into(), + region: "executable".into(), + symbol_count: 30, + size: 150, + }, + SectionTotal { + section: ".bss".into(), + region: "writable".into(), + symbol_count: 10, + size: 50, + }, + ]; + selected.hidden = HiddenCounts { + zero_size: 2_837, + absolute: 99, + undefined: 0, + }; + let out = render(&selected, OutputFormat::Table, false, 100); + + let sections = out.find("Bytes by section").expect(&out); + let heading = out.find("Largest 2 of 40 symbols").expect(&out); + let symbol_table = out.find("Address").expect(&out); + assert!(sections < heading && heading < symbol_table, "{out}"); + assert!(out.contains("75.0%"), "{out}"); + assert!(out.contains("… 38 more not shown"), "{out}"); + assert!( + out.contains("Hidden: 2,837 zero-size, 99 absolute symbols that occupy no bytes"), + "{out}" + ); + // Only the type letters that appear in the table are explained. + assert!(out.contains("D = writable .data"), "{out}"); + assert!(!out.contains("U = undefined"), "{out}"); + + let mut complete = selected.clone(); + complete.omitted_count = 0; + let out = render(&complete, OutputFormat::Table, false, 100); + assert!(!out.contains("Bytes by section"), "{out}"); + assert!(!out.contains("more not shown"), "{out}"); + } + + #[test] + fn empty_result_still_reports_hidden_symbols() { + let mut selected = selection(Vec::new()); + selected.hidden.absolute = 3; + let out = render(&selected, OutputFormat::Table, false, 80); + assert!(out.contains("No matching symbols."), "{out}"); + assert!(out.contains("Hidden: 3 absolute symbols"), "{out}"); } #[test] diff --git a/crates/fat_cli/src/symbol_model.rs b/crates/fat_cli/src/symbol_model.rs index 64e74ee..9b52072 100644 --- a/crates/fat_cli/src/symbol_model.rs +++ b/crates/fat_cli/src/symbol_model.rs @@ -5,7 +5,7 @@ use serde::Serialize; -pub const SCHEMA_VERSION: &str = "elf-symbols/v2"; +pub const SCHEMA_VERSION: &str = "elf-symbols/v3"; pub const DIFF_SCHEMA_VERSION: &str = "elf-symbol-diff/v1"; @@ -81,6 +81,35 @@ pub struct SelectionInfo { pub sort: String, pub reverse: bool, pub requested_order: bool, + /// Keep zero-size, absolute and undefined symbols, which are hidden by + /// default unless exact names are requested. + pub include_all: bool, +} + +/// Symbols that matched every filter but were hidden because they occupy no +/// bytes in the image: zero-size labels, absolute symbols (linker constants, +/// register offsets, ROM functions) and undefined references. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +pub struct HiddenCounts { + pub zero_size: usize, + pub absolute: usize, + pub undefined: usize, +} + +impl HiddenCounts { + pub fn total(&self) -> usize { + self.zero_size + self.absolute + self.undefined + } +} + +/// Bytes covered by the selected symbols in one section. +#[derive(Debug, Clone, Serialize)] +pub struct SectionTotal { + /// Section name; empty for symbols without a section. + pub section: String, + pub region: String, + pub symbol_count: usize, + pub size: u64, } #[derive(Debug, Clone, Serialize)] @@ -89,9 +118,19 @@ pub struct SelectedSymbols { pub file: String, pub selection: SelectionInfo, pub symbols: Vec, + /// Number of selected symbols, including any dropped by a row limit. pub symbol_count: usize, + /// Bytes covered by the selected symbols; aliases that share an address + /// range are counted once. pub total_size: u64, pub total_size_hex: String, + /// Bytes that per-symbol sizes count more than once because of aliases. + pub overlap_size: u64, + /// Covered bytes per section, largest first. + pub sections: Vec, + pub hidden: HiddenCounts, + /// Selected symbols left out of `symbols` by a row limit. + pub omitted_count: usize, /// Requested exact names that did not match a symbol. pub missing_names: Vec, /// Non-fatal observations such as aliases sharing an address range. diff --git a/crates/fat_cli/src/symbol_selection.rs b/crates/fat_cli/src/symbol_selection.rs index a8b1150..c179bf1 100644 --- a/crates/fat_cli/src/symbol_selection.rs +++ b/crates/fat_cli/src/symbol_selection.rs @@ -3,12 +3,13 @@ //! Analysis stays immutable: every row that leaves this module is a copy with //! presentation fields refreshed against the selected total. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use regex::Regex; use crate::symbol_model::{ - address_range, human_size, percent, FullSymbolReport, SelectedSymbols, SelectionInfo, SymbolRow, + address_range, human_size, percent, FullSymbolReport, HiddenCounts, SectionTotal, + SelectedSymbols, SelectionInfo, SymbolRow, }; /// Parse a byte size: decimal, `0x` hex, or a `KiB`/`MiB`/`GiB` suffix. @@ -49,11 +50,11 @@ pub fn parse_size(raw: &str) -> Result { .ok_or_else(|| format!("size '{raw}' is too large")) } -/// Parse the sort key. Empty input means the default, `address`. +/// Parse the sort key. Empty input means the default, `size` (largest first). pub fn parse_sort(raw: &str) -> Result { let value = raw.trim().to_ascii_lowercase(); if value.is_empty() { - return Ok("address".to_string()); + return Ok("size".to_string()); } match value.as_str() { "address" | "size" | "name" => Ok(value), @@ -157,6 +158,24 @@ pub fn select(full: &FullSymbolReport, selection: &SelectionInfo) -> SelectedSym .cloned() .collect(); + // Exact names are an explicit request, so they bypass the default hiding. + let mut hidden = HiddenCounts::default(); + if !selection.include_all && requested.is_empty() { + matched.retain(|row| { + let counter = if row.size == 0 { + &mut hidden.zero_size + } else if row.kind == "A" { + &mut hidden.absolute + } else if row.kind == "U" { + &mut hidden.undefined + } else { + return true; + }; + *counter += 1; + false + }); + } + let mut symbols = if selection.requested_order && !requested.is_empty() { let mut ordered = Vec::with_capacity(matched.len()); for name in &requested { @@ -170,7 +189,7 @@ pub fn select(full: &FullSymbolReport, selection: &SelectionInfo) -> SelectedSym ordered } else { match selection.sort.as_str() { - "size" => matched.sort_by(|a, b| a.size.cmp(&b.size).then_with(|| a.name.cmp(&b.name))), + "size" => matched.sort_by(|a, b| b.size.cmp(&a.size).then_with(|| a.name.cmp(&b.name))), "name" => matched.sort_by(|a, b| a.name.cmp(&b.name)), _ => { matched.sort_by(|a, b| a.address.cmp(&b.address).then_with(|| a.name.cmp(&b.name))) @@ -183,10 +202,15 @@ pub fn select(full: &FullSymbolReport, selection: &SelectionInfo) -> SelectedSym symbols.reverse(); } - let total_size = symbols + let summed = symbols .iter() .fold(0_u64, |sum, row| sum.saturating_add(row.size)); + let sections = section_totals(&symbols); + let total_size = sections + .iter() + .fold(0_u64, |sum, section| sum.saturating_add(section.size)); let total_size_hex = format!("0x{total_size:x}"); + let overlap_size = summed.saturating_sub(total_size); let symbol_count = symbols.len(); for row in &mut symbols { @@ -196,26 +220,63 @@ pub fn select(full: &FullSymbolReport, selection: &SelectionInfo) -> SelectedSym row.size_human = human_size(row.size); } - // One warning for all aliases, naming every symbol in a colliding group. - let mut nonzero_at: HashMap = HashMap::new(); + // Aliases are grouped per section so that relocatable objects, whose + // addresses restart at zero in every section, do not collide. + let mut alias_groups: Vec> = Vec::new(); + let mut group_at: HashMap<(Option, u64), usize> = HashMap::new(); for row in &symbols { - if row.size != 0 { - *nonzero_at.entry(row.address).or_insert(0) += 1; + if row.size == 0 || row.kind == "C" { + continue; } - } - let mut alias_names: Vec<&str> = Vec::new(); - for row in &symbols { - if row.size != 0 - && nonzero_at.get(&row.address).copied().unwrap_or(0) >= 2 - && !alias_names.contains(&row.name.as_str()) - { - alias_names.push(row.name.as_str()); + let index = *group_at + .entry((row.section_index, row.address)) + .or_insert_with(|| { + alias_groups.push(Vec::new()); + alias_groups.len() - 1 + }); + if !alias_groups[index].contains(&row.name.as_str()) { + alias_groups[index].push(row.name.as_str()); } } - if !alias_names.is_empty() { + alias_groups.retain(|group| group.len() >= 2); + if !alias_groups.is_empty() { + const EXAMPLES: usize = 3; + const EXAMPLE_NAME: usize = 32; + let short = |name: &&str| -> String { + if name.chars().count() <= EXAMPLE_NAME { + (*name).to_string() + } else { + let head: String = name.chars().take(EXAMPLE_NAME - 1).collect(); + format!("{head}…") + } + }; + let examples: Vec = alias_groups + .iter() + .take(EXAMPLES) + .map(|group| { + const GROUP_NAMES: usize = 3; + let names: Vec = group.iter().take(GROUP_NAMES).map(short).collect(); + let joined = names.join(" = "); + if group.len() > GROUP_NAMES { + format!("{joined} (+{} more)", group.len() - GROUP_NAMES) + } else { + joined + } + }) + .collect(); + let more = if alias_groups.len() > EXAMPLES { + ", …" + } else { + "" + }; + let subject = if alias_groups.len() == 1 { + "1 address is".to_string() + } else { + format!("{} addresses are", alias_groups.len()) + }; warnings.push(format!( - "alias risk: {} share an address with nonzero size; sizes may be double-counted", - alias_names.join(", ") + "{subject} shared by aliases ({}{more}); shared bytes are counted once in the total", + examples.join("; ") )); } if symbols.iter().any(|row| row.size == 0) { @@ -230,11 +291,97 @@ pub fn select(full: &FullSymbolReport, selection: &SelectionInfo) -> SelectedSym symbol_count, total_size, total_size_hex, + overlap_size, + sections, + hidden, + omitted_count: 0, missing_names, warnings, } } +/// Keep the first `limit` rows; 0 keeps every row. Totals still describe the +/// whole selection. +pub fn truncate(selected: &mut SelectedSymbols, limit: usize) { + if limit > 0 && selected.symbols.len() > limit { + selected.omitted_count += selected.symbols.len() - limit; + selected.symbols.truncate(limit); + } +} + +/// Covered bytes per section: the union of symbol ranges, so overlapping +/// aliases count once. Common symbols carry an alignment rather than an +/// address in `st_value`, so their sizes are added without merging. +fn section_totals(rows: &[SymbolRow]) -> Vec { + struct Accumulator { + section: String, + region: String, + symbol_count: usize, + common: u64, + ranges: Vec<(u64, u64)>, + } + + let mut by_section: BTreeMap<(Option, String), Accumulator> = BTreeMap::new(); + for row in rows { + let entry = by_section + .entry((row.section_index, row.section.clone())) + .or_insert_with(|| Accumulator { + section: row.section.clone(), + region: row.region.clone(), + symbol_count: 0, + common: 0, + ranges: Vec::new(), + }); + entry.symbol_count += 1; + if row.kind == "C" { + entry.common = entry.common.saturating_add(row.size); + } else if row.size > 0 { + entry + .ranges + .push((row.address, row.address.saturating_add(row.size))); + } + } + + // Distinct section indices can share a name (several `.text` sections in + // a relocatable object), so merge by name after the per-index unions. + let mut totals: Vec = Vec::new(); + for mut entry in by_section.into_values() { + entry.ranges.sort_unstable(); + let mut covered = entry.common; + let mut current: Option<(u64, u64)> = None; + for (start, end) in entry.ranges { + current = match current { + Some((open, close)) if start <= close => Some((open, close.max(end))), + Some((open, close)) => { + covered = covered.saturating_add(close - open); + Some((start, end)) + } + None => Some((start, end)), + }; + } + if let Some((open, close)) = current { + covered = covered.saturating_add(close - open); + } + match totals + .iter_mut() + .find(|total| total.section == entry.section && total.region == entry.region) + { + Some(total) => { + total.symbol_count += entry.symbol_count; + total.size = total.size.saturating_add(covered); + } + None => totals.push(SectionTotal { + section: entry.section, + region: entry.region, + symbol_count: entry.symbol_count, + size: covered, + }), + } + } + totals.sort_by(|a, b| b.size.cmp(&a.size).then_with(|| a.section.cmp(&b.section))); + totals +} + #[cfg(test)] mod tests { use super::*; @@ -290,7 +437,7 @@ mod tests { #[test] fn parse_sort_and_symbol_type_validate_input() { - assert_eq!(parse_sort(""), Ok("address".to_string())); + assert_eq!(parse_sort(""), Ok("size".to_string())); assert_eq!(parse_sort(" SIZE "), Ok("size".to_string())); assert_eq!(parse_sort("name"), Ok("name".to_string())); assert!(parse_sort("date").is_err()); @@ -470,7 +617,7 @@ mod tests { .iter() .map(|r| r.name.as_str()) .collect::>(), - vec!["zeta", "mid", "alpha"] + vec!["alpha", "mid", "zeta"] ); let by_name = select( @@ -514,23 +661,32 @@ mod tests { row("alias_b", 0x100, 60, "read-only", "func"), row("empty", 0x200, 0, "read-only", "notype"), ]); - let result = select(&full, &SelectionInfo::default()); + let result = select( + &full, + &SelectionInfo { + include_all: true, + ..SelectionInfo::default() + }, + ); + // The aliases overlap in [0x100, 0x128), so the total is the 60-byte + // union rather than the 100-byte sum. assert_eq!(result.symbol_count, 3); - assert_eq!(result.total_size, 100); - assert_eq!(result.total_size_hex, "0x64"); - let share_sum: f64 = result.symbols.iter().map(|row| row.share_percent).sum(); - assert_eq!(share_sum, 100.0); - assert_eq!(result.symbols[0].share_percent, 40.0); - assert_eq!(result.symbols[1].share_percent, 60.0); + assert_eq!(result.total_size, 60); + assert_eq!(result.total_size_hex, "0x3c"); + assert_eq!(result.overlap_size, 40); + assert_eq!(result.symbols[1].share_percent, 100.0); assert_eq!(result.symbols[2].share_percent, 0.0); assert_eq!(result.symbols[0].range, "[0x100, 0x128)"); assert_eq!(result.symbols[0].size_hex, "0x28"); assert_eq!(result.symbols[0].size_human, "40 B"); assert_eq!(result.warnings.len(), 2); - assert!(result.warnings[0].contains("alias_a")); - assert!(result.warnings[0].contains("alias_b")); + assert!( + result.warnings[0].contains("1 address is shared by aliases (alias_a = alias_b)"), + "{}", + result.warnings[0] + ); assert!(result.warnings[1].contains("zero size")); // The input report is untouched. @@ -546,7 +702,135 @@ mod tests { &SelectionInfo::default(), ); assert!(clean.warnings.is_empty()); + assert_eq!(clean.overlap_size, 0); + } + + #[test] + fn default_hides_symbols_that_occupy_no_image_bytes() { + let mut absolute = row("rom_printf", 0x4000_0000, 0x100, "absolute", "func"); + absolute.kind = "A".into(); + absolute.section_index = None; + let mut undefined = row("ext_fn", 0, 8, "undefined", "func"); + undefined.kind = "U".into(); + undefined.section_index = None; + let full = report(vec![ + row("real", 0x100, 16, "read-only", "func"), + row("label", 0x110, 0, "read-only", "notype"), + absolute, + undefined, + ]); + + let result = select(&full, &SelectionInfo::default()); + assert_eq!(result.symbol_count, 1); + assert_eq!(result.symbols[0].name, "real"); + assert_eq!( + result.hidden, + HiddenCounts { + zero_size: 1, + absolute: 1, + undefined: 1, + } + ); + assert_eq!(result.total_size, 16); + assert!(result.warnings.is_empty(), "{:?}", result.warnings); + + // Hiding is counted only among rows that passed the other filters. + let filtered = select( + &full, + &SelectionInfo { + filter: Some("rom_".into()), + ..SelectionInfo::default() + }, + ); + assert_eq!(filtered.symbol_count, 0); + assert_eq!(filtered.hidden.total(), 1); + + let all = select( + &full, + &SelectionInfo { + include_all: true, + ..SelectionInfo::default() + }, + ); + assert_eq!(all.symbol_count, 4); + assert_eq!(all.hidden.total(), 0); + + let named = select( + &full, + &SelectionInfo { + names: vec!["label".into(), "rom_printf".into()], + ..SelectionInfo::default() + }, + ); + assert_eq!(named.symbol_count, 2); + assert!(named.missing_names.is_empty()); + } + + #[test] + fn section_totals_merge_overlaps_per_section_only() { + let mut data = row("in_data", 0x0, 8, "writable", "object"); + data.section = ".data".into(); + data.section_index = Some(2); + let mut text_a = row("text_a", 0x0, 8, "executable", "func"); + text_a.section = ".text".into(); + let mut text_b = row("text_b", 0x4, 8, "executable", "func"); + text_b.section = ".text".into(); + let result = select( + &report(vec![text_a, text_b, data]), + &SelectionInfo::default(), + ); + + // .text covers [0x0, 0xc); .data starts at the same address but is a + // different section, so it neither merges nor raises an alias warning. + assert_eq!(result.total_size, 12 + 8); + assert_eq!(result.overlap_size, 4); + assert_eq!(result.sections.len(), 2); + assert_eq!(result.sections[0].section, ".text"); + assert_eq!(result.sections[0].size, 12); + assert_eq!(result.sections[0].symbol_count, 2); + assert_eq!(result.sections[1].section, ".data"); + assert!(result.warnings.is_empty(), "{:?}", result.warnings); } + + #[test] + fn truncate_keeps_totals_and_counts_omitted_rows() { + let full = report( + (1..=5) + .map(|index| { + row( + &format!("s{index}"), + index * 0x10, + index, + "read-only", + "func", + ) + }) + .collect(), + ); + let mut result = select( + &full, + &SelectionInfo { + sort: "size".into(), + ..SelectionInfo::default() + }, + ); + truncate(&mut result, 2); + assert_eq!( + result + .symbols + .iter() + .map(|r| r.name.as_str()) + .collect::>(), + vec!["s5", "s4"] + ); + assert_eq!(result.omitted_count, 3); + assert_eq!(result.symbol_count, 5); + assert_eq!(result.total_size, 15); + + truncate(&mut result, 0); + assert_eq!(result.symbols.len(), 2); + } + #[test] fn in_flash_includes_executable_regions() { let full = report(vec![