fix(cli): color unpack and inspect terminal output

Share a scoped terminal palette across unpack progress, summaries and rich research reports. Add auto, always and never color modes with stream-specific terminal checks, NO_COLOR handling and Windows virtual-terminal support.

Keep report data, redirected auto output, JSON and saved run logs plain. Test color roles, quiet behavior, policy restoration and escape-free artifacts.
This commit is contained in:
Momoko-Ayase committed 2026-11-06 03:16:18 +08:00
1 parent 1ee4344c1e
commit 7fde1809c7
6 files changed
+1074 -149

No files matched your search

+66 -14
View File
@@ -1,5 +1,8 @@
use senbei_engine::android::ResourceLimits; use senbei_engine::android::ResourceLimits;
use senbei_io::{job, pause, scan}; use senbei_io::{
job, pause, scan,
ui::{self, ColorMode, Palette, Tone},
};
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::path::Path; use std::path::Path;
@@ -8,14 +11,22 @@ fn main() -> std::process::ExitCode {
Ok(Outcome::Run(options)) => options, Ok(Outcome::Run(options)) => options,
Ok(Outcome::Handled(code)) => return code, Ok(Outcome::Handled(code)) => return code,
Err(message) => { Err(message) => {
eprintln!("error: {message}"); eprintln!(
"{}: {message}",
Palette::stderr().paint(Tone::Error, "error")
);
return std::process::ExitCode::from(2); return std::process::ExitCode::from(2);
} }
}; };
let code = match options.threads { let color = if options.machine {
ColorMode::Never
} else {
options.color
};
let code = ui::with_color_mode(color, || match options.threads {
Some(count) => senbei_engine::with_thread_cap(count, || execute(&mut options)), Some(count) => senbei_engine::with_thread_cap(count, || execute(&mut options)),
None => execute(&mut options), None => execute(&mut options),
}; });
if !options.machine { if !options.machine {
pause::maybe_pause(options.no_pause); pause::maybe_pause(options.no_pause);
} }
@@ -42,6 +53,7 @@ struct Options {
scan_all: bool, scan_all: bool,
strict_integrity: bool, strict_integrity: bool,
threads: Option<NonZeroUsize>, threads: Option<NonZeroUsize>,
color: ColorMode,
limits: ResourceLimits, limits: ResourceLimits,
/// Machine-readable output on stdout and nothing else. /// Machine-readable output on stdout and nothing else.
machine: bool, machine: bool,
@@ -68,6 +80,7 @@ impl Options {
let mut scan_all = false; let mut scan_all = false;
let mut strict_integrity = false; let mut strict_integrity = false;
let mut threads = None; let mut threads = None;
let mut color = ColorMode::Auto;
let mut machine = false; let mut machine = false;
let mut dry_run = false; let mut dry_run = false;
let mut limits = ResourceLimits::default(); let mut limits = ResourceLimits::default();
@@ -91,6 +104,10 @@ impl Options {
"--json" => machine = true, "--json" => machine = true,
"--dry-run" => dry_run = true, "--dry-run" => dry_run = true,
"--threads" => threads = Some(parse_thread_cap(args.next().as_deref())?), "--threads" => threads = Some(parse_thread_cap(args.next().as_deref())?),
"--color" => color = parse_color(args.next().as_deref())?,
flag if flag.starts_with("--color=") => {
color = parse_color(flag.strip_prefix("--color="))?
}
flag flag
@ ("--max-entry-mib" | "--max-total-mib" | "--max-entries" | "--max-depth") => { @ ("--max-entry-mib" | "--max-total-mib" | "--max-entries" | "--max-depth") => {
set_resource_limit(&mut limits, flag, args.next().as_deref())?; set_resource_limit(&mut limits, flag, args.next().as_deref())?;
@@ -176,6 +193,7 @@ impl Options {
scan_all, scan_all,
strict_integrity, strict_integrity,
threads, threads,
color,
limits, limits,
machine, machine,
dry_run, dry_run,
@@ -183,6 +201,15 @@ impl Options {
} }
} }
fn parse_color(value: Option<&str>) -> Result<ColorMode, String> {
match value {
Some("auto") => Ok(ColorMode::Auto),
Some("always") => Ok(ColorMode::Always),
Some("never") => Ok(ColorMode::Never),
_ => Err("--color requires auto, always, or never".to_owned()),
}
}
fn parse_thread_cap(value: Option<&str>) -> Result<NonZeroUsize, String> { fn parse_thread_cap(value: Option<&str>) -> Result<NonZeroUsize, String> {
value value
.filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())) .filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()))
@@ -213,7 +240,7 @@ fn execute_inspect(options: &Options, path: &Path, scan_all: bool) -> u8 {
if options.machine { if options.machine {
println!("{}", report.to_json()); println!("{}", report.to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
print!("{}", report.render_text()); print!("{}", report.render_text_with_palette(Palette::stdout()));
} }
code code
} }
@@ -222,7 +249,10 @@ fn execute_inspect(options: &Options, path: &Path, scan_all: bool) -> u8 {
let report = job::error_report(job::Mode::Inspect, &format!("{error:#}")); let report = job::error_report(job::Mode::Inspect, &format!("{error:#}"));
println!("{}", report.to_json()); println!("{}", report.to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
eprintln!("error: {error:#}"); eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
} }
1 1
} }
@@ -236,8 +266,8 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
if options.machine { if options.machine {
println!("{}", report.to_json()); println!("{}", report.to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
print!("{}", report.render_text()); print!("{}", report.render_text_with_palette(Palette::stdout()));
println!("{}", report.summary_line()); println!("{}", report.summary_line_with_palette(Palette::stdout()));
} }
code code
} }
@@ -246,7 +276,10 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
let report = job::error_report(job::Mode::DryRun, &format!("{error:#}")); let report = job::error_report(job::Mode::DryRun, &format!("{error:#}"));
println!("{}", report.to_json()); println!("{}", report.to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
eprintln!("error: {error:#}"); eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
} }
1 1
} }
@@ -255,7 +288,13 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 { fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
if options.quiet < 2 && !options.machine { if options.quiet < 2 && !options.machine {
println!("Senbei {}", env!("CARGO_PKG_VERSION")); println!(
"{}",
Palette::stdout().paint(
Tone::Heading,
format!("Senbei {}", env!("CARGO_PKG_VERSION"))
)
);
} }
let out_path = options.out.as_deref().map(Path::new); let out_path = options.out.as_deref().map(Path::new);
// A machine run goes through the same drivers with an observer attached; // A machine run goes through the same drivers with an observer attached;
@@ -310,8 +349,12 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
if options.machine { if options.machine {
println!("{}", collector.finish().to_json()); println!("{}", collector.finish().to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
println!("{}", summary.line()); println!("{}", summary.line_with_palette(Palette::stdout()));
println!("done in {} ms", summary.duration_ms); println!(
"{}",
Palette::stdout()
.paint(Tone::Muted, format!("done in {} ms", summary.duration_ms))
);
} }
exit_code(&summary, options.strict_integrity) exit_code(&summary, options.strict_integrity)
} }
@@ -321,7 +364,10 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
failed.push_error(format!("{error:#}")); failed.push_error(format!("{error:#}"));
println!("{}", failed.finish().to_json()); println!("{}", failed.finish().to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
eprintln!("error: {error:#}"); eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
} }
1 1
} }
@@ -383,7 +429,7 @@ fn set_resource_limit(
fn print_help() { fn print_help() {
println!( println!(
"senbei [inspect|unpack] <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--json] [--dry-run] [--threads N] [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]" "senbei [inspect|unpack] <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--json] [--dry-run] [--threads N] [--color auto|always|never] [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]"
); );
println!( println!(
" <file|folder>\n\ " <file|folder>\n\
@@ -416,6 +462,12 @@ fn print_help() {
" --threads N positive worker cap for this run. Overrides SENBEI_THREADS;\n\ " --threads N positive worker cap for this run. Overrides SENBEI_THREADS;\n\
\x20 1 selects the sequential path. The environment is unchanged." \x20 1 selects the sequential path. The environment is unchanged."
); );
println!(
" --color MODE auto (default), always, or never; --color=MODE also works.\n\
\x20 Auto colors terminal stdout/stderr separately, unless\n\
\x20 NO_COLOR is nonempty or TERM=dumb. Explicit always/never\n\
\x20 override these variables. JSON and saved logs stay plain."
);
println!( println!(
" --scan-all probe selected .exe/.dll/.so/metadata names below the\n\ " --scan-all probe selected .exe/.dll/.so/metadata names below the\n\
\x20 size floor; other filenames remain excluded." \x20 size floor; other filenames remain excluded."
+269
View File
@@ -0,0 +1,269 @@
//! Terminal presentation is opt-in for pipes and never enters stored data.
#[path = "support/fixtures.rs"]
mod fixtures;
use std::path::Path;
use std::process::{Command, Output};
fn senbei() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command
.arg("--no-pause")
.env_remove("NO_COLOR")
.env("TERM", "xterm-256color");
command
}
fn fixture(root: &Path) -> std::path::PathBuf {
let path = root.join("global-metadata.dat");
std::fs::write(&path, fixtures::obfuscated_metadata()).unwrap();
path
}
fn text(bytes: &[u8]) -> &str {
std::str::from_utf8(bytes).expect("UTF-8 console output")
}
fn assert_plain(output: &Output) {
for bytes in [&output.stdout, &output.stderr] {
assert!(!bytes.contains(&0x1b), "unexpected ANSI: {}", text(bytes));
assert!(!text(bytes).to_ascii_lowercase().contains("\\u001b"));
}
}
fn strip_styles(value: &str) -> String {
let mut chars = value.chars();
let mut plain = String::new();
while let Some(ch) = chars.next() {
if ch == '\x1b' {
assert_eq!(chars.next(), Some('['));
for code in chars.by_ref() {
if code == 'm' {
break;
}
assert!(code.is_ascii_digit() || code == ';');
}
} else {
plain.push(ch);
}
}
plain
}
#[test]
fn inspect_colors_preserve_report_content() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
let plain = senbei()
.arg("inspect")
.arg(&path)
.args(["--color", "never"])
.output()
.unwrap();
let colored = senbei()
.arg("inspect")
.arg(&path)
.arg("--color=always")
.output()
.unwrap();
assert!(plain.status.success());
assert!(colored.status.success());
assert_plain(&plain);
assert!(colored.stdout.contains(&0x1b));
assert!(colored.stderr.is_empty());
let strip_time = |value: &str| {
value
.lines()
.filter(|line| !line.ends_with(" ms"))
.collect::<Vec<_>>()
.join("\n")
};
assert_eq!(
strip_time(&strip_styles(text(&colored.stdout))),
strip_time(text(&plain.stdout))
);
assert!(text(&colored.stdout).contains("\x1b[32msucceeded\x1b[0m"));
assert!(!temp.path().join("unpack").exists());
}
#[test]
fn ordinary_unpack_colors_results_but_not_saved_logs() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
let out = temp.path().join("out");
let output = senbei()
.arg("unpack")
.arg(&path)
.arg("--out")
.arg(&out)
.args(["--color", "always"])
.output()
.unwrap();
assert!(output.status.success(), "{}", text(&output.stderr));
assert!(output.stdout.contains(&0x1b));
assert!(text(&output.stdout).contains("\x1b[32m✓\x1b[0m"));
assert!(out.join("global-metadata.unpack.dat").is_file());
let logs: Vec<_> = std::fs::read_dir(&out)
.unwrap()
.flatten()
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|value| value == "log"))
.collect();
assert_eq!(logs.len(), 1);
let log = std::fs::read_to_string(&logs[0]).unwrap();
assert!(!log.contains('\x1b'));
assert!(!log.contains("\\u001b"));
assert!(log.contains("summary:"));
assert!(log.contains("method fields"));
}
#[test]
fn folder_unpack_uses_the_same_palette_and_plain_logs() {
let temp = tempfile::tempdir().unwrap();
fixture(temp.path());
let output = senbei()
.arg("unpack")
.arg(temp.path())
.args(["--color=always", "--scan-all"])
.output()
.unwrap();
assert!(output.status.success(), "{}", text(&output.stderr));
assert!(text(&output.stdout).contains("\x1b[32m✓\x1b[0m"));
assert!(text(&output.stdout).contains("metadata"));
for entry in std::fs::read_dir(temp.path().join("unpack"))
.unwrap()
.flatten()
{
if entry.path().extension().is_some_and(|value| value == "log") {
assert!(!std::fs::read(entry.path()).unwrap().contains(&0x1b));
}
}
}
#[test]
fn redirected_auto_and_never_are_plain_for_both_commands() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
for operation in ["inspect", "unpack"] {
for args in [vec![], vec!["--color", "auto"], vec!["--color=never"]] {
let output = senbei()
.arg(operation)
.arg(&path)
.args(args)
.arg("--no-log")
.output()
.unwrap();
assert!(output.status.success());
assert_plain(&output);
}
}
}
#[test]
fn explicit_color_overrides_no_color_and_dumb_terminal() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
for operation in ["inspect", "unpack"] {
let forced = senbei()
.env("NO_COLOR", "1")
.env("TERM", "dumb")
.arg(operation)
.arg(&path)
.args(["--color=always", "--no-log"])
.output()
.unwrap();
assert!(forced.status.success());
assert!(forced.stdout.contains(&0x1b));
let plain = senbei()
.env("NO_COLOR", "1")
.env("TERM", "dumb")
.arg(operation)
.arg(&path)
.args(["--color=auto", "--no-log"])
.output()
.unwrap();
assert!(plain.status.success());
assert_plain(&plain);
}
}
#[test]
fn json_stays_plain_even_with_forced_color_and_verbose() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
for operation in ["inspect", "unpack"] {
let out = temp.path().join(format!("json-{operation}"));
let mut command = senbei();
command
.arg(operation)
.arg(&path)
.args(["--json", "--verbose", "--color", "always"]);
if operation == "unpack" {
command.arg("--out").arg(&out);
}
let output = command.output().unwrap();
assert!(output.status.success(), "{}", text(&output.stderr));
assert_plain(&output);
assert!(output.stderr.is_empty());
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(report["inputs"][0]["profile"]["recovery"], "succeeded");
if out.exists() {
assert!(
std::fs::read_dir(&out)
.unwrap()
.flatten()
.all(|entry| entry.path().extension().is_none_or(|value| value != "log"))
);
}
}
}
#[test]
fn forced_color_diagnostics_use_stderr_and_quiet_still_wins() {
let temp = tempfile::tempdir().unwrap();
let invalid = temp.path().join("invalid.exe");
std::fs::write(&invalid, b"not a protected image").unwrap();
let failed = senbei()
.arg(&invalid)
.args(["--color=always", "--no-log"])
.output()
.unwrap();
assert_eq!(failed.status.code(), Some(1));
assert!(text(&failed.stderr).contains("\x1b[31merror\x1b[0m"));
for operation in ["inspect", "unpack"] {
let output = senbei()
.arg(operation)
.arg(&invalid)
.args(["--color=always", "--no-log", "-q", "-q"])
.output()
.unwrap();
assert!(output.stdout.is_empty());
assert!(output.stderr.is_empty());
}
}
#[test]
fn invalid_color_arguments_are_usage_errors_and_help_explains_policy() {
for args in [
vec!["--color"],
vec!["--color="],
vec!["--color=bright"],
vec!["--color", "bright"],
] {
let output = senbei().args(args).output().unwrap();
assert_eq!(output.status.code(), Some(2));
assert!(text(&output.stderr).contains("--color requires auto, always, or never"));
assert_plain(&output);
}
let help = senbei().arg("--help").output().unwrap();
let help = text(&help.stdout);
for fact in [
"--color",
"NO_COLOR",
"TERM=dumb",
"JSON and saved logs stay plain",
] {
assert!(help.contains(fact), "missing {fact}: {help}");
}
}
+75 -23
View File
@@ -7,6 +7,7 @@ use crate::report::{
CompanionReport, CompanionState, ContainerReport, Digest, EntryKind, EntryReport, EntryStatus, CompanionReport, CompanionState, ContainerReport, Digest, EntryKind, EntryReport, EntryStatus,
InputReport, InputStatus, OutputFile, Role, Stage, StageReport, StageStatus, InputReport, InputStatus, OutputFile, Role, Stage, StageReport, StageStatus,
}; };
use crate::ui::{Palette, Tone};
pub use crate::windows::{ pub use crate::windows::{
UnpackedImage, unpack_bytes, unpack_bytes_force_exe, unpack_bytes_force_exe_profiled, UnpackedImage, unpack_bytes, unpack_bytes_force_exe, unpack_bytes_force_exe_profiled,
unpack_bytes_force_exe_profiled_v, unpack_bytes_profiled, unpack_bytes_profiled_v, unpack_one, unpack_bytes_force_exe_profiled_v, unpack_bytes_profiled, unpack_bytes_profiled_v, unpack_one,
@@ -33,14 +34,28 @@ pub struct Summary {
} }
impl Summary { impl Summary {
/// The summary line shared by CLI output and the log file. /// The plain summary line shared by CLI output and the log file.
pub fn line(&self) -> String { pub fn line(&self) -> String {
self.line_with_palette(crate::ui::Palette::plain())
}
/// Console rendering without adding presentation escapes to log data.
pub fn line_with_palette(&self, palette: crate::ui::Palette) -> String {
use crate::ui::{Tone, count};
let mut line = format!( let mut line = format!(
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata", "{} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
self.unpacked, self.skipped, self.errors, self.suspect, self.metadata count(palette, self.unpacked, Tone::Success),
count(palette, self.skipped, Tone::Muted),
count(palette, self.errors, Tone::Error),
count(palette, self.suspect, Tone::Warning),
count(palette, self.metadata, Tone::Success)
); );
if self.packages > 0 { if self.packages > 0 {
line.push_str(&format!(" · {} packages", self.packages)); line.push_str(&format!(
" · {} packages",
palette.paint(Tone::Value, self.packages)
));
} }
line line
} }
@@ -215,7 +230,8 @@ fn run_folder_inner(
let scan_failed = scan_stats.walk_errors + scan_stats.probe_errors; let scan_failed = scan_stats.walk_errors + scan_stats.probe_errors;
if scan_failed > 0 && quiet == 0 { if scan_failed > 0 && quiet == 0 {
eprintln!( eprintln!(
"warning: {} file(s) could not be read during the scan and may be missed targets", "{}: {} file(s) could not be read during the scan and may be missed targets",
Palette::stderr().paint(Tone::Warning, "warning"),
scan_failed scan_failed
); );
} }
@@ -415,7 +431,12 @@ fn run_folder_inner(
if let Some(validation) = &report_validation { if let Some(validation) = &report_validation {
if !suppress_file_lines { if !suppress_file_lines {
for message in &validation.messages { for message in &validation.messages {
eprintln!("- {} {}", rel.display(), message); eprintln!(
"{} {} {}",
Palette::stderr().paint(Tone::Warning, "-"),
rel.display(),
message
);
} }
} }
if let Some(log) = &log { if let Some(log) = &log {
@@ -719,7 +740,8 @@ fn run_folder_inner(
s.skipped += 1; s.skipped += 1;
if !suppress_file_lines { if !suppress_file_lines {
eprintln!( eprintln!(
"- {} unsupported metadata version {v}, left untouched", "{} {} unsupported metadata version {v}, left untouched",
Palette::stderr().paint(Tone::Warning, "-"),
rel.display() rel.display()
); );
} }
@@ -895,8 +917,11 @@ fn run_file_inner(
} }
if quiet == 0 { if quiet == 0 {
println!( println!(
"✓ metadata v{} -> {:?} ({} method fields remapped)", "{} metadata v{} -> {} ({} method fields remapped)",
report.version, dest, report.remapped Palette::stdout().paint(Tone::Success, "✓"),
Palette::stdout().paint(Tone::Value, report.version),
Palette::stdout().paint(Tone::Value, format!("{dest:?}")),
Palette::stdout().paint(Tone::Value, report.remapped)
); );
} }
if let Some(reporter) = reporter.as_deref_mut() { if let Some(reporter) = reporter.as_deref_mut() {
@@ -915,8 +940,10 @@ fn run_file_inner(
} }
if quiet == 0 { if quiet == 0 {
println!( println!(
"metadata v{}: already de-obfuscated, nothing to do", "metadata v{}: {}",
report.version Palette::stdout().paint(Tone::Value, report.version),
Palette::stdout()
.paint(Tone::Muted, "already de-obfuscated, nothing to do")
); );
} }
if let Some(reporter) = reporter.as_deref_mut() { if let Some(reporter) = reporter.as_deref_mut() {
@@ -933,7 +960,7 @@ fn run_file_inner(
} }
// Level 1 quiet: banner/summary/duration only (match folder mode). // Level 1 quiet: banner/summary/duration only (match folder mode).
if quiet == 0 { if quiet == 0 {
eprintln!("error: {e:#}"); eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
} }
if let Some(reporter) = reporter.as_deref_mut() { if let Some(reporter) = reporter.as_deref_mut() {
let unsupported = unsupported_version(&e); let unsupported = unsupported_version(&e);
@@ -973,7 +1000,13 @@ fn run_file_inner(
log.step(&format!("OK {:?} -> {:?} (Android SO)", input, dest)); log.step(&format!("OK {:?} -> {:?} (Android SO)", input, dest));
} }
if quiet == 0 { if quiet == 0 {
println!("✓ So {} -> {}", input.display(), dest.display()); let palette = Palette::stdout();
println!(
"{} {} -> {}",
palette.paint(Tone::Success, "✓ So"),
palette.paint(Tone::Label, input.display()),
palette.paint(Tone::Value, dest.display())
);
} }
match write_embedded_metadata(embedded, &dest) { match write_embedded_metadata(embedded, &dest) {
Ok(Some(meta_dest)) => { Ok(Some(meta_dest)) => {
@@ -983,9 +1016,10 @@ fn run_file_inner(
} }
if quiet == 0 { if quiet == 0 {
println!( println!(
"✓ metadata {} (embedded) -> {}", "{} metadata {} (embedded) -> {}",
input.display(), Palette::stdout().paint(Tone::Success, "✓"),
meta_dest.display() Palette::stdout().paint(Tone::Label, input.display()),
Palette::stdout().paint(Tone::Value, meta_dest.display())
); );
} }
} }
@@ -996,7 +1030,10 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: embedded metadata: {e:#}", input)); log.step(&format!("ERR {:?}: embedded metadata: {e:#}", input));
} }
if quiet == 0 { if quiet == 0 {
eprintln!("error: embedded metadata: {e:#}"); eprintln!(
"{}: embedded metadata: {e:#}",
Palette::stderr().paint(Tone::Error, "error")
);
} }
} }
} }
@@ -1013,7 +1050,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input)); log.step(&format!("ERR {:?}: {e:#}", input));
} }
if quiet == 0 { if quiet == 0 {
eprintln!("error: {e:#}"); eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
} }
if let Some(reporter) = reporter.as_deref_mut() { if let Some(reporter) = reporter.as_deref_mut() {
let mut reported = android_library_input_with_error( let mut reported = android_library_input_with_error(
@@ -1067,7 +1104,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input)); log.step(&format!("ERR {:?}: {e:#}", input));
} }
if quiet == 0 { if quiet == 0 {
eprintln!("error: {e:#}"); eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
} }
if let Some(reporter) = reporter { if let Some(reporter) = reporter {
reporter.push(failed_input(input, &e, t0)); reporter.push(failed_input(input, &e, t0));
@@ -1097,7 +1134,12 @@ fn run_file_inner(
log.step(&format!("OK {:?} -> {:?} ({kind:?})", input, dest)); log.step(&format!("OK {:?} -> {:?} ({kind:?})", input, dest));
} }
if quiet == 0 { if quiet == 0 {
println!("✓ {:?} -> {:?}", kind, dest); let palette = Palette::stdout();
println!(
"{} -> {}",
palette.paint(Tone::Success, format!("✓ {kind:?}")),
palette.paint(Tone::Value, format!("{dest:?}"))
);
} }
if !report.ok() { if !report.ok() {
s.suspect = 1; s.suspect = 1;
@@ -1110,7 +1152,11 @@ fn run_file_inner(
} }
if quiet == 0 { if quiet == 0 {
eprintln!( eprintln!(
"! integrity check failed (likely to crash at runtime): {}", "{}: {}",
Palette::stderr().paint(
Tone::Warning,
"! integrity check failed (likely to crash at runtime)"
),
report.issues.join("; ") report.issues.join("; ")
); );
} }
@@ -1127,7 +1173,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input)); log.step(&format!("ERR {:?}: {e:#}", input));
} }
if quiet == 0 { if quiet == 0 {
eprintln!("error: {e:#}"); eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
} }
if let Some(reporter) = reporter { if let Some(reporter) = reporter {
let mut reported = match profile { let mut reported = match profile {
@@ -1275,7 +1321,10 @@ fn deobfuscate_metadata_researched(
} }
write_atomic(dest, &out)?; write_atomic(dest, &out)?;
if verbose { if verbose {
println!("Write to {}", dest.display()); println!(
"Write to {}",
Palette::stdout().paint(Tone::Value, dest.display())
);
} }
} }
Ok((report, layout, metadata_research)) Ok((report, layout, metadata_research))
@@ -1706,7 +1755,10 @@ fn unpack_one_researched(
return (profile, observed, Err(error.into())); return (profile, observed, Err(error.into()));
} }
if verbose { if verbose {
println!("Write to {}", dest.display()); println!(
"Write to {}",
Palette::stdout().paint(Tone::Value, dest.display())
);
} }
(profile, observed, Ok((image.kind, image.integrity))) (profile, observed, Ok((image.kind, image.integrity)))
} }
+62 -12
View File
@@ -469,38 +469,64 @@ impl Report {
}) })
} }
/// One-line summary in the same shape as [`crate::job::Summary::line`]. /// Plain summary in the same shape as [`crate::job::Summary::line`].
pub fn summary_line(&self) -> String { pub fn summary_line(&self) -> String {
self.summary_line_with_palette(crate::ui::Palette::plain())
}
/// Console summary with colors for actual nonzero outcomes.
pub fn summary_line_with_palette(&self, palette: crate::ui::Palette) -> String {
use crate::ui::{Tone, count};
let s = &self.summary; let s = &self.summary;
let mut line = format!( let mut line = format!(
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata", "{} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
s.recovered, s.skipped, s.errors, s.suspect, s.metadata count(palette, s.recovered, Tone::Success),
count(palette, s.skipped, Tone::Muted),
count(palette, s.errors, Tone::Error),
count(palette, s.suspect, Tone::Warning),
count(palette, s.metadata, Tone::Success)
); );
if s.packages > 0 { if s.packages > 0 {
line.push_str(&format!(" · {} packages", s.packages)); line.push_str(&format!(
" · {} packages",
palette.paint(Tone::Value, s.packages)
));
} }
line line
} }
/// Human-readable rendering, one block per input, for non-`--json` runs. /// Plain human-readable rendering, independent of the destination terminal.
pub fn render_text(&self) -> String { pub fn render_text(&self) -> String {
self.render_text_with_palette(crate::ui::Palette::plain())
}
/// Human-readable rendering with an explicit console palette. Report data
/// and JSON remain unstyled; callers select the destination's color policy.
pub fn render_text_with_palette(&self, palette: crate::ui::Palette) -> String {
use crate::ui::Tone;
let mut text = String::new(); let mut text = String::new();
if let Some(scan) = self.scan { if let Some(scan) = self.scan {
text.push_str(&format!( text.push_str(&format!(
"scan: {} probed non-targets · {} walk errors · {} probe errors\n", "{}: {} probed non-targets · {} walk errors · {} probe errors\n",
scan.non_target_skipped, scan.walk_errors, scan.probe_errors palette.paint(Tone::Heading, "scan"),
scan.non_target_skipped,
scan.walk_errors,
scan.probe_errors
)); ));
if scan.walk_errors > 0 || scan.probe_errors > 0 { if scan.walk_errors > 0 || scan.probe_errors > 0 {
text.push_str("warning: analysis is incomplete; some directory entries or selected files could not be examined\n"); text.push_str(&format!("{}: analysis is incomplete; some directory entries or selected files could not be examined\n", palette.paint(Tone::Warning, "warning")));
} }
} }
for input in &self.inputs { for input in &self.inputs {
text.push_str(&text::render_input(input)); text.push_str(&text::render_input(input, palette));
} }
if !self.errors.is_empty() { for error in &self.errors {
for error in &self.errors { text.push_str(&format!(
text.push_str(&format!("error: {error}\n")); "{}: {error}\n",
} palette.paint(Tone::Error, "error")
));
} }
text text
} }
@@ -815,6 +841,30 @@ mod tests {
assert!(value["inputs"][0]["recovered"]["sha256"].is_string()); assert!(value["inputs"][0]["recovered"]["sha256"].is_string());
} }
#[test]
fn console_colors_never_enter_report_data_or_plain_rendering() {
use crate::ui::{Palette, Tone};
let mut collector = Collector::new(Mode::Inspect);
collector.push(sample_input(InputStatus::Error));
collector.set_scan(ScanReport {
walk_errors: 1,
..ScanReport::default()
});
collector.push_error("input could not be examined");
let report = collector.finish();
let json = report.to_json();
let plain = report.render_text();
let colored = report.render_text_with_palette(Palette::colored());
assert!(colored.contains(&Palette::colored().paint(Tone::Heading, "scan").to_string()));
assert!(colored.contains(&Palette::colored().paint(Tone::Error, "error").to_string()));
assert!(!plain.contains('\x1b'));
assert!(!json.contains('\x1b'));
assert!(!json.contains("\\u001b"));
assert_eq!(report.to_json(), json);
assert_eq!(report.render_text_with_palette(Palette::plain()), plain);
}
#[test] #[test]
fn error_status_counts_and_surfaces_in_the_summary() { fn error_status_counts_and_surfaces_in_the_summary() {
let mut collector = Collector::new(Mode::Unpack); let mut collector = Collector::new(Mode::Unpack);
+307 -82
View File
@@ -1,12 +1,53 @@
//! Human-readable research reports. JSON retains the same underlying evidence. //! Human-readable research reports. JSON retains the same underlying evidence.
use std::fmt::Write; use std::fmt::{self, Write};
use senbei_engine::windows::{ResearchTrace, TraceValue, WindowsInspection}; use senbei_engine::windows::{ResearchTrace, TraceValue, WindowsInspection};
use serde::Serialize; use serde::Serialize;
use serde_json::Value; use serde_json::Value;
use super::{AndroidResearchReport, InputReport}; use super::{AndroidResearchReport, InputReport};
use crate::ui::{Painted, Palette, Tone};
struct Text {
contents: String,
palette: Palette,
}
impl Text {
fn new(palette: Palette) -> Self {
Self {
contents: String::new(),
palette,
}
}
}
impl Write for Text {
fn write_str(&mut self, value: &str) -> fmt::Result {
self.contents.write_str(value)
}
}
fn status(palette: Palette, value: &impl Serialize) -> Painted<String> {
status_text(palette, label(value))
}
fn status_text(palette: Palette, value: String) -> Painted<String> {
let normalized = value.replace('_', " ");
let tone = match normalized.as_str() {
"ok" | "clean" | "succeeded" | "restored" | "unchanged" | "accepted" | "matched"
| "validated" => Tone::Success,
"error" | "failed" | "unreadable" | "rejected" => Tone::Error,
"warning" | "warnings" | "suspect" | "blocked" | "unmatched" | "budget limited" => {
Tone::Warning
}
"skipped" | "not run" | "not attempted" | "unavailable" | "absent" | "duplicate"
| "not recognized" => Tone::Muted,
_ => Tone::Value,
};
palette.paint(tone, value)
}
fn label(value: &impl Serialize) -> String { fn label(value: &impl Serialize) -> String {
match serde_json::to_value(value) { match serde_json::to_value(value) {
@@ -16,24 +57,40 @@ fn label(value: &impl Serialize) -> String {
} }
} }
fn hex<T: Into<u64>>(value: Option<T>) -> String { fn hex<T: Into<u64>>(palette: Palette, value: Option<T>) -> Painted<String> {
value let tone = if value.is_some() {
.map(|value| format!("0x{:X}", value.into())) Tone::Value
.unwrap_or_else(|| "unavailable".to_owned()) } else {
Tone::Muted
};
palette.paint(
tone,
value
.map(|value| format!("0x{:X}", value.into()))
.unwrap_or_else(|| "unavailable".to_owned()),
)
} }
fn diagnostic(text: &mut String, indent: &str, kind: &str, message: &str) { fn diagnostic(text: &mut Text, indent: &str, kind: &str, message: &str) {
let tone = match kind {
"error" => Tone::Error,
"warning" | "parse issue" | "reason" => Tone::Warning,
_ => Tone::Muted,
};
let palette = text.palette;
for line in message.lines() { for line in message.lines() {
let _ = writeln!(text, "{indent}{kind}: {line}"); let _ = writeln!(text, "{indent}{}: {line}", palette.paint(tone, kind));
} }
} }
pub(super) fn render_input(input: &InputReport) -> String { pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
let mut text = format!("{}\n", input.path); let mut text = Text::new(palette);
let _ = writeln!(text, "{}", palette.paint(Tone::Heading, &input.path));
if input.analysis_incomplete { if input.analysis_incomplete {
let _ = writeln!( let _ = writeln!(
text, text,
" analysis incomplete: I/O, resource limits or infrastructure prevented the requested work" " {}: I/O, resource limits or infrastructure prevented the requested work",
palette.paint(Tone::Error, "analysis incomplete")
); );
} }
if let Some(source) = &input.source { if let Some(source) = &input.source {
@@ -42,7 +99,11 @@ pub(super) fn render_input(input: &InputReport) -> String {
" source: {} bytes (0x{:X})", " source: {} bytes (0x{:X})",
source.size, source.size source.size, source.size
); );
let _ = writeln!(text, " SHA-256: {}", source.sha256); let _ = writeln!(
text,
" SHA-256: {}",
palette.paint(Tone::Muted, &source.sha256)
);
} }
if let Some(profile) = &input.profile { if let Some(profile) = &input.profile {
let target = &profile.observed; let target = &profile.observed;
@@ -64,7 +125,7 @@ pub(super) fn render_input(input: &InputReport) -> String {
let _ = writeln!( let _ = writeln!(
text, text,
" protection recognition: {}", " protection recognition: {}",
label(&profile.recognition) status(palette, &profile.recognition)
); );
if !profile.evidence.is_empty() { if !profile.evidence.is_empty() {
let evidence = profile let evidence = profile
@@ -79,8 +140,8 @@ pub(super) fn render_input(input: &InputReport) -> String {
let _ = writeln!( let _ = writeln!(
text, text,
" route {}: {}", " route {}: {}",
label(&candidate.layout), palette.paint(Tone::Label, label(&candidate.layout)),
label(&candidate.outcome) status(palette, &candidate.outcome)
); );
for message in &candidate.warnings { for message in &candidate.warnings {
diagnostic(&mut text, " ", "warning", message); diagnostic(&mut text, " ", "warning", message);
@@ -90,20 +151,28 @@ pub(super) fn render_input(input: &InputReport) -> String {
} }
} }
if let Some(selected) = profile.selected { if let Some(selected) = profile.selected {
let _ = writeln!(text, " selected route: {}", label(&selected)); let _ = writeln!(
text,
" selected route: {}",
palette.paint(Tone::Success, label(&selected))
);
} }
let _ = writeln!(text, " static recovery: {}", label(&profile.recovery)); let _ = writeln!(
text,
" static recovery: {}",
status(palette, &profile.recovery)
);
let _ = writeln!( let _ = writeln!(
text, text,
" output static validation: {}", " output static validation: {}",
label(&profile.static_validation) status(palette, &profile.static_validation)
); );
} }
if let Some(companion) = &input.companion { if let Some(companion) = &input.companion {
let _ = writeln!( let _ = writeln!(
text, text,
" companion: {}{}", " companion: {}{}",
label(&companion.state), status(palette, &companion.state),
companion companion
.path .path
.as_ref() .as_ref()
@@ -140,18 +209,18 @@ pub(super) fn render_input(input: &InputReport) -> String {
let _ = writeln!( let _ = writeln!(
text, text,
" protected → recovered: entry RVA {} → {} · SizeOfImage {} → {} · sections {} → {}", " protected → recovered: entry RVA {} → {} · SizeOfImage {} → {} · sections {} → {}",
hex(before.entry_point_rva), hex(palette, before.entry_point_rva),
hex(after.entry_point_rva), hex(palette, after.entry_point_rva),
hex(before.size_of_image), hex(palette, before.size_of_image),
hex(after.size_of_image), hex(palette, after.size_of_image),
before.sections.len(), before.sections.len(),
after.sections.len() after.sections.len()
); );
let _ = writeln!( let _ = writeln!(
text, text,
" DLL characteristics {} → {}", " DLL characteristics {} → {}",
hex(before.dll_characteristics), hex(palette, before.dll_characteristics),
hex(after.dll_characteristics) hex(palette, after.dll_characteristics)
); );
} }
render_windows(&mut text, "recovered image (not retained)", restored); render_windows(&mut text, "recovered image (not retained)", restored);
@@ -206,15 +275,19 @@ pub(super) fn render_input(input: &InputReport) -> String {
render_android(&mut text, " ", research); render_android(&mut text, " ", research);
} }
if let Some(research) = &input.metadata_research { if let Some(research) = &input.metadata_research {
let _ = writeln!(text, " metadata transform evidence:"); let _ = writeln!(
text,
" {}:",
palette.paint(Tone::Heading, "metadata transform evidence")
);
render_tree(&mut text, " ", research); render_tree(&mut text, " ", research);
} }
for entry in &input.entries { for entry in &input.entries {
let _ = writeln!( let _ = writeln!(
text, text,
" entry {}: {}{}", " entry {}: {}{}",
entry.name, palette.paint(Tone::Label, &entry.name),
label(&entry.status), status(palette, &entry.status),
entry entry
.output .output
.as_ref() .as_ref()
@@ -224,7 +297,8 @@ pub(super) fn render_input(input: &InputReport) -> String {
if entry.analysis_incomplete { if entry.analysis_incomplete {
let _ = writeln!( let _ = writeln!(
text, text,
" analysis incomplete: requested entry analysis could not finish" " {}: requested entry analysis could not finish",
palette.paint(Tone::Error, "analysis incomplete")
); );
} }
if let Some(layout) = entry.layout { if let Some(layout) = entry.layout {
@@ -249,7 +323,11 @@ pub(super) fn render_input(input: &InputReport) -> String {
render_android(&mut text, " ", research); render_android(&mut text, " ", research);
} }
if let Some(research) = &entry.metadata_research { if let Some(research) = &entry.metadata_research {
let _ = writeln!(text, " metadata transform evidence:"); let _ = writeln!(
text,
" {}:",
palette.paint(Tone::Heading, "metadata transform evidence")
);
render_tree(&mut text, " ", research); render_tree(&mut text, " ", research);
} }
} }
@@ -260,8 +338,8 @@ pub(super) fn render_input(input: &InputReport) -> String {
let _ = writeln!( let _ = writeln!(
text, text,
" stage {}: {}{}", " stage {}: {}{}",
label(&stage.stage), palette.paint(Tone::Label, label(&stage.stage)),
label(&stage.status), status(palette, &stage.status),
stage stage
.duration_ms .duration_ms
.map(|elapsed| format!(" · {elapsed} ms")) .map(|elapsed| format!(" · {elapsed} ms"))
@@ -298,14 +376,20 @@ pub(super) fn render_input(input: &InputReport) -> String {
let _ = writeln!( let _ = writeln!(
text, text,
" inspection status: {} · {} ms", " inspection status: {} · {} ms",
label(&input.status), status(palette, &input.status),
input.duration_ms input.duration_ms
); );
text text.contents
} }
fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspection) { fn render_windows(text: &mut Text, heading: &str, inspection: &WindowsInspection) {
let _ = writeln!(text, " {heading}: {} bytes", inspection.input_len); let palette = text.palette;
let _ = writeln!(
text,
" {}: {} bytes",
palette.paint(Tone::Heading, heading),
inspection.input_len
);
if let Some(pe) = &inspection.pe { if let Some(pe) = &inspection.pe {
let machine = match pe.machine { let machine = match pe.machine {
Some(0x14c) => "x86", Some(0x14c) => "x86",
@@ -316,8 +400,8 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!( let _ = writeln!(
text, text,
" PE header: {} · {machine} ({})", " PE header: {} · {machine} ({})",
hex(pe.pe_offset), hex(palette, pe.pe_offset),
hex(pe.machine) hex(palette, pe.machine)
); );
let _ = writeln!( let _ = writeln!(
text, text,
@@ -334,15 +418,15 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!( let _ = writeln!(
text, text,
" image base: {} · SizeOfImage: {} · SizeOfHeaders: {}", " image base: {} · SizeOfImage: {} · SizeOfHeaders: {}",
hex(pe.image_base), hex(palette, pe.image_base),
hex(pe.size_of_image), hex(palette, pe.size_of_image),
hex(pe.size_of_headers) hex(palette, pe.size_of_headers)
); );
let _ = writeln!( let _ = writeln!(
text, text,
" entry point: RVA {} · file offset {} · file-backed: {}", " entry point: RVA {} · file offset {} · file-backed: {}",
hex(pe.entry_point_rva), hex(palette, pe.entry_point_rva),
hex(pe.entry_point_file_offset), hex(palette, pe.entry_point_file_offset),
pe.entry_point_available pe.entry_point_available
.map(|value| value.to_string()) .map(|value| value.to_string())
.unwrap_or_else(|| "unavailable".to_owned()) .unwrap_or_else(|| "unavailable".to_owned())
@@ -350,14 +434,14 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!( let _ = writeln!(
text, text,
" alignments: section {} · file {}", " alignments: section {} · file {}",
hex(pe.section_alignment), hex(palette, pe.section_alignment),
hex(pe.file_alignment) hex(palette, pe.file_alignment)
); );
let _ = writeln!( let _ = writeln!(
text, text,
" declared flags: COFF {} · DLL {} (runtime behavior not tested)", " declared flags: COFF {} · DLL {} (runtime behavior not tested)",
hex(pe.characteristics), hex(palette, pe.characteristics),
hex(pe.dll_characteristics) hex(palette, pe.dll_characteristics)
); );
for flag in &pe.named_flags { for flag in &pe.named_flags {
let _ = writeln!( let _ = writeln!(
@@ -368,19 +452,28 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
flag.bit flag.bit
); );
} }
let _ = writeln!(text, " sections ({}):", pe.sections.len());
let _ = writeln!( let _ = writeln!(
text, text,
" # name RVA virtual size raw offset raw size R W X" " {} ({}):",
palette.paint(Tone::Label, "sections"),
pe.sections.len()
);
let _ = writeln!(
text,
"{}",
palette.paint(
Tone::Label,
" # name RVA virtual size raw offset raw size R W X"
)
); );
for section in &pe.sections { for section in &pe.sections {
let p = &section.permissions; let p = &section.permissions;
let name = section.name.escape_debug().to_string(); let name = section.name.escape_debug().to_string();
let _ = writeln!( let _ = writeln!(
text, text,
" {:>2} {:<10} 0x{:08X} 0x{:08X} 0x{:08X} 0x{:08X} {} {} {}", " {:>2} {} 0x{:08X} 0x{:08X} 0x{:08X} 0x{:08X} {} {} {}",
section.index, section.index,
name, palette.paint(Tone::Label, format!("{name:<10}")),
section.virtual_address, section.virtual_address,
section.virtual_size, section.virtual_size,
section.raw_offset, section.raw_offset,
@@ -407,17 +500,22 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!(text, " observation: {}", label(anomaly)); let _ = writeln!(text, " observation: {}", label(anomaly));
} }
} }
let _ = writeln!(text, " data directories ({}):", pe.directories.len()); let _ = writeln!(
text,
" {} ({}):",
palette.paint(Tone::Label, "data directories"),
pe.directories.len()
);
for directory in &pe.directories { for directory in &pe.directories {
let _ = writeln!( let _ = writeln!(
text, text,
" {:>2} {:<18} {} 0x{:08X} · size 0x{:X} · file {} · {}", " {:>2} {} {} 0x{:08X} · size 0x{:X} · file {} · {}",
directory.index, directory.index,
directory.name, palette.paint(Tone::Label, format!("{:<18}", directory.name)),
label(&directory.address_space), label(&directory.address_space),
directory.address, directory.address,
directory.size, directory.size,
hex(directory.file_offset), hex(palette, directory.file_offset),
label(&directory.mapping) label(&directory.mapping)
); );
if let Some(note) = directory.note { if let Some(note) = directory.note {
@@ -461,7 +559,7 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!( let _ = writeln!(
text, text,
" header-table decode: magic {} · supported KONN: {}", " header-table decode: magic {} · supported KONN: {}",
hex(protection.magic), hex(palette, protection.magic),
protection.magic_recognized protection.magic_recognized
); );
for word in &protection.header_words { for word in &protection.header_words {
@@ -513,7 +611,7 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!( let _ = writeln!(
text, text,
" payload probe: {} · scratch requested 0x{:X} · constructed 0x{:X} · ceiling 0x{:X}", " payload probe: {} · scratch requested 0x{:X} · constructed 0x{:X} · ceiling 0x{:X}",
label(&probe.status), status(palette, &probe.status),
probe.requested_length, probe.requested_length,
probe.decoded_length, probe.decoded_length,
probe.limit_bytes probe.limit_bytes
@@ -539,7 +637,7 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!( let _ = writeln!(
text, text,
" shell discovery: {} · {} positions scanned · {} candidates reported", " shell discovery: {} · {} positions scanned · {} candidates reported",
label(&discovery.status), status(palette, &discovery.status),
discovery.positions_scanned, discovery.positions_scanned,
discovery.candidates.len() discovery.candidates.len()
); );
@@ -550,18 +648,18 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!( let _ = writeln!(
text, text,
" {}: {} · decoded offset {} · image RVA {} · source file {}", " {}: {} · decoded offset {} · image RVA {} · source file {}",
label(&candidate.kind), palette.paint(Tone::Label, label(&candidate.kind)),
label(&candidate.status), status(palette, &candidate.status),
hex(candidate.payload_offset), hex(palette, candidate.payload_offset),
hex(candidate.image_rva), hex(palette, candidate.image_rva),
hex(candidate.source_file_offset) hex(palette, candidate.source_file_offset)
); );
let _ = writeln!(text, " {}", candidate.reason); let _ = writeln!(text, " {}", candidate.reason);
for field in &candidate.fields { for field in &candidate.fields {
let _ = writeln!( let _ = writeln!(
text, text,
" {} = 0x{:X}{}", " {} = 0x{:X}{}",
field.name, palette.paint(Tone::Label, field.name),
field.value, field.value,
field field
.space .space
@@ -576,7 +674,7 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
let _ = writeln!( let _ = writeln!(
text, text,
" {} [{}]: {}", " {} [{}]: {}",
label(&issue.severity), status(palette, &issue.severity),
issue.area, issue.area,
issue.message issue.message
); );
@@ -584,22 +682,28 @@ fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspecti
if inspection.work.budget_limited { if inspection.work.budget_limited {
let _ = writeln!( let _ = writeln!(
text, text,
" inspection work was budget-limited; omitted probes are not negative evidence" " {}",
palette.paint(
Tone::Warning,
"inspection work was budget-limited; omitted probes are not negative evidence"
)
); );
} }
} }
fn render_trace(text: &mut String, trace: &ResearchTrace) { fn render_trace(text: &mut Text, trace: &ResearchTrace) {
let palette = text.palette;
let _ = writeln!( let _ = writeln!(
text, text,
" actual static-pipeline discoveries ({} events):", " {} ({} events):",
palette.paint(Tone::Heading, "actual static-pipeline discoveries"),
trace.events.len() trace.events.len()
); );
let mut previous = String::new(); let mut previous = String::new();
for event in &trace.events { for event in &trace.events {
let stage = label(&event.stage); let stage = label(&event.stage);
if previous != stage { if previous != stage {
let _ = writeln!(text, " {stage}:"); let _ = writeln!(text, " {}:", palette.paint(Tone::Label, &stage));
previous = stage; previous = stage;
} }
let value = match &event.value { let value = match &event.value {
@@ -621,7 +725,13 @@ fn render_trace(text: &mut String, trace: &ResearchTrace) {
.as_ref() .as_ref()
.map(|address| format!(" @ {} 0x{:X}", label(&address.space), address.offset)) .map(|address| format!(" @ {} 0x{:X}", label(&address.space), address.offset))
.unwrap_or_default(); .unwrap_or_default();
let _ = writeln!(text, " {}: {value}{provenance}", event.name); let _ = writeln!(
text,
" {}: {}{}",
palette.paint(Tone::Label, event.name),
status_text(palette, value),
palette.paint(Tone::Muted, provenance)
);
if let Some(note) = event.note { if let Some(note) = event.note {
let _ = writeln!(text, " {note}"); let _ = writeln!(text, " {note}");
} }
@@ -629,28 +739,44 @@ fn render_trace(text: &mut String, trace: &ResearchTrace) {
if trace.truncated { if trace.truncated {
let _ = writeln!( let _ = writeln!(
text, text,
" trace truncated at {} events; {} events omitted", " {}",
trace.limit, trace.dropped palette.paint(
Tone::Warning,
format!(
"trace truncated at {} events; {} events omitted",
trace.limit, trace.dropped
)
)
); );
} }
} }
fn render_android(text: &mut String, indent: &str, research: &AndroidResearchReport) { fn render_android(text: &mut Text, indent: &str, research: &AndroidResearchReport) {
let _ = writeln!(text, "{indent}Android extraction evidence:"); let palette = text.palette;
let _ = writeln!(
text,
"{indent}{}:",
palette.paint(Tone::Heading, "Android extraction evidence")
);
render_tree(text, &format!("{indent} "), &research.extraction); render_tree(text, &format!("{indent} "), &research.extraction);
if let Some(restoration) = &research.restoration { if let Some(restoration) = &research.restoration {
let _ = writeln!(text, "{indent}Android restoration evidence:"); let _ = writeln!(
text,
"{indent}{}:",
palette.paint(Tone::Heading, "Android restoration evidence")
);
render_tree(text, &format!("{indent} "), restoration); render_tree(text, &format!("{indent} "), restoration);
} }
} }
fn render_tree(text: &mut String, indent: &str, value: &Value) { fn render_tree(text: &mut Text, indent: &str, value: &Value) {
let palette = text.palette;
match value { match value {
Value::Object(fields) => { Value::Object(fields) => {
for (name, value) in fields { for (name, value) in fields {
match value { match value {
Value::Array(_) | Value::Object(_) => { Value::Array(_) | Value::Object(_) => {
let _ = writeln!(text, "{indent}{name}:"); let _ = writeln!(text, "{indent}{}:", palette.paint(Tone::Label, name));
render_tree(text, &format!("{indent} "), value); render_tree(text, &format!("{indent} "), value);
} }
Value::Number(number) => { Value::Number(number) => {
@@ -658,13 +784,28 @@ fn render_tree(text: &mut String, indent: &str, value: &Value) {
.as_u64() .as_u64()
.map(|value| format!("{value} (0x{value:X})")) .map(|value| format!("{value} (0x{value:X})"))
.unwrap_or_else(|| number.to_string()); .unwrap_or_else(|| number.to_string());
let _ = writeln!(text, "{indent}{name}: {numeric}"); let _ = writeln!(
text,
"{indent}{}: {}",
palette.paint(Tone::Label, name),
palette.paint(Tone::Value, numeric)
);
} }
Value::String(value) => { Value::String(value) => {
let _ = writeln!(text, "{indent}{name}: {}", value.escape_debug()); let _ = writeln!(
text,
"{indent}{}: {}",
palette.paint(Tone::Label, name),
status_text(palette, value.escape_debug().to_string())
);
} }
_ => { _ => {
let _ = writeln!(text, "{indent}{name}: {value}"); let _ = writeln!(
text,
"{indent}{}: {}",
palette.paint(Tone::Label, name),
palette.paint(Tone::Value, value)
);
} }
} }
} }
@@ -690,6 +831,73 @@ mod tests {
use senbei_engine::{Kind, ObservedTarget, ProtectionProfile, TargetFormat}; use senbei_engine::{Kind, ObservedTarget, ProtectionProfile, TargetFormat};
use std::path::Path; use std::path::Path;
fn strip_styles(text: &str) -> String {
let mut plain = String::new();
let mut chars = text.chars();
while let Some(ch) = chars.next() {
if ch == '\x1b' {
assert_eq!(chars.next(), Some('['));
for code in chars.by_ref() {
if code == 'm' {
break;
}
assert!(code.is_ascii_digit() || code == ';');
}
} else {
plain.push(ch);
}
}
plain
}
#[test]
fn colors_distinguish_findings_from_actual_recovery_verdicts() {
let palette = Palette::colored();
for (value, tone) in [
("recognized", Tone::Value),
("structural_candidate", Tone::Value),
("succeeded", Tone::Success),
("clean", Tone::Success),
("suspect", Tone::Warning),
("failed", Tone::Error),
("not_attempted", Tone::Muted),
] {
assert_eq!(
status(palette, &value).to_string(),
palette.paint(tone, value.replace('_', " ")).to_string()
);
}
}
#[test]
fn trace_and_tree_strings_keep_literal_underscores() {
use senbei_engine::windows::{ResearchEvent, ResearchStage};
let trace = ResearchTrace {
events: vec![ResearchEvent {
stage: ResearchStage::Header,
name: "route",
value: TraceValue::Text("exe_style".to_owned()),
address: None,
note: None,
}],
truncated: false,
dropped: 0,
limit: 1,
};
for palette in [Palette::plain(), Palette::colored()] {
let mut text = Text::new(palette);
render_trace(&mut text, &trace);
render_tree(
&mut text,
"",
&serde_json::json!({"path": "app_data/module_0c.bin"}),
);
let plain = strip_styles(&text.contents);
assert!(plain.contains("route: exe_style"));
assert!(plain.contains("path: app_data/module_0c.bin"));
}
}
#[test] #[test]
fn text_keeps_target_source_context_and_diagnostics() { fn text_keeps_target_source_context_and_diagnostics() {
let mut input = InputReport::new(Path::new("module.exe"), Role::Content); let mut input = InputReport::new(Path::new("module.exe"), Role::Content);
@@ -713,7 +921,10 @@ mod tests {
StageReport::new(Stage::Recovery, StageStatus::Failed) StageReport::new(Stage::Recovery, StageStatus::Failed)
.detail("parameters were unavailable"), .detail("parameters were unavailable"),
); );
let text = render_input(&input); let text = render_input(&input, Palette::plain());
let colored = render_input(&input, Palette::colored());
assert!(colored.contains('\x1b'));
assert_eq!(strip_styles(&colored), text);
for fact in [ for fact in [
"SHA-256:", "SHA-256:",
"pe32", "pe32",
@@ -746,8 +957,19 @@ mod tests {
dropped: 2, dropped: 2,
limit: 1, limit: 1,
}; };
let mut text = String::new(); let mut text = Text::new(Palette::plain());
render_trace(&mut text, &trace); render_trace(&mut text, &trace);
let text = text.contents;
let mut colored = Text::new(Palette::colored());
render_trace(&mut colored, &trace);
assert_eq!(strip_styles(&colored.contents), text);
assert!(
colored.contents.contains(
&Palette::colored()
.paint(Tone::Value, "0x00001234 (4660)")
.to_string()
)
);
for fact in [ for fact in [
"0x00001234", "0x00001234",
"file offset 0x1000", "file offset 0x1000",
@@ -769,7 +991,10 @@ mod tests {
}); });
input.metadata_research = input.metadata_research =
Some(serde_json::json!({"tried_seeds": [0x5678], "route": "seeded"})); Some(serde_json::json!({"tried_seeds": [0x5678], "route": "seeded"}));
let text = render_input(&input); let text = render_input(&input, Palette::plain());
let colored = render_input(&input, Palette::colored());
assert!(colored.contains('\x1b'));
assert_eq!(strip_styles(&colored), text);
for fact in [ for fact in [
"header_seed: 4660 (0x1234)", "header_seed: 4660 (0x1234)",
"module_registry:", "module_registry:",
+295 -18
View File
@@ -1,23 +1,191 @@
use indicatif::{ProgressBar, ProgressStyle}; use indicatif::{ProgressBar, ProgressStyle};
use owo_colors::OwoColorize; use owo_colors::Style;
use senbei_engine::{IntegrityReport, Kind}; use senbei_engine::{IntegrityReport, Kind};
use std::cell::Cell;
use std::fmt::{self, Display};
use std::io::IsTerminal;
use std::path::Path; use std::path::Path;
/// Color policy for human-readable console output. Machine reports and logs
/// never use the console palette.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ColorMode {
#[default]
Auto,
Always,
Never,
}
thread_local! {
static COLOR_MODE: Cell<ColorMode> = const { Cell::new(ColorMode::Auto) };
}
/// Apply a console policy to one caller's run, restoring it on return or panic.
pub fn with_color_mode<R>(mode: ColorMode, f: impl FnOnce() -> R) -> R {
struct Restore(ColorMode);
impl Drop for Restore {
fn drop(&mut self) {
COLOR_MODE.set(self.0);
}
}
let _restore = Restore(COLOR_MODE.replace(mode));
f()
}
/// Presentation roles shared by unpack progress and research reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tone {
Heading,
Label,
Value,
Success,
Warning,
Error,
Muted,
}
/// A resolved palette. Explicit palettes keep string rendering deterministic;
/// only the console entry points consult the terminal and environment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Palette {
colored: bool,
}
impl Palette {
pub const fn plain() -> Self {
Self { colored: false }
}
pub const fn colored() -> Self {
Self { colored: true }
}
pub const fn is_colored(self) -> bool {
self.colored
}
pub fn stdout() -> Self {
Self::for_stream(false)
}
pub fn stderr() -> Self {
Self::for_stream(true)
}
fn for_stream(stderr: bool) -> Self {
let terminal = if stderr {
std::io::stderr().is_terminal()
} else {
std::io::stdout().is_terminal()
};
let mode = COLOR_MODE.get();
let no_color = std::env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty());
let dumb = std::env::var_os("TERM").is_some_and(|value| value == "dumb");
let mut colored = color_enabled(mode, terminal, no_color, dumb);
if colored && terminal && !enable_ansi(stderr) && mode == ColorMode::Auto {
colored = false;
}
Self { colored }
}
pub fn paint<T: Display>(self, tone: Tone, value: T) -> Painted<T> {
Painted {
palette: self,
tone,
value,
}
}
}
pub(crate) fn count(palette: Palette, value: usize, nonzero: Tone) -> Painted<usize> {
palette.paint(if value == 0 { Tone::Muted } else { nonzero }, value)
}
fn color_enabled(mode: ColorMode, terminal: bool, no_color: bool, dumb: bool) -> bool {
match mode {
ColorMode::Auto => terminal && !no_color && !dumb,
ColorMode::Always => true,
ColorMode::Never => false,
}
}
#[cfg(windows)]
fn enable_ansi(stderr: bool) -> bool {
use windows::Win32::System::Console::{
CONSOLE_MODE, ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle,
STD_ERROR_HANDLE, STD_OUTPUT_HANDLE, SetConsoleMode,
};
// These borrowed standard handles are not closed. Read the existing mode
// before enabling VT so other console flags are preserved.
unsafe {
let Ok(handle) = GetStdHandle(if stderr {
STD_ERROR_HANDLE
} else {
STD_OUTPUT_HANDLE
}) else {
return false;
};
let mut mode = CONSOLE_MODE::default();
if GetConsoleMode(handle, &mut mode).is_err() {
return false;
}
mode.contains(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
|| SetConsoleMode(handle, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING).is_ok()
}
}
#[cfg(not(windows))]
fn enable_ansi(_stderr: bool) -> bool {
true
}
/// A styled console value. The underlying value is never modified or stored in
/// a report, so formatting the same data for JSON or a log remains plain.
pub struct Painted<T> {
palette: Palette,
tone: Tone,
value: T,
}
impl<T: Display> Display for Painted<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.palette.colored {
return Display::fmt(&self.value, f);
}
let style = match self.tone {
Tone::Heading => Style::new().cyan().bold(),
Tone::Label => Style::new().blue().bold(),
Tone::Value => Style::new().cyan(),
Tone::Success => Style::new().green(),
Tone::Warning => Style::new().yellow(),
Tone::Error => Style::new().red(),
Tone::Muted => Style::new().dimmed(),
};
Display::fmt(&style.style(&self.value), f)
}
}
/// Create a progress bar for `n` items. Hidden when `quiet` is true. /// Create a progress bar for `n` items. Hidden when `quiet` is true.
pub fn progress(n: u64, quiet: bool) -> ProgressBar { pub fn progress(n: u64, quiet: bool) -> ProgressBar {
if quiet || n == 0 { if quiet || n == 0 {
return ProgressBar::hidden(); return ProgressBar::hidden();
} }
let bar = ProgressBar::new(n); let bar = ProgressBar::new(n);
let template = if Palette::stderr().is_colored() {
"[{elapsed_precise}] {bar:40.cyan/blue} {pos}/{len} {msg}"
} else {
"[{elapsed_precise}] {bar:40} {pos}/{len} {msg}"
};
bar.set_style( bar.set_style(
ProgressStyle::default_bar() ProgressStyle::default_bar()
.template("[{elapsed_precise}] {bar:40.cyan/blue} {pos}/{len} {msg}") .template(template)
.unwrap_or_else(|_| ProgressStyle::default_bar()), .unwrap_or_else(|_| ProgressStyle::default_bar()),
); );
bar bar
} }
/// Print a green success line, suspending the progress bar. /// Print a success line, suspending the progress bar.
pub fn ok(bar: &ProgressBar, quiet: bool, rel: &Path, kind: Kind, dest: &Path) { pub fn ok(bar: &ProgressBar, quiet: bool, rel: &Path, kind: Kind, dest: &Path) {
ok_label( ok_label(
bar, bar,
@@ -28,52 +196,161 @@ pub fn ok(bar: &ProgressBar, quiet: bool, rel: &Path, kind: Kind, dest: &Path) {
); );
} }
/// Print a green success line with a free-form kind label (Android targets), /// Print a success line with a free-form kind label (Android targets),
/// suspending the progress bar. /// suspending the progress bar.
pub fn ok_label(bar: &ProgressBar, quiet: bool, rel: &str, label: &str, dest: &Path) { pub fn ok_label(bar: &ProgressBar, quiet: bool, rel: &str, label: &str, dest: &Path) {
if quiet { if quiet {
return; return;
} }
let msg = format!("{} {} {} -> {}", "✓".green(), label, rel, dest.display()); let palette = Palette::stdout();
let msg = format!(
"{} {} {} -> {}",
palette.paint(Tone::Success, "✓"),
palette.paint(Tone::Success, label),
palette.paint(Tone::Label, rel),
palette.paint(Tone::Value, dest.display())
);
bar.suspend(|| println!("{msg}")); bar.suspend(|| println!("{msg}"));
} }
/// Print a green success line for a de-obfuscated il2cpp `global-metadata.dat`, /// Print a success line for de-obfuscated IL2CPP metadata, reporting how many
/// reporting how many protected method fields were remapped. /// protected method fields were remapped.
pub fn metadata(bar: &ProgressBar, quiet: bool, rel: &Path, remapped: usize, dest: &Path) { pub fn metadata(bar: &ProgressBar, quiet: bool, rel: &Path, remapped: usize, dest: &Path) {
if quiet { if quiet {
return; return;
} }
let palette = Palette::stdout();
let msg = format!( let msg = format!(
"{} metadata {} -> {} ({} method fields remapped)", "{} metadata {} -> {} ({} method fields remapped)",
"✓".green(), palette.paint(Tone::Success, "✓"),
rel.display(), palette.paint(Tone::Label, rel.display()),
dest.display(), palette.paint(Tone::Value, dest.display()),
remapped palette.paint(Tone::Value, remapped)
); );
bar.suspend(|| println!("{msg}")); bar.suspend(|| println!("{msg}"));
} }
/// Print a red error line, suspending the progress bar. /// Print an error line, suspending the progress bar.
pub fn err(bar: &ProgressBar, quiet: bool, rel: &Path, e: &anyhow::Error) { pub fn err(bar: &ProgressBar, quiet: bool, rel: &Path, e: &anyhow::Error) {
if quiet { if quiet {
return; return;
} }
let msg = format!("{} {} {e:#}", "✗".red(), rel.display()); let palette = Palette::stderr();
let msg = format!(
"{} {} {e:#}",
palette.paint(Tone::Error, "✗"),
palette.paint(Tone::Label, rel.display())
);
bar.suspend(|| eprintln!("{msg}")); bar.suspend(|| eprintln!("{msg}"));
} }
/// Print a yellow warning line for a file that unpacked but failed the static /// Print a warning for an output that failed the static integrity check,
/// integrity check (likely to crash at runtime), suspending the progress bar. /// suspending the progress bar.
pub fn suspect(bar: &ProgressBar, quiet: bool, rel: &Path, report: &IntegrityReport) { pub fn suspect(bar: &ProgressBar, quiet: bool, rel: &Path, report: &IntegrityReport) {
if quiet { if quiet {
return; return;
} }
let palette = Palette::stderr();
let msg = format!( let msg = format!(
"{} {} integrity check failed: {}", "{} {} {}: {}",
"!".yellow(), palette.paint(Tone::Warning, "!"),
rel.display(), palette.paint(Tone::Label, rel.display()),
palette.paint(Tone::Warning, "integrity check failed"),
report.issues.join("; ") report.issues.join("; ")
); );
bar.suspend(|| eprintln!("{msg}")); bar.suspend(|| eprintln!("{msg}"));
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn auto_color_checks_each_destination_and_environment() {
for terminal in [false, true] {
for no_color in [false, true] {
for dumb in [false, true] {
assert_eq!(
color_enabled(ColorMode::Auto, terminal, no_color, dumb),
terminal && !no_color && !dumb
);
assert!(color_enabled(ColorMode::Always, terminal, no_color, dumb));
assert!(!color_enabled(ColorMode::Never, terminal, no_color, dumb));
}
}
}
}
#[test]
fn explicit_palettes_preserve_text_and_distinguish_severity() {
for tone in [
Tone::Heading,
Tone::Label,
Tone::Value,
Tone::Success,
Tone::Warning,
Tone::Error,
Tone::Muted,
] {
assert_eq!(
Palette::plain().paint(tone, "模块 → 0x1234").to_string(),
"模块 → 0x1234"
);
let styled = Palette::colored().paint(tone, "模块 → 0x1234").to_string();
assert!(styled.starts_with("\x1b["));
assert!(styled.ends_with("\x1b[0m"));
assert!(styled.contains("模块 → 0x1234"));
}
assert!(
Palette::colored()
.paint(Tone::Error, "error")
.to_string()
.contains("[31m")
);
assert!(
Palette::colored()
.paint(Tone::Warning, "warning")
.to_string()
.contains("[33m")
);
assert!(
Palette::colored()
.paint(Tone::Success, "ok")
.to_string()
.contains("[32m")
);
}
#[test]
fn nested_color_scopes_restore_the_enclosing_policy() {
let previous = COLOR_MODE.get();
with_color_mode(ColorMode::Never, || {
assert!(!Palette::stdout().is_colored());
with_color_mode(ColorMode::Always, || {
assert!(Palette::stdout().is_colored());
assert!(Palette::stderr().is_colored());
});
assert!(!Palette::stderr().is_colored());
});
assert_eq!(COLOR_MODE.get(), previous);
}
#[test]
fn panic_restores_color_policy_and_callers_are_thread_local() {
with_color_mode(ColorMode::Never, || {
let failure = std::panic::catch_unwind(|| {
with_color_mode(ColorMode::Always, || panic!("synthetic unwind"));
});
assert!(failure.is_err());
assert_eq!(COLOR_MODE.get(), ColorMode::Never);
std::thread::spawn(|| {
with_color_mode(ColorMode::Always, || {
assert!(Palette::stdout().is_colored())
});
})
.join()
.unwrap();
assert!(!Palette::stdout().is_colored());
});
}
}