feat: localize console output and add a run observer

Engine errors, integrity findings, and driver outcomes carry message
codes from senbei-i18n, with their English unchanged, so reports, logs,
and --json stay byte-identical. Verbose pipeline steps go through a
progress sink instead of println!, and an error chain is translated
through its first coded cause.

The CLI takes the display language from SENBEI_LANG, or else from the
system's preferred UI language, and translates console text: usage
errors, help, per-file lines, the run summary, and the summary lines of
the inspect report. Structural research evidence and saved logs stay
English. When a translation leaves out context the English chain has,
the English follows on a muted line.

A front end can attach a RunObserver and a CancelToken to the Collector
to follow a run input by input, receive verbose steps as events, and
stop before the next input. A cancelled report says so. The CLI never
cancels, so its JSON is unchanged.
This commit is contained in:
Momoko-Ayase committed 2026-11-08 02:41:04 +08:00
1 parent 9481b0ccf9
commit 4853fe22c0
39 files changed
+2016 -684

No files matched your search

Generated
+3
View File
@@ -426,6 +426,7 @@ version = "1.3.4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"senbei-engine", "senbei-engine",
"senbei-i18n",
"senbei-io", "senbei-io",
"senbei-metadata", "senbei-metadata",
"serde", "serde",
@@ -457,6 +458,7 @@ dependencies = [
"memmap2", "memmap2",
"senbei-crypto", "senbei-crypto",
"senbei-elf", "senbei-elf",
"senbei-i18n",
"senbei-pe", "senbei-pe",
"serde", "serde",
"serde_json", "serde_json",
@@ -485,6 +487,7 @@ dependencies = [
"senbei-crypto", "senbei-crypto",
"senbei-elf", "senbei-elf",
"senbei-engine", "senbei-engine",
"senbei-i18n",
"senbei-metadata", "senbei-metadata",
"senbei-pe", "senbei-pe",
"serde", "serde",
+1
View File
@@ -38,6 +38,7 @@ thiserror = "2"
walkdir = "2" walkdir = "2"
windows = { version = "0.62", features = [ windows = { version = "0.62", features = [
"Win32_Foundation", "Win32_Foundation",
"Win32_Globalization",
"Win32_System_Console", "Win32_System_Console",
"Win32_System_SystemInformation", "Win32_System_SystemInformation",
] } ] }
+1
View File
@@ -14,6 +14,7 @@ path = "src/main.rs"
[dependencies] [dependencies]
senbei-io.workspace = true senbei-io.workspace = true
senbei-engine.workspace = true senbei-engine.workspace = true
senbei-i18n.workspace = true
[dev-dependencies] [dev-dependencies]
anyhow.workspace = true anyhow.workspace = true
+80 -106
View File
@@ -1,19 +1,26 @@
use senbei_engine::android::ResourceLimits; use senbei_engine::android::ResourceLimits;
use senbei_i18n::{Cli, Localize};
use senbei_io::{ use senbei_io::{
job, pause, scan, job,
message::of_error,
pause, scan,
ui::{self, ColorMode, Palette, Tone}, ui::{self, ColorMode, Palette, Tone},
}; };
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::path::Path; use std::path::Path;
fn main() -> std::process::ExitCode { fn main() -> std::process::ExitCode {
// Console text follows the user's language; logs and JSON stay English.
senbei_i18n::set_current(senbei_io::locale::detect());
let mut options = match Options::parse(std::env::args().skip(1)) { let mut options = match Options::parse(std::env::args().skip(1)) {
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) => {
let lang = senbei_i18n::current();
eprintln!( eprintln!(
"{}: {message}", "{}: {}",
Palette::stderr().paint(Tone::Error, "error") Palette::stderr().paint(Tone::Error, Cli::Error.localize(lang)),
message.localize(lang)
); );
return std::process::ExitCode::from(2); return std::process::ExitCode::from(2);
} }
@@ -67,7 +74,7 @@ enum Outcome {
} }
impl Options { impl Options {
fn parse(args: impl Iterator<Item = String>) -> Result<Outcome, String> { fn parse(args: impl Iterator<Item = String>) -> Result<Outcome, Box<Cli>> {
let mut args = args.peekable(); let mut args = args.peekable();
let mut command = Command::Unpack; let mut command = Command::Unpack;
let mut subcommand: Option<String> = None; let mut subcommand: Option<String> = None;
@@ -114,11 +121,14 @@ impl Options {
} }
"--out" => match args.next() { "--out" => match args.next() {
Some(v) if !v.starts_with('-') => out = Some(v), Some(v) if !v.starts_with('-') => out = Some(v),
_ => return Err("--out requires a directory argument".to_owned()), _ => return Err(Cli::OutRequiresDirectory.into()),
}, },
other if other.starts_with('-') => { other if other.starts_with('-') => {
print_help(); print_help();
return Err(format!("unknown option '{other}'")); return Err(Cli::UnknownOption {
option: other.to_owned(),
}
.into());
} }
// A subcommand is only a subcommand when it is the first // A subcommand is only a subcommand when it is the first
// positional word. `senbei inspect` therefore means the // positional word. `senbei inspect` therefore means the
@@ -137,9 +147,11 @@ impl Options {
} }
other => { other => {
if let Some(prev) = &path { if let Some(prev) = &path {
return Err(format!( return Err(Cli::MultipleInputs {
"multiple input paths given ('{prev}' and '{other}')" first: prev.clone(),
)); second: other.to_owned(),
}
.into());
} }
path = Some(other.to_string()); path = Some(other.to_string());
} }
@@ -150,7 +162,7 @@ impl Options {
// A subcommand with no path is a usage error; no arguments at all // A subcommand with no path is a usage error; no arguments at all
// still prints help and exits 2, as before. // still prints help and exits 2, as before.
if let Some(subcommand) = subcommand { if let Some(subcommand) = subcommand {
return Err(format!("'{subcommand}' requires an input path")); return Err(Cli::SubcommandNeedsPath { subcommand }.into());
} }
print_help(); print_help();
return Ok(Outcome::Handled(std::process::ExitCode::from(2))); return Ok(Outcome::Handled(std::process::ExitCode::from(2)));
@@ -160,10 +172,10 @@ impl Options {
// rejected rather than guessed at. // rejected rather than guessed at.
if command == Command::Inspect { if command == Command::Inspect {
if dry_run { if dry_run {
return Err("'inspect' writes nothing; drop --dry-run".to_owned()); return Err(Cli::InspectNoDryRun.into());
} }
if out.is_some() { if out.is_some() {
return Err("'inspect' writes nothing; --out is not allowed".to_owned()); return Err(Cli::InspectNoOut.into());
} }
// `--strict-integrity` is meaningful: inspection runs the real // `--strict-integrity` is meaningful: inspection runs the real
// static check and reports its verdict. // static check and reports its verdict.
@@ -177,7 +189,7 @@ impl Options {
if dry_run { if dry_run {
// A dry run keeps nothing: no ordinary output directory, no log. // A dry run keeps nothing: no ordinary output directory, no log.
if out.is_some() { if out.is_some() {
return Err("--dry-run writes no output; --out is not allowed".to_owned()); return Err(Cli::DryRunNoOut.into());
} }
no_log = true; no_log = true;
} }
@@ -201,20 +213,20 @@ impl Options {
} }
} }
fn parse_color(value: Option<&str>) -> Result<ColorMode, String> { fn parse_color(value: Option<&str>) -> Result<ColorMode, Box<Cli>> {
match value { match value {
Some("auto") => Ok(ColorMode::Auto), Some("auto") => Ok(ColorMode::Auto),
Some("always") => Ok(ColorMode::Always), Some("always") => Ok(ColorMode::Always),
Some("never") => Ok(ColorMode::Never), Some("never") => Ok(ColorMode::Never),
_ => Err("--color requires auto, always, or never".to_owned()), _ => Err(Cli::ColorRequiresMode.into()),
} }
} }
fn parse_thread_cap(value: Option<&str>) -> Result<NonZeroUsize, String> { fn parse_thread_cap(value: Option<&str>) -> Result<NonZeroUsize, Box<Cli>> {
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()))
.and_then(|text| text.parse().ok()) .and_then(|text| text.parse().ok())
.ok_or_else(|| "--threads requires a positive integer argument".to_owned()) .ok_or_else(|| Cli::ThreadsRequiresInteger.into())
} }
/// Run the parsed command. Kept separate from argument parsing and the pause /// Run the parsed command. Kept separate from argument parsing and the pause
@@ -246,13 +258,10 @@ fn execute_inspect(options: &Options, path: &Path, scan_all: bool) -> u8 {
} }
Err(error) => { Err(error) => {
if options.machine { if options.machine {
let report = job::error_report(job::Mode::Inspect, &format!("{error:#}")); let report = job::error_report(job::Mode::Inspect, of_error(&error));
println!("{}", report.to_json()); println!("{}", report.to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
eprintln!( ui::print_anyhow(&error);
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
} }
1 1
} }
@@ -273,13 +282,10 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
} }
Err(error) => { Err(error) => {
if options.machine { if options.machine {
let report = job::error_report(job::Mode::DryRun, &format!("{error:#}")); let report = job::error_report(job::Mode::DryRun, of_error(&error));
println!("{}", report.to_json()); println!("{}", report.to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
eprintln!( ui::print_anyhow(&error);
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
} }
1 1
} }
@@ -350,10 +356,12 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
println!("{}", collector.finish().to_json()); println!("{}", collector.finish().to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
println!("{}", summary.line_with_palette(Palette::stdout())); println!("{}", summary.line_with_palette(Palette::stdout()));
let done = Cli::DoneIn {
ms: summary.duration_ms,
};
println!( println!(
"{}", "{}",
Palette::stdout() Palette::stdout().paint(Tone::Muted, done.localize(senbei_i18n::current()))
.paint(Tone::Muted, format!("done in {} ms", summary.duration_ms))
); );
} }
exit_code(&summary, options.strict_integrity) exit_code(&summary, options.strict_integrity)
@@ -361,13 +369,10 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
Err(error) => { Err(error) => {
if options.machine { if options.machine {
let mut failed = collector; let mut failed = collector;
failed.push_error(format!("{error:#}")); failed.push_error(of_error(&error));
println!("{}", failed.finish().to_json()); println!("{}", failed.finish().to_json());
} else if options.quiet < 2 { } else if options.quiet < 2 {
eprintln!( ui::print_anyhow(&error);
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
} }
1 1
} }
@@ -400,20 +405,27 @@ fn set_resource_limit(
limits: &mut ResourceLimits, limits: &mut ResourceLimits,
flag: &str, flag: &str,
value: Option<&str>, value: Option<&str>,
) -> Result<(), String> { ) -> Result<(), Box<Cli>> {
let invalid = || format!("{flag} requires an unsigned integer argument"); let invalid = || Cli::LimitRequiresInteger {
flag: flag.to_owned(),
};
let text = value let text = 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()))
.ok_or_else(invalid)?; .ok_or_else(invalid)?;
let value: u64 = text.parse().map_err(|_| invalid())?; let value: u64 = text.parse().map_err(|_| invalid())?;
if value == 0 && flag != "--max-depth" { if value == 0 && flag != "--max-depth" {
return Err(format!("{flag} must be greater than zero")); return Err(Cli::LimitMustBePositive {
flag: flag.to_owned(),
}
.into());
} }
match flag { match flag {
"--max-entry-mib" | "--max-total-mib" => { "--max-entry-mib" | "--max-total-mib" => {
let bytes = value let bytes = value
.checked_mul(1024 * 1024) .checked_mul(1024 * 1024)
.ok_or_else(|| format!("{flag} exceeds the supported byte range"))?; .ok_or_else(|| Cli::LimitTooLarge {
flag: flag.to_owned(),
})?;
if flag == "--max-entry-mib" { if flag == "--max-entry-mib" {
limits.max_entry_bytes = bytes; limits.max_entry_bytes = bytes;
} else { } else {
@@ -422,7 +434,12 @@ fn set_resource_limit(
} }
"--max-entries" => limits.max_entries = usize::try_from(value).map_err(|_| invalid())?, "--max-entries" => limits.max_entries = usize::try_from(value).map_err(|_| invalid())?,
"--max-depth" => limits.max_depth = usize::try_from(value).map_err(|_| invalid())?, "--max-depth" => limits.max_depth = usize::try_from(value).map_err(|_| invalid())?,
_ => return Err(format!("unknown resource option '{flag}'")), _ => {
return Err(Cli::UnknownLimit {
flag: flag.to_owned(),
}
.into());
}
} }
Ok(()) Ok(())
} }
@@ -431,73 +448,28 @@ fn print_help() {
println!( println!(
"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]" "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!(
" <file|folder>\n\
\x20 a CrackProof PE (.exe/.dll), an il2cpp global-metadata.dat,\n\
\x20 a protected Android AArch64 library (.so), an Android app\n\
\x20 package (.apk/.apks/.xapk), or a folder containing any of\n\
\x20 these. The bare form is the same as 'unpack'."
);
println!(
" inspect PATH\n\
\x20 run the real static recovery for research, and report\n\
\x20 everything observed: recognition evidence, each route\n\
\x20 tried and why it was rejected, the route selected, the\n\
\x20 static check's verdict, and the engines' own structural\n\
\x20 evidence (protected-header fields, seeds, module records,\n\
\x20 restored-image facts). Nothing is kept: no output file,\n\
\x20 no log, no temporary tree, and the input is never run."
);
println!(" unpack PATH detection and recovery; writes outputs (the default).");
println!(
" --json write one versioned machine-readable report to stdout and\n\
\x20 nothing else. Implies quiet and --no-log."
);
println!(
" --dry-run run the real recovery but keep nothing: no output tree and\n\
\x20 no log. Android extraction still uses its own temporary\n\
\x20 workspace, which is discarded."
);
println!(
" --threads N positive worker cap for this run. Overrides SENBEI_THREADS;\n\
\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!(
" --scan-all probe selected .exe/.dll/.so/metadata names below the\n\
\x20 size floor; other filenames remain excluded."
);
println!(
" --strict-integrity\n\
\x20 exit non-zero when any output fails the static integrity\n\
\x20 check (a suspect) or a file errors. Off by default: a\n\
\x20 suspect is still written and the process exits 0 unless\n\
\x20 a file errors. Quiet levels are unchanged.\n\
\x20 With 'inspect', the check applies to the image actually\n\
\x20 recovered for research; no output file is retained."
);
let defaults = ResourceLimits::default(); let defaults = ResourceLimits::default();
println!( let lang = senbei_i18n::current();
" Android resource limits (MiB = 1048576 bytes):\n\ for block in [
\x20 --max-entry-mib N single archive entry/decoded buffer/output (default {})\n\ Cli::HelpPath,
\x20 --max-total-mib N cumulative archive bytes and per-engine task budget (default {})\n\ Cli::HelpInspect,
\x20 --max-entries N archive entries/stage-2 records (default {})\n\ Cli::HelpUnpack,
\x20 --max-depth N nesting depth, root = 0 (default {})\n\ Cli::HelpJson,
\x20 Limits are checked before extraction/allocation; they are not a peak-RSS cap.", Cli::HelpDryRun,
defaults.max_entry_bytes / (1024 * 1024), Cli::HelpThreads,
defaults.max_total_bytes / (1024 * 1024), Cli::HelpColor,
defaults.max_entries, Cli::HelpScanAll,
defaults.max_depth, Cli::HelpStrictIntegrity,
); Cli::HelpLimits {
println!( entry_mib: defaults.max_entry_bytes / (1024 * 1024),
" Exit codes: 0 success, 1 a target failed (or a suspect with\n\ total_mib: defaults.max_total_bytes / (1024 * 1024),
\x20 --strict-integrity), 2 the command line was rejected." entries: defaults.max_entries,
); depth: defaults.max_depth,
},
Cli::HelpExitCodes,
] {
println!("{}", block.localize(lang));
}
} }
#[cfg(test)] #[cfg(test)]
@@ -641,7 +613,9 @@ mod command_line {
use super::*; use super::*;
fn parse(args: &[&str]) -> Result<Options, String> { fn parse(args: &[&str]) -> Result<Options, String> {
match Options::parse(args.iter().map(|arg| (*arg).to_string()))? { let parsed = Options::parse(args.iter().map(|arg| (*arg).to_string()))
.map_err(|error| error.localize(senbei_i18n::Lang::En).into_owned())?;
match parsed {
Outcome::Run(options) => Ok(options), Outcome::Run(options) => Ok(options),
Outcome::Handled(code) => Err(format!( Outcome::Handled(code) => Err(format!(
"handled: {}", "handled: {}",
+1
View File
@@ -10,6 +10,7 @@ fn senbei() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei")); let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command command
.arg("--no-pause") .arg("--no-pause")
.env("SENBEI_LANG", "en")
.env_remove("NO_COLOR") .env_remove("NO_COLOR")
.env("TERM", "xterm-256color"); .env("TERM", "xterm-256color");
command command
+140
View File
@@ -0,0 +1,140 @@
//! The console follows SENBEI_LANG (or the system language); saved logs and
//! `--json` reports stay English in every language.
#[path = "support/fixtures.rs"]
mod fixtures;
use std::path::Path;
use std::process::Command;
use senbei_i18n::{Cli, Lang, Localize};
fn senbei(lang: &str) -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command.arg("--no-pause").env("SENBEI_LANG", lang);
command
}
fn text(bytes: &[u8]) -> &str {
std::str::from_utf8(bytes).expect("UTF-8 console output")
}
fn fixture(root: &Path) -> std::path::PathBuf {
let path = root.join("global-metadata.dat");
std::fs::write(&path, fixtures::obfuscated_metadata()).unwrap();
path
}
fn without_timings(json: &str) -> String {
let mut value: serde_json::Value = serde_json::from_str(json).expect("one JSON document");
fn strip(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(map) => {
map.remove("duration_ms");
map.values_mut().for_each(strip);
}
serde_json::Value::Array(items) => items.iter_mut().for_each(strip),
_ => {}
}
}
strip(&mut value);
value.to_string()
}
#[test]
fn usage_errors_and_help_follow_the_language() {
for lang in [Lang::ZhCn, Lang::ZhTw, Lang::Ja, Lang::Ko] {
let output = senbei(lang.tag()).arg("--bogus").output().unwrap();
assert_eq!(output.status.code(), Some(2));
let expected = format!(
"{}: {}",
Cli::Error.localize(lang),
Cli::UnknownOption {
option: "--bogus".into()
}
.localize(lang)
);
assert!(text(&output.stderr).contains(&expected), "{lang:?}");
assert!(text(&output.stdout).contains(&*Cli::HelpJson.localize(lang)));
assert_ne!(
Cli::HelpJson.localize(lang),
Cli::HelpJson.localize(Lang::En),
"{lang:?} is still English"
);
}
}
#[test]
fn an_unknown_language_falls_back_to_english() {
for value in ["fr", "C", "x-unknown"] {
let output = senbei(value).arg("--bogus").output().unwrap();
assert!(
text(&output.stderr).contains("error: unknown option '--bogus'"),
"{value}"
);
}
}
#[test]
fn the_console_is_translated_while_logs_and_json_stay_english() {
let temp = tempfile::tempdir().unwrap();
let input = fixture(temp.path());
let out = temp.path().join("out");
let output = senbei("zh-CN")
.arg(&input)
.arg("--out")
.arg(&out)
.output()
.unwrap();
assert!(output.status.success(), "{}", text(&output.stderr));
let summary = Cli::Summary {
unpacked: "0".into(),
skipped: "0".into(),
errors: "0".into(),
suspect: "0".into(),
metadata: "1".into(),
};
let stdout = text(&output.stdout);
assert!(stdout.contains(&*summary.localize(Lang::ZhCn)), "{stdout}");
assert!(!stdout.contains("unpacked"), "{stdout}");
let log = std::fs::read_dir(&out)
.unwrap()
.flatten()
.map(|entry| entry.path())
.find(|path| path.extension().is_some_and(|value| value == "log"))
.expect("a run log");
let log = std::fs::read_to_string(log).unwrap();
assert!(
log.contains("summary: 0 unpacked · 0 skipped · 0 errors · 0 suspect · 1 metadata"),
"{log}"
);
let json = |lang: &str| {
let output = senbei(lang)
.args(["inspect", "--json"])
.arg(&input)
.output()
.unwrap();
assert!(output.status.success());
without_timings(text(&output.stdout))
};
assert_eq!(json("ko"), json("en"));
}
#[test]
fn inspect_text_translates_summary_lines_but_keeps_values() {
let temp = tempfile::tempdir().unwrap();
let input = fixture(temp.path());
let output = senbei("ja").arg("inspect").arg(&input).output().unwrap();
assert!(output.status.success());
let stdout = text(&output.stdout);
let recovery = Cli::StaticRecovery {
status: senbei_i18n::Term::Succeeded.localize(Lang::Ja).into_owned(),
};
assert!(stdout.contains(&*recovery.localize(Lang::Ja)), "{stdout}");
assert!(!stdout.contains("static recovery"), "{stdout}");
// Paths and the structural evidence are values, never translated.
assert!(stdout.contains(&*input.display().to_string()), "{stdout}");
assert!(stdout.contains("tried_seeds"), "{stdout}");
}
+157
View File
@@ -0,0 +1,157 @@
//! A front end follows a run through an observer and can stop it between
//! inputs. The CLI uses neither, so its output and reports are unaffected.
#[path = "support/fixtures.rs"]
mod fixtures;
use std::path::Path;
use std::sync::{Arc, Mutex};
use senbei_engine::android::ResourceLimits;
use senbei_io::job::{self, Collector, Mode};
use senbei_io::observe::{CancelToken, RunObserver};
use senbei_io::report::InputReport;
#[derive(Default)]
struct Recorder {
events: Mutex<Vec<String>>,
/// Cancelled when the first input finishes.
stop_after_first: Option<CancelToken>,
}
impl Recorder {
fn push(&self, event: String) {
self.events.lock().unwrap().push(event);
}
fn events(&self) -> Vec<String> {
self.events.lock().unwrap().clone()
}
}
fn parent_name(path: &Path) -> String {
path.parent()
.and_then(Path::file_name)
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default()
}
impl RunObserver for Recorder {
fn scanned(&self, inputs: usize) {
self.push(format!("scanned {inputs}"));
}
fn input_started(&self, path: &Path) {
self.push(format!("started {}", parent_name(path)));
}
fn progress(&self, event: &senbei_engine::progress::Event) {
if let senbei_engine::progress::Event::Step { step, .. } = event {
self.push(
format!("step {step:?}")
.split(' ')
.take(2)
.collect::<Vec<_>>()
.join(" "),
);
}
}
fn input_finished(&self, input: &InputReport) {
self.push(format!("finished {}", parent_name(Path::new(&input.path))));
if let Some(cancel) = &self.stop_after_first {
cancel.cancel();
}
}
}
/// Two applications, each with its own obfuscated metadata blob.
fn two_apps(root: &Path) {
for app in ["a", "b"] {
let dir = root.join(app);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("global-metadata.dat"),
fixtures::obfuscated_metadata(),
)
.unwrap();
}
}
fn run(root: &Path, out: &Path, collector: &mut Collector) {
job::run_folder_reported(
root,
Some(out),
2,
true,
true,
true,
&ResourceLimits::default(),
collector,
)
.unwrap();
}
#[test]
fn an_observer_sees_each_input_start_progress_and_finish() {
let temp = tempfile::tempdir().unwrap();
two_apps(temp.path());
let recorder = Arc::new(Recorder::default());
let mut collector = Collector::new(Mode::Unpack).with_observer(recorder.clone());
run(temp.path(), &temp.path().join("out"), &mut collector);
assert_eq!(
recorder.events(),
[
"scanned 2",
"started a",
"step WriteTo",
"finished a",
"started b",
"step WriteTo",
"finished b",
]
);
let report = collector.finish();
assert_eq!(report.inputs.len(), 2);
assert!(!report.cancelled);
assert!(!report.to_json().contains("cancelled"));
}
#[test]
fn cancelling_stops_before_the_next_input_and_is_reported() {
let temp = tempfile::tempdir().unwrap();
two_apps(temp.path());
let cancel = CancelToken::new();
let recorder = Arc::new(Recorder {
stop_after_first: Some(cancel.clone()),
..Recorder::default()
});
let mut collector = Collector::new(Mode::Unpack)
.with_observer(recorder.clone())
.with_cancel(cancel);
let out = temp.path().join("out");
run(temp.path(), &out, &mut collector);
assert_eq!(
recorder.events(),
["scanned 2", "started a", "step WriteTo", "finished a"]
);
let report = collector.finish();
assert_eq!(report.inputs.len(), 1);
assert!(report.cancelled);
assert!(report.to_json().contains("\"cancelled\":true"));
assert!(out.join("a").join("global-metadata.unpack.dat").is_file());
assert!(!out.join("b").exists());
}
#[test]
fn a_run_cancelled_before_it_starts_processes_nothing() {
let temp = tempfile::tempdir().unwrap();
two_apps(temp.path());
let cancel = CancelToken::new();
cancel.cancel();
let mut collector = Collector::new(Mode::DryRun).with_cancel(cancel);
run(temp.path(), &temp.path().join("out"), &mut collector);
let report = collector.finish();
assert!(report.inputs.is_empty());
assert!(report.cancelled);
}
+2 -1
View File
@@ -32,7 +32,7 @@ fn unreadable_unpack_input_blocks_routes_instead_of_inventing_an_attempt() {
fn senbei() -> Command { fn senbei() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei")); let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command.arg("--no-pause"); command.arg("--no-pause").env("SENBEI_LANG", "en");
command command
} }
@@ -638,6 +638,7 @@ fn a_relative_path_is_reported_verbatim() {
let td = tempfile::tempdir().unwrap(); let td = tempfile::tempdir().unwrap();
write_plain(td.path(), "plain.exe"); write_plain(td.path(), "plain.exe");
let output = Command::new(env!("CARGO_BIN_EXE_senbei")) let output = Command::new(env!("CARGO_BIN_EXE_senbei"))
.env("SENBEI_LANG", "en")
.current_dir(td.path()) .current_dir(td.path())
.args(["--no-pause", "inspect", "plain.exe", "--json"]) .args(["--no-pause", "inspect", "plain.exe", "--json"])
.output() .output()
+3 -1
View File
@@ -2,7 +2,9 @@ use std::process::Command;
fn command() -> Command { fn command() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei")); let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command.args(["--no-pause", "--no-log"]); command
.args(["--no-pause", "--no-log"])
.env("SENBEI_LANG", "en");
command command
} }
+3 -1
View File
@@ -10,7 +10,9 @@ use std::path::Path;
use std::process::Command; use std::process::Command;
fn senbei() -> Command { fn senbei() -> Command {
Command::new(env!("CARGO_BIN_EXE_senbei")) let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command.env("SENBEI_LANG", "en");
command
} }
fn run(args: &[&str]) -> std::process::Output { fn run(args: &[&str]) -> std::process::Output {
+8 -8
View File
@@ -835,10 +835,16 @@ fn run_pe(
output.detected_kind = Some(kind_name(image.kind).to_owned()); output.detected_kind = Some(kind_name(image.kind).to_owned());
output.bytes = Some(image.bytes.len() as u64); output.bytes = Some(image.bytes.len() as u64);
output.sha256 = Some(sha256_hex(&image.bytes)); output.sha256 = Some(sha256_hex(&image.bytes));
let issues: Vec<String> = image
.integrity
.issues
.iter()
.map(|issue| issue.text().to_owned())
.collect();
output.integrity = Some(IntegrityInfo { output.integrity = Some(IntegrityInfo {
ok: image.integrity.ok(), ok: image.integrity.ok(),
fatal: image.integrity.has_fatal(), fatal: image.integrity.has_fatal(),
issues: image.integrity.issues.clone(), issues: issues.clone(),
}); });
if expect_failure { if expect_failure {
output.fail("expected failure, but the input unpacked"); output.fail("expected failure, but the input unpacked");
@@ -847,13 +853,7 @@ fn run_pe(
"expected failure, but the input unpacked", "expected failure, but the input unpacked",
); );
} else { } else {
compare_output( compare_output(&mut output, &image.bytes, expected, allow_suspect, &issues);
&mut output,
&image.bytes,
expected,
allow_suspect,
&image.integrity.issues,
);
finish_case(report, &mut output, "unpacked"); finish_case(report, &mut output, "unpacked");
} }
} }
+3 -1
View File
@@ -3,7 +3,9 @@
use std::process::Command; use std::process::Command;
fn senbei() -> Command { fn senbei() -> Command {
Command::new(env!("CARGO_BIN_EXE_senbei")) let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command.env("SENBEI_LANG", "en");
command
} }
#[test] #[test]
+1
View File
@@ -14,6 +14,7 @@ sha2.workspace = true
tempfile.workspace = true tempfile.workspace = true
thiserror.workspace = true thiserror.workspace = true
senbei-crypto.workspace = true senbei-crypto.workspace = true
senbei-i18n.workspace = true
senbei-elf.workspace = true senbei-elf.workspace = true
senbei-pe.workspace = true senbei-pe.workspace = true
+4 -1
View File
@@ -84,7 +84,10 @@ pub fn probe_libil2cpp_profiled_with_limits(
} }
Err(error) => { Err(error) => {
profile.recognition = RecognitionStatus::Blocked; profile.recognition = RecognitionStatus::Blocked;
profile.push_error(error.to_string()); profile.push_error(match &error {
Error::Limit(limit) => limit.message(),
other => other.to_string().into(),
});
if let Error::Limit(_) = error { if let Error::Limit(_) = error {
profile profile
.candidates .candidates
+53
View File
@@ -110,6 +110,28 @@ pub enum LimitExceeded {
Depth { requested: usize, limit: usize }, Depth { requested: usize, limit: usize },
} }
impl LimitExceeded {
/// The ceiling as a translatable message whose English is this error's.
pub fn message(&self) -> senbei_i18n::Message {
use senbei_i18n::Msg;
let msg = match *self {
Self::Entry { requested, limit } => Msg::LimitEntry { requested, limit },
Self::Total {
requested,
adding,
limit,
} => Msg::LimitTotal {
requested,
adding,
limit,
},
Self::Entries { requested, limit } => Msg::LimitEntries { requested, limit },
Self::Depth { requested, limit } => Msg::LimitDepth { requested, limit },
};
senbei_i18n::Message::with_text(msg, self.to_string())
}
}
/// Running sum of retained or temporary bytes for one task. /// Running sum of retained or temporary bytes for one task.
/// ///
/// Each call starts its own budget at zero. Charging checks the single-entry /// Each call starts its own budget at zero. Charging checks the single-entry
@@ -213,6 +235,37 @@ impl EntryBudget {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn limit_messages_keep_the_error_wording_and_translate_it() {
use senbei_i18n::Lang;
for error in [
LimitExceeded::Entry {
requested: 10,
limit: 4,
},
LimitExceeded::Total {
requested: 9,
adding: 3,
limit: 8,
},
LimitExceeded::Entries {
requested: 101,
limit: 100,
},
LimitExceeded::Depth {
requested: 33,
limit: 32,
},
] {
let message = error.message();
assert_eq!(message.text(), error.to_string());
assert!(message.msg().is_some());
for lang in Lang::ALL {
assert_eq!(message.detail(lang), None, "{lang:?}");
}
}
}
#[test] #[test]
fn defaults_match_the_documented_ceilings() { fn defaults_match_the_documented_ceilings() {
let limits = ResourceLimits::default(); let limits = ResourceLimits::default();
@@ -8,6 +8,7 @@ use memmap2::{Mmap, MmapMut, MmapOptions};
use senbei_crypto::android::{ use senbei_crypto::android::{
ContainerHeader, HuffmanLzDecoder, Module9bConfig, ProtectedDescriptor, transform_segment, ContainerHeader, HuffmanLzDecoder, Module9bConfig, ProtectedDescriptor, transform_segment,
}; };
use senbei_i18n::Step;
use serde::Serialize; use serde::Serialize;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
@@ -463,12 +464,12 @@ where
data_cursor = encoded_end; data_cursor = encoded_end;
} }
if verbose { if verbose {
eprintln!( crate::progress::detail_err(format_args!(
"[{current:02}/{total:02}] writers={writer_count} encoded=0x{size:x}", "[{current:02}/{total:02}] writers={writer_count} encoded=0x{size:x}",
current = segment_index + 1, current = segment_index + 1,
total = header.segments.len(), total = header.segments.len(),
size = encoded.size, size = encoded.size,
); ));
} }
} }
Ok(statistics) Ok(statistics)
@@ -2671,7 +2672,7 @@ pub fn restore_libil2cpp_with_limits(
{ {
let mut output = map_mut(temporary.as_file(), private_size, &temporary_path)?; let mut output = map_mut(temporary.as_file(), private_size, &temporary_path)?;
if options.verbose { if options.verbose {
eprintln!("Decoding primary 0x9D target-image container..."); crate::progress::stage(Step::AndroidPrimary);
} }
let mut writer = FileLayoutWriter { let mut writer = FileLayoutWriter {
output: &mut output, output: &mut output,
@@ -2711,7 +2712,7 @@ pub fn restore_libil2cpp_with_limits(
if !options.outer_only { if !options.outer_only {
if options.verbose { if options.verbose {
eprintln!("Decoding auxiliary 0x9D ELF materialization container..."); crate::progress::stage(Step::AndroidAuxiliary);
} }
let mut decoded = allocate_auxiliary(auxiliary_header.output_size, limits, &mut bytes)?; let mut decoded = allocate_auxiliary(auxiliary_header.output_size, limits, &mut bytes)?;
let auxiliary_len = decoded.len(); let auxiliary_len = decoded.len();
@@ -2771,7 +2772,7 @@ pub fn restore_libil2cpp_with_limits(
.set_len(mapping_bytes) .set_len(mapping_bytes)
.map_err(|error| Error::io("extend temporary output", &temporary_path, error))?; .map_err(|error| Error::io("extend temporary output", &temporary_path, error))?;
if options.verbose { if options.verbose {
eprintln!("Rebuilding static ELF dynamic-linker tables..."); crate::progress::stage(Step::AndroidTables);
} }
{ {
let mut output = map_mut(temporary.as_file(), mapping_length, &temporary_path)?; let mut output = map_mut(temporary.as_file(), mapping_length, &temporary_path)?;
+1
View File
@@ -4,6 +4,7 @@ pub mod android;
mod findings; mod findings;
mod panic_capture; mod panic_capture;
pub mod profile; pub mod profile;
pub mod progress;
mod threading; mod threading;
pub mod windows; pub mod windows;
+13 -12
View File
@@ -13,6 +13,7 @@
//! vendor version, or runtime-behaviour claim. A caller can serialize it as-is; //! vendor version, or runtime-behaviour claim. A caller can serialize it as-is;
//! the schema is versioned by [`PROFILE_FORMAT_VERSION`]. //! the schema is versioned by [`PROFILE_FORMAT_VERSION`].
use senbei_i18n::Message;
use serde::Serialize; use serde::Serialize;
use crate::windows::{IntegrityReport, IntegritySeverity, Kind}; use crate::windows::{IntegrityReport, IntegritySeverity, Kind};
@@ -180,8 +181,8 @@ impl ObservedTarget {
pub struct LayoutAttempt { pub struct LayoutAttempt {
pub layout: LayoutKind, pub layout: LayoutKind,
pub outcome: AttemptOutcome, pub outcome: AttemptOutcome,
pub warnings: Vec<String>, pub warnings: Vec<Message>,
pub errors: Vec<String>, pub errors: Vec<Message>,
} }
impl LayoutAttempt { impl LayoutAttempt {
@@ -211,10 +212,10 @@ pub struct ProtectionProfile {
/// The route whose output was accepted, when recovery succeeded. /// The route whose output was accepted, when recovery succeeded.
pub selected: Option<LayoutKind>, pub selected: Option<LayoutKind>,
/// Defects still present after the final validation. Empty when clean. /// Defects still present after the final validation. Empty when clean.
pub warnings: Vec<String>, pub warnings: Vec<Message>,
/// Unresolved failures: rejected/failed candidates when no route was /// Unresolved failures: rejected/failed candidates when no route was
/// accepted, or fatal findings on an accepted image. Empty when none. /// accepted, or fatal findings on an accepted image. Empty when none.
pub errors: Vec<String>, pub errors: Vec<Message>,
} }
impl ProtectionProfile { impl ProtectionProfile {
@@ -234,11 +235,11 @@ impl ProtectionProfile {
} }
} }
pub fn push_warning(&mut self, message: impl Into<String>) { pub fn push_warning(&mut self, message: impl Into<Message>) {
self.warnings.push(message.into()); self.warnings.push(message.into());
} }
pub fn push_error(&mut self, message: impl Into<String>) { pub fn push_error(&mut self, message: impl Into<Message>) {
self.errors.push(message.into()); self.errors.push(message.into());
} }
@@ -269,8 +270,8 @@ impl ProtectionProfile {
&mut self, &mut self,
layout: LayoutKind, layout: LayoutKind,
outcome: AttemptOutcome, outcome: AttemptOutcome,
warnings: Vec<String>, warnings: Vec<Message>,
errors: Vec<String>, errors: Vec<Message>,
) -> &mut LayoutAttempt { ) -> &mut LayoutAttempt {
if self.attempt_mut(layout).is_none() { if self.attempt_mut(layout).is_none() {
self.candidates.push(LayoutAttempt::not_attempted(layout)); self.candidates.push(LayoutAttempt::not_attempted(layout));
@@ -312,7 +313,7 @@ fn validation_status(report: &IntegrityReport) -> ValidationStatus {
} }
} }
fn messages(report: &IntegrityReport, severity: IntegritySeverity) -> Vec<String> { fn messages(report: &IntegrityReport, severity: IntegritySeverity) -> Vec<Message> {
report report
.findings .findings
.iter() .iter()
@@ -330,13 +331,13 @@ mod tests {
IntegrityReport { IntegrityReport {
issues: findings issues: findings
.iter() .iter()
.map(|(_, issue)| (*issue).to_owned()) .map(|(_, issue)| Message::raw(issue.to_string()))
.collect(), .collect(),
findings: findings findings: findings
.iter() .iter()
.map(|(severity, message)| IntegrityFinding { .map(|(severity, message)| IntegrityFinding {
severity: *severity, severity: *severity,
message: (*message).to_owned(), message: Message::raw(message.to_string()),
}) })
.collect(), .collect(),
} }
@@ -393,7 +394,7 @@ mod tests {
LayoutKind::Dll, LayoutKind::Dll,
AttemptOutcome::Rejected, AttemptOutcome::Rejected,
Vec::new(), Vec::new(),
vec!["bad".to_owned()], vec![Message::raw("bad")],
); );
profile.record_attempt( profile.record_attempt(
LayoutKind::ExeStyle, LayoutKind::ExeStyle,
+154
View File
@@ -0,0 +1,154 @@
//! Verbose progress from the recovery pipelines.
//!
//! With `verbose` on, a pipeline reports each step and its technical detail
//! lines here instead of printing them. A front end installs a sink for its
//! thread with [`with_sink`] and receives them as [`Event`]s. Without a sink
//! they print as they always have: Windows pipelines to stdout, the Android
//! pipeline to stderr, step titles in the process language
//! ([`senbei_i18n::current`]). Detail lines are technical and stay English.
use std::cell::RefCell;
use std::fmt;
use senbei_i18n::{Localize, Step};
/// One verbose progress event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
/// A pipeline step. `position` is `(n, total)` for the numbered Windows
/// steps and `None` for the Android stages.
Step {
step: Step,
position: Option<(u8, u8)>,
},
/// A technical detail line in English, with its leading indentation.
Detail(String),
}
type Sink = Box<dyn FnMut(&Event)>;
thread_local! {
static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
}
/// Send this thread's progress events to `sink` while `f` runs.
///
/// The previous sink, if any, is restored afterwards, also on panic.
/// Recovery runs on the calling thread, so events from parallel helpers are
/// never lost; the pipelines report only from the thread that called them.
pub fn with_sink<R>(sink: impl FnMut(&Event) + 'static, f: impl FnOnce() -> R) -> R {
struct Restore(Option<Sink>);
impl Drop for Restore {
fn drop(&mut self) {
let previous = self.0.take();
SINK.with(|slot| *slot.borrow_mut() = previous);
}
}
let previous = SINK.with(|slot| slot.borrow_mut().replace(Box::new(sink)));
let _restore = Restore(previous);
f()
}
/// Deliver `event` to this thread's sink. False when none is installed, in
/// which case the caller prints the line itself.
pub fn emit(event: &Event) -> bool {
SINK.with(|slot| match slot.borrow_mut().as_mut() {
Some(sink) => {
sink(event);
true
}
None => false,
})
}
/// A numbered Windows pipeline step.
pub(crate) fn step(n: u8, total: u8, step: Step) {
let event = Event::Step {
step,
position: Some((n, total)),
};
if !emit(&event)
&& let Event::Step { step, .. } = &event
{
println!("[{n}/{total}] {}", step.localize(senbei_i18n::current()));
}
}
/// A Windows detail line.
pub(crate) fn detail(args: fmt::Arguments<'_>) {
if !emit(&Event::Detail(args.to_string())) {
println!("{args}");
}
}
/// An Android pipeline stage.
pub(crate) fn stage(step: Step) {
let event = Event::Step {
step,
position: None,
};
if !emit(&event)
&& let Event::Step { step, .. } = &event
{
eprintln!("{}", step.localize(senbei_i18n::current()));
}
}
/// An Android detail line.
pub(crate) fn detail_err(args: fmt::Arguments<'_>) {
if !emit(&Event::Detail(args.to_string())) {
eprintln!("{args}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
#[test]
fn a_sink_receives_events_and_is_removed_afterwards() {
let seen = Arc::new(Mutex::new(Vec::new()));
let sink_seen = Arc::clone(&seen);
with_sink(
move |event| sink_seen.lock().unwrap().push(event.clone()),
|| {
step(1, 9, Step::DecryptHeader);
detail(format_args!(" info[0] key = 0x{:08X}", 0x1234));
stage(Step::AndroidPrimary);
},
);
assert_eq!(
*seen.lock().unwrap(),
[
Event::Step {
step: Step::DecryptHeader,
position: Some((1, 9)),
},
Event::Detail(" info[0] key = 0x00001234".to_owned()),
Event::Step {
step: Step::AndroidPrimary,
position: None,
},
]
);
assert!(!emit(&Event::Detail(String::new())));
}
#[test]
fn nested_sinks_restore_the_outer_one_even_after_a_panic() {
let outer = Arc::new(Mutex::new(0));
let counted = Arc::clone(&outer);
with_sink(
move |_| *counted.lock().unwrap() += 1,
|| {
let failed = std::panic::catch_unwind(|| {
with_sink(|_| {}, || panic!("synthetic unwind"));
});
assert!(failed.is_err());
detail(format_args!("after"));
},
);
assert_eq!(*outer.lock().unwrap(), 1);
}
}
+68 -34
View File
@@ -20,6 +20,7 @@ use super::super::{
}; };
use senbei_crypto::bytecode::{Op, OpsLut, generate}; use senbei_crypto::bytecode::{Op, OpsLut, generate};
use senbei_crypto::primitives::{self, *}; use senbei_crypto::primitives::{self, *};
use senbei_i18n::Step;
/// Per-code-block index for trace events. The four blocks share one research /// Per-code-block index for trace events. The four blocks share one research
/// stage, so an explicit index keeps their events orderable. /// stage, so an explicit index keeps their events orderable.
@@ -627,13 +628,31 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
); );
} }
if verbose { if verbose {
println!("[1/9] Initializing keys..."); crate::progress::step(1, 9, Step::InitKeys);
println!(" keys[0] key = 0x{:08X}", keys[0] as u32); crate::progress::detail(format_args!(
println!(" keys[1] signature = 0x{:08X}", keys[1] as u32); " keys[0] key = 0x{:08X}",
println!(" keys[3] base = 0x{:08X}", keys[3] as u32); keys[0] as u32
println!(" keys[4] src_off = 0x{:08X}", keys[4] as u32); ));
println!(" keys[5] size = 0x{:08X}", keys[5] as u32); crate::progress::detail(format_args!(
println!(" keys[6] anchor = 0x{:08X}", keys[6] as u32); " keys[1] signature = 0x{:08X}",
keys[1] as u32
));
crate::progress::detail(format_args!(
" keys[3] base = 0x{:08X}",
keys[3] as u32
));
crate::progress::detail(format_args!(
" keys[4] src_off = 0x{:08X}",
keys[4] as u32
));
crate::progress::detail(format_args!(
" keys[5] size = 0x{:08X}",
keys[5] as u32
));
crate::progress::detail(format_args!(
" keys[6] anchor = 0x{:08X}",
keys[6] as u32
));
} }
if !super::super::is_supported_magic(keys[1] as u32) { if !super::super::is_supported_magic(keys[1] as u32) {
@@ -706,9 +725,15 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
); );
} }
if verbose { if verbose {
println!("[2/9] Decrypting key table..."); crate::progress::step(2, 9, Step::DecryptKeyTable);
println!(" size_of_image = 0x{:08X}", size_of_image as u32); crate::progress::detail(format_args!(
println!(" base_offset = 0x{:08X}", base_offset as u32); " size_of_image = 0x{:08X}",
size_of_image as u32
));
crate::progress::detail(format_args!(
" base_offset = 0x{:08X}",
base_offset as u32
));
} }
// DecryptKeyTable. // DecryptKeyTable.
@@ -805,10 +830,19 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
research::emit_u32(ResearchStage::DllStages, "descriptor_shift", 21); research::emit_u32(ResearchStage::DllStages, "descriptor_shift", 21);
} }
if verbose { if verbose {
println!("[3/9] Decrypting primary descriptor..."); crate::progress::step(3, 9, Step::DecryptPrimary);
println!(" xor_accumulator = 0x{:08X}", xor_accumulator); crate::progress::detail(format_args!(
println!(" checksum1 = 0x{:08X}", checksum1 as u32); " xor_accumulator = 0x{:08X}",
println!(" decrypted_addr1 = 0x{:08X}", decrypted_addr1 as u32); xor_accumulator
));
crate::progress::detail(format_args!(
" checksum1 = 0x{:08X}",
checksum1 as u32
));
crate::progress::detail(format_args!(
" decrypted_addr1 = 0x{:08X}",
decrypted_addr1 as u32
));
} }
let primary_end = decrypted_addr1.checked_add(3856); let primary_end = decrypted_addr1.checked_add(3856);
if decrypted_addr1 < keys[3] if decrypted_addr1 < keys[3]
@@ -939,15 +973,15 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
); );
} }
if verbose { if verbose {
println!("[4/9] Processing relocations & decomp params..."); crate::progress::step(4, 9, Step::RelocsParams);
println!(" addr2 = 0x{:08X}", addr2 as u32); crate::progress::detail(format_args!(" addr2 = 0x{:08X}", addr2 as u32));
println!( crate::progress::detail(format_args!(
" decomp_params = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]", " decomp_params = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]",
decomp_params[0] as u32, decomp_params[0] as u32,
decomp_params[1] as u32, decomp_params[1] as u32,
decomp_params[2] as u32, decomp_params[2] as u32,
decomp_params[3] as u32 decomp_params[3] as u32
); ));
} }
let checksum2 = calculate_checksum(&out, (keys[6] + 5640) as u32) as i32; let checksum2 = calculate_checksum(&out, (keys[6] + 5640) as u32) as i32;
@@ -981,9 +1015,9 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
let addr3b = get_i32(&out, decrypted_addr1 + 3728); let addr3b = get_i32(&out, decrypted_addr1 + 3728);
if verbose { if verbose {
println!("[5/9] Decrypting code block 1 (addr3)..."); crate::progress::step(5, 9, Step::DecryptBlock1);
println!(" checksum2 = 0x{:08X}", checksum2 as u32); crate::progress::detail(format_args!(" checksum2 = 0x{:08X}", checksum2 as u32));
println!(" addr3b = 0x{:08X}", addr3b as u32); crate::progress::detail(format_args!(" addr3b = 0x{:08X}", addr3b as u32));
} }
let crc_data_offset = decrypted_addr1 + 3488; let crc_data_offset = decrypted_addr1 + 3488;
@@ -1046,10 +1080,10 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
research::emit_u32(ResearchStage::DllStages, "crc_val", crc_val as u32); research::emit_u32(ResearchStage::DllStages, "crc_val", crc_val as u32);
research::emit_u32(ResearchStage::DllStages, "checksum3", checksum3 as u32); research::emit_u32(ResearchStage::DllStages, "checksum3", checksum3 as u32);
if verbose { if verbose {
println!("[6/9] Decrypting code blocks 2-3 (addr3b, addr4)..."); crate::progress::step(6, 9, Step::DecryptBlocks2To3);
println!(" crc_val = 0x{:08X}", crc_val as u32); crate::progress::detail(format_args!(" crc_val = 0x{:08X}", crc_val as u32));
println!(" checksum3 = 0x{:08X}", checksum3 as u32); crate::progress::detail(format_args!(" checksum3 = 0x{:08X}", checksum3 as u32));
println!(" addr4 = 0x{:08X}", addr4 as u32); crate::progress::detail(format_args!(" addr4 = 0x{:08X}", addr4 as u32));
} }
let checksum4 = calculate_checksum(&out, (decrypted_addr1 + 3472) as u32) as i32; let checksum4 = calculate_checksum(&out, (decrypted_addr1 + 3472) as u32) as i32;
@@ -1108,9 +1142,9 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
DecompressionStage::DllCodeBlock4, DecompressionStage::DllCodeBlock4,
)?; )?;
if verbose { if verbose {
println!("[7/9] Decrypting code block 4 (addr5)..."); crate::progress::step(7, 9, Step::DecryptBlock4);
println!(" checksum4 = 0x{:08X}", checksum4 as u32); crate::progress::detail(format_args!(" checksum4 = 0x{:08X}", checksum4 as u32));
println!(" addr5 = 0x{:08X}", addr5 as u32); crate::progress::detail(format_args!(" addr5 = 0x{:08X}", addr5 as u32));
} }
let metadata_offset = addr5 + 12312; let metadata_offset = addr5 + 12312;
@@ -1188,15 +1222,15 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
trace_offset(section_image_base), trace_offset(section_image_base),
); );
if verbose { if verbose {
println!("[8/9] Decrypting & decompressing sections..."); crate::progress::step(8, 9, Step::DllSections);
println!( crate::progress::detail(format_args!(
" section_image_base = 0x{:08X}", " section_image_base = 0x{:08X}",
section_image_base as u32 section_image_base as u32
); ));
println!( crate::progress::detail(format_args!(
" section_data_offset = 0x{:08X}", " section_data_offset = 0x{:08X}",
section_data_offset as u32 section_data_offset as u32
); ));
} }
// Managed-only pre-fill of .text (Task 3.2). No-op for native (clr_rva == 0). // Managed-only pre-fill of .text (Task 3.2). No-op for native (clr_rva == 0).
@@ -1278,7 +1312,7 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
out[..4096].copy_from_slice(&file_data[..4096]); out[..4096].copy_from_slice(&file_data[..4096]);
if verbose { if verbose {
println!("[9/9] Fixing up PE header & section table..."); crate::progress::step(9, 9, Step::FixHeaders);
} }
let section_header_base = get_u16(file_data, (pe_offset + 20) as u32) as i32 + pe_offset; let section_header_base = get_u16(file_data, (pe_offset + 20) as u32) as i32 + pe_offset;
+41 -1
View File
@@ -1,4 +1,5 @@
pub use senbei_crypto::{BufferOperation, DecompressionFailure}; pub use senbei_crypto::{BufferOperation, DecompressionFailure};
use senbei_i18n::{Message, Msg};
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecompressionStage { pub enum DecompressionStage {
@@ -225,7 +226,7 @@ pub enum UnpackError {
}, },
#[error("structurally invalid layout candidate: {}", issues.join("; "))] #[error("structurally invalid layout candidate: {}", issues.join("; "))]
InvalidLayoutCandidate { issues: Vec<String> }, InvalidLayoutCandidate { issues: Vec<Message> },
#[error( #[error(
"PE32 second-stage range is invalid (offset {offset}, size {size}, image length {image_len})" "PE32 second-stage range is invalid (offset {offset}, size {size}, image length {image_len})"
@@ -254,6 +255,45 @@ pub enum UnpackError {
}, },
} }
impl UnpackError {
/// This error as a report message: the English it displays, with the
/// catalog entry a front end translates.
///
/// Errors a user can act on have their own entry. Internal decode
/// failures share one summary entry and keep their specific English as
/// the recorded text.
pub fn message(&self) -> Message {
let msg = match self {
Self::CompanionMissing => Msg::CompanionMissing,
Self::CompanionMismatch => Msg::CompanionMismatch,
Self::InputTooShort { actual, required } => Msg::InputTooShort {
actual: *actual,
required: *required,
},
Self::NotCrackProof => Msg::NotProtected,
Self::InvalidPeOffset { offset, input_len } => Msg::InvalidPeOffset {
offset: *offset,
input_len: *input_len,
},
Self::UnsupportedDllPeMagic { found } => Msg::DllNeedsPe32Plus { found: *found },
Self::Stage5MarkerNotFound => Msg::LayoutUnsupported,
Self::InternalPanic {
message,
file,
line,
column,
} => Msg::InternalPanic {
file: file.clone(),
line: *line,
column: *column,
message: message.clone(),
},
_ => Msg::DecodeFailed,
};
Message::with_text(msg, self.to_string())
}
}
impl From<senbei_crypto::Error> for UnpackError { impl From<senbei_crypto::Error> for UnpackError {
fn from(error: senbei_crypto::Error) -> Self { fn from(error: senbei_crypto::Error) -> Self {
match error { match error {
+71 -54
View File
@@ -1,6 +1,7 @@
use senbei_crypto::bytecode::{Op, OpsLut, generate}; use senbei_crypto::bytecode::{Op, OpsLut, generate};
use senbei_crypto::primitives; use senbei_crypto::primitives;
use senbei_crypto::primitives::*; use senbei_crypto::primitives::*;
use senbei_i18n::Step;
use super::super::error::*; use super::super::error::*;
use super::super::layout::{self, *}; use super::super::layout::{self, *};
@@ -362,15 +363,15 @@ impl<'a> Unpacker<'a> {
0x1004, 0x1004,
); );
if verbose { if verbose {
println!("[1/9] Decrypting file header..."); crate::progress::step(1, 9, Step::DecryptHeader);
println!(" info[0] key = 0x{:08X}", u.info[0]); crate::progress::detail(format_args!(" info[0] key = 0x{:08X}", u.info[0]));
println!(" info[1] signature = 0x{:08X}", u.info[1]); crate::progress::detail(format_args!(" info[1] signature = 0x{:08X}", u.info[1]));
println!(" info[2] = 0x{:08X}", u.info[2]); crate::progress::detail(format_args!(" info[2] = 0x{:08X}", u.info[2]));
println!(" info[3] base = 0x{:08X}", u.info[3]); crate::progress::detail(format_args!(" info[3] base = 0x{:08X}", u.info[3]));
println!(" info[4] src_off = 0x{:08X}", u.info[4]); crate::progress::detail(format_args!(" info[4] src_off = 0x{:08X}", u.info[4]));
println!(" info[5] total_size = 0x{:08X}", u.info[5]); crate::progress::detail(format_args!(" info[5] total_size = 0x{:08X}", u.info[5]));
println!(" info[6] end_mark = 0x{:08X}", u.info[6]); crate::progress::detail(format_args!(" info[6] end_mark = 0x{:08X}", u.info[6]));
println!(" info[7] = 0x{:08X}", u.info[7]); crate::progress::detail(format_args!(" info[7] = 0x{:08X}", u.info[7]));
} }
if !super::super::is_supported_magic(u.info[1]) { if !super::super::is_supported_magic(u.info[1]) {
return Err(UnpackError::HeaderMagicMismatch { found: u.info[1] }); return Err(UnpackError::HeaderMagicMismatch { found: u.info[1] });
@@ -409,7 +410,7 @@ impl<'a> Unpacker<'a> {
u.info[5] as u64, u.info[5] as u64,
); );
if verbose { if verbose {
println!("[2/9] Decrypting payload..."); crate::progress::step(2, 9, Step::DecryptPayload);
} }
let pe32_table = u.load_payload(); let pe32_table = u.load_payload();
research::emit_u32(ResearchStage::Payload, "prefix_length", u.decrypt_size); research::emit_u32(ResearchStage::Payload, "prefix_length", u.decrypt_size);
@@ -505,8 +506,8 @@ impl<'a> Unpacker<'a> {
); );
if verbose { if verbose {
println!(" anchor = 0x{anchor:08X}"); crate::progress::detail(format_args!(" anchor = 0x{anchor:08X}"));
println!(" anchor layout offset = +0x{anchor_extra:X}"); crate::progress::detail(format_args!(" anchor layout offset = +0x{anchor_extra:X}"));
} }
let p1 = get_u32(&u.decompressed, anchor.wrapping_add(8)); let p1 = get_u32(&u.decompressed, anchor.wrapping_add(8));
@@ -555,14 +556,16 @@ impl<'a> Unpacker<'a> {
stage1_descriptor.to_vec(), stage1_descriptor.to_vec(),
); );
if verbose { if verbose {
println!("[3/9] Locating config layout..."); crate::progress::step(3, 9, Step::LocateConfig);
println!(" stage1 = 0x{:08X}", stage1); crate::progress::detail(format_args!(" stage1 = 0x{:08X}", stage1));
println!(" stage1_len = 0x{stage1_len:08X}"); crate::progress::detail(format_args!(" stage1_len = 0x{stage1_len:08X}"));
println!( crate::progress::detail(format_args!(
" stage1 descriptor = [0x{:08X}, 0x{:08X}]", " stage1 descriptor = [0x{:08X}, 0x{:08X}]",
stage1_descriptor[0], stage1_descriptor[1] stage1_descriptor[0], stage1_descriptor[1]
); ));
println!(" stage1 key = xor 0x{xor_acc:08X} ^ chk 0x{chk1:08X} ^ val 0x{v:08X}"); crate::progress::detail(format_args!(
" stage1 key = xor 0x{xor_acc:08X} ^ chk 0x{chk1:08X} ^ val 0x{v:08X}"
));
} }
// Field offsets inside stage1 vary between CrackProof versions. Locate // Field offsets inside stage1 vary between CrackProof versions. Locate
@@ -653,11 +656,13 @@ impl<'a> Unpacker<'a> {
chk_src_start, chk_src_start,
); );
if verbose { if verbose {
println!("[4/9] Decrypting stage2..."); crate::progress::step(4, 9, Step::DecryptStage2);
println!(" stage2 = 0x{:08X}", stage2); crate::progress::detail(format_args!(" stage2 = 0x{:08X}", stage2));
println!(" stage2_off = 0x{stage2_off:04X}"); crate::progress::detail(format_args!(" stage2_off = 0x{stage2_off:04X}"));
println!(" checksum table = stage1+0x{chk_src_start:04X}"); crate::progress::detail(format_args!(
println!(" stage2 key = 0x{key2:08X}"); " checksum table = stage1+0x{chk_src_start:04X}"
));
crate::progress::detail(format_args!(" stage2 key = 0x{key2:08X}"));
} }
// The stage2 head/walk2 tables shift between CrackProof versions. The 4-entry // The stage2 head/walk2 tables shift between CrackProof versions. The 4-entry
@@ -690,17 +695,21 @@ impl<'a> Unpacker<'a> {
let head_off = table_start.wrapping_add(32); let head_off = table_start.wrapping_add(32);
let walk2_off = head_off.wrapping_sub(88); let walk2_off = head_off.wrapping_sub(88);
if verbose { if verbose {
println!(" operation table = stage2+0x{table_start:04X}"); crate::progress::detail(format_args!(
println!(" head/walk = +0x{head_off:04X}/+0x{walk2_off:04X}"); " operation table = stage2+0x{table_start:04X}"
));
crate::progress::detail(format_args!(
" head/walk = +0x{head_off:04X}/+0x{walk2_off:04X}"
));
for index in 0..2u32 { for index in 0..2u32 {
let entry = stage2.wrapping_add(head_off + index * 16); let entry = stage2.wrapping_add(head_off + index * 16);
println!( crate::progress::detail(format_args!(
" operation[{index}] = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]", " operation[{index}] = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]",
get_u32(&u.decompressed, entry), get_u32(&u.decompressed, entry),
get_u32(&u.decompressed, entry.wrapping_add(4)), get_u32(&u.decompressed, entry.wrapping_add(4)),
get_u32(&u.decompressed, entry.wrapping_add(8)), get_u32(&u.decompressed, entry.wrapping_add(8)),
get_u32(&u.decompressed, entry.wrapping_add(12)), get_u32(&u.decompressed, entry.wrapping_add(12)),
); ));
} }
} }
@@ -751,10 +760,10 @@ impl<'a> Unpacker<'a> {
u.key_offsets.to_vec(), u.key_offsets.to_vec(),
); );
if verbose { if verbose {
println!( crate::progress::detail(format_args!(
" key offsets = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]", " key offsets = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]",
u.key_offsets[0], u.key_offsets[1], u.key_offsets[2], u.key_offsets[3] u.key_offsets[0], u.key_offsets[1], u.key_offsets[2], u.key_offsets[3]
); ));
} }
let chk2 = u.calculate_checksum(anchor.wrapping_add(48 + anchor_extra)); let chk2 = u.calculate_checksum(anchor.wrapping_add(48 + anchor_extra));
@@ -779,13 +788,15 @@ impl<'a> Unpacker<'a> {
let stage3_dest = get_u32(&u.decompressed, at1.wrapping_add(8)); let stage3_dest = get_u32(&u.decompressed, at1.wrapping_add(8));
let stage3_dlen = get_u32(&u.decompressed, at1.wrapping_add(12)); let stage3_dlen = get_u32(&u.decompressed, at1.wrapping_add(12));
if verbose { if verbose {
println!("[5/9] Decrypting stages 3-5..."); crate::progress::step(5, 9, Step::DecryptStages3To5);
println!(" stage3 = 0x{:08X}", stage3_field); crate::progress::detail(format_args!(" stage3 = 0x{:08X}", stage3_field));
println!( crate::progress::detail(format_args!(
" stage3 descriptor = [0x{stage3_field:08X}, 0x{stage3_slen:08X}, 0x{stage3_dest:08X}, 0x{stage3_dlen:08X}]" " stage3 descriptor = [0x{stage3_field:08X}, 0x{stage3_slen:08X}, 0x{stage3_dest:08X}, 0x{stage3_dlen:08X}]"
); ));
println!(" stage3 key = xor 0x{xor_acc:08X} ^ chk 0x{chk2:08X} ^ val 0x{accum:08X}"); crate::progress::detail(format_args!(
println!(" stage3 accum seed = 0x{accum_seed:08X}"); " stage3 key = xor 0x{xor_acc:08X} ^ chk 0x{chk2:08X} ^ val 0x{accum:08X}"
));
crate::progress::detail(format_args!(" stage3 accum seed = 0x{accum_seed:08X}"));
} }
let stage3_key = xor_acc ^ chk2 ^ accum; let stage3_key = xor_acc ^ chk2 ^ accum;
research::emit_range( research::emit_range(
@@ -858,7 +869,9 @@ impl<'a> Unpacker<'a> {
rounds, rounds,
); );
if verbose { if verbose {
println!(" selected stage3 accumulator rounds = {rounds}"); crate::progress::detail(format_args!(
" selected stage3 accumulator rounds = {rounds}"
));
} }
} else { } else {
restore_stage3(&mut u.decompressed); restore_stage3(&mut u.decompressed);
@@ -873,7 +886,7 @@ impl<'a> Unpacker<'a> {
let stage3b_field = get_u32(&u.decompressed, at2); let stage3b_field = get_u32(&u.decompressed, at2);
let stage3b_dlen = get_u32(&u.decompressed, at2.wrapping_add(12)); let stage3b_dlen = get_u32(&u.decompressed, at2.wrapping_add(12));
if verbose { if verbose {
println!(" stage3b = 0x{:08X}", stage3b_field); crate::progress::detail(format_args!(" stage3b = 0x{:08X}", stage3b_field));
} }
let chk3 = u.calculate_checksum(stage1.wrapping_add(chk_src_start.wrapping_add(24))); let chk3 = u.calculate_checksum(stage1.wrapping_add(chk_src_start.wrapping_add(24)));
// v4_val lives at the end of stage3, immediately following `C3 CC CC CC` // v4_val lives at the end of stage3, immediately following `C3 CC CC CC`
@@ -903,7 +916,7 @@ impl<'a> Unpacker<'a> {
let stage4_field = get_u32(&u.decompressed, at3); let stage4_field = get_u32(&u.decompressed, at3);
let stage4_dlen = get_u32(&u.decompressed, at3.wrapping_add(12)); let stage4_dlen = get_u32(&u.decompressed, at3.wrapping_add(12));
if verbose { if verbose {
println!(" stage4 = 0x{:08X}", stage4_field); crate::progress::detail(format_args!(" stage4 = 0x{:08X}", stage4_field));
} }
if let Err(reason) = u.decrypt_and_decompress_data(at3, xor_acc ^ chk4 ^ v5_val, None) { if let Err(reason) = u.decrypt_and_decompress_data(at3, xor_acc ^ chk4 ^ v5_val, None) {
return Err(UnpackError::StageDecompressionFailed { return Err(UnpackError::StageDecompressionFailed {
@@ -988,12 +1001,14 @@ impl<'a> Unpacker<'a> {
let stage5_dest = get_u32(&u.decompressed, at4.wrapping_add(8)); let stage5_dest = get_u32(&u.decompressed, at4.wrapping_add(8));
let stage5_dlen = get_u32(&u.decompressed, at4.wrapping_add(12)); let stage5_dlen = get_u32(&u.decompressed, at4.wrapping_add(12));
if verbose { if verbose {
println!(" stage5 = 0x{:08X}", stage5_field); crate::progress::detail(format_args!(" stage5 = 0x{:08X}", stage5_field));
println!( crate::progress::detail(format_args!(
" stage5 descriptor = [0x{stage5_field:08X}, 0x{stage5_slen:08X}, 0x{stage5_dest:08X}, 0x{stage5_dlen:08X}]" " stage5 descriptor = [0x{stage5_field:08X}, 0x{stage5_slen:08X}, 0x{stage5_dest:08X}, 0x{stage5_dlen:08X}]"
); ));
println!(" stage5 bytecode = 0x{data_offset:08X}"); crate::progress::detail(format_args!(" stage5 bytecode = 0x{data_offset:08X}"));
println!(" stage5 accumulator seed = 0x{accum2_seed:08X} at 0x{v6:08X}"); crate::progress::detail(format_args!(
" stage5 accumulator seed = 0x{accum2_seed:08X} at 0x{v6:08X}"
));
} }
let stage5_lo = stage5_field.min(stage5_dest) as usize; let stage5_lo = stage5_field.min(stage5_dest) as usize;
let stage5_hi = stage5_field let stage5_hi = stage5_field
@@ -1047,7 +1062,9 @@ impl<'a> Unpacker<'a> {
stage5_dlen as u64, stage5_dlen as u64,
); );
if verbose { if verbose {
println!(" selected stage5 accumulator rounds = {selected_rounds}"); crate::progress::detail(format_args!(
" selected stage5 accumulator rounds = {selected_rounds}"
));
} }
// Inside stage5, the loader stores a table of (ptr, size) pairs at a // Inside stage5, the loader stores a table of (ptr, size) pairs at a
@@ -1185,10 +1202,10 @@ impl<'a> Unpacker<'a> {
Ok(next) => chain_crc = next, Ok(next) => chain_crc = next,
Err(UnpackError::ExeChecksumRangeOutOfBounds { .. }) => { Err(UnpackError::ExeChecksumRangeOutOfBounds { .. }) => {
if verbose { if verbose {
println!( crate::progress::detail(format_args!(
" checksum chain terminates at 0x{:08X}: descriptor payload is outside protected input", " checksum chain terminates at 0x{:08X}: descriptor payload is outside protected input",
walk3.wrapping_sub(16) walk3.wrapping_sub(16)
); ));
} }
break; break;
} }
@@ -1200,18 +1217,18 @@ impl<'a> Unpacker<'a> {
} }
} }
if verbose { if verbose {
println!("[6/9] Decrypting section data..."); crate::progress::step(6, 9, Step::DecryptSections);
println!( crate::progress::detail(format_args!(
" integrity = 0x{:08X}", " integrity = 0x{:08X}",
get_u32(u.file_data, 56).wrapping_add(1985229329) get_u32(u.file_data, 56).wrapping_add(1985229329)
); ));
println!(" chain_crc = 0x{:08X}", chain_crc); crate::progress::detail(format_args!(" chain_crc = 0x{:08X}", chain_crc));
} }
for (addr, bytes) in walk3_backups { for (addr, bytes) in walk3_backups {
u.decompressed[addr..addr + 16].copy_from_slice(&bytes); u.decompressed[addr..addr + 16].copy_from_slice(&bytes);
} }
} else if verbose { } else if verbose {
println!("[6/9] Decrypting section data (new layout)..."); crate::progress::step(6, 9, Step::DecryptSectionsNewLayout);
} }
let data_offset2 = bc2_off; let data_offset2 = bc2_off;
@@ -1255,7 +1272,7 @@ impl<'a> Unpacker<'a> {
let at6 = walk4_slot; let at6 = walk4_slot;
if verbose { if verbose {
println!("[7/9] Loading and decompressing sections..."); crate::progress::step(7, 9, Step::LoadSections);
} }
let mut walk4 = get_u32(&u.decompressed, at6); let mut walk4 = get_u32(&u.decompressed, at6);
// Pass 1 (sequential): the 16-byte descriptors are decrypted in a // Pass 1 (sequential): the 16-byte descriptors are decrypted in a
@@ -1402,7 +1419,7 @@ impl<'a> Unpacker<'a> {
let at7 = walk5_slot; let at7 = walk5_slot;
if verbose { if verbose {
println!("[8/9] Decrypting import strings..."); crate::progress::step(8, 9, Step::DecryptImports);
} }
// walk5 is the old layout's encrypted import-name pointer table. The new // walk5 is the old layout's encrypted import-name pointer table. The new
// layout has no such table — imports are rebuilt from the PE Import // layout has no such table — imports are rebuilt from the PE Import
@@ -1464,7 +1481,7 @@ impl<'a> Unpacker<'a> {
} // end !new_layout (walk5) } // end !new_layout (walk5)
if verbose { if verbose {
println!("[9/9] Reconstructing PE headers..."); crate::progress::step(9, 9, Step::RebuildHeaders);
} }
u.decompressed[..4096].copy_from_slice(&u.file_data[..4096]); u.decompressed[..4096].copy_from_slice(&u.file_data[..4096]);
let opt_hdr_size = get_u16(u.file_data, pe_off.wrapping_add(20)); let opt_hdr_size = get_u16(u.file_data, pe_off.wrapping_add(20));
+37 -26
View File
@@ -1,6 +1,7 @@
use super::super::super::layout; use super::super::super::layout;
use super::super::super::research::{self, AddressSpace, ResearchStage}; use super::super::super::research::{self, AddressSpace, ResearchStage};
use super::*; use super::*;
use senbei_i18n::Step;
/// Name of the dd8 formula the PE32 selector actually chose. `None` is the /// Name of the dd8 formula the PE32 selector actually chose. `None` is the
/// selector's skip verdict, not "did not run". /// selector's skip verdict, not "did not run".
@@ -209,8 +210,8 @@ impl<'a> Unpacker<'a> {
tbl as u64, tbl as u64,
); );
if verbose { if verbose {
println!("[3/9] Locating config layout (PE32)..."); crate::progress::step(3, 9, Step::Pe32LocateConfig);
println!(" tbl = 0x{:X}, compact = {}", tbl, compact); crate::progress::detail(format_args!(" tbl = 0x{:X}, compact = {}", tbl, compact));
} }
// ---- Stage 3: SecondStage ---- // ---- Stage 3: SecondStage ----
@@ -234,10 +235,10 @@ impl<'a> Unpacker<'a> {
header_checksum, header_checksum,
); );
if verbose { if verbose {
println!( crate::progress::detail(format_args!(
" ss = 0x{:08X}, size = 0x{:X}, shift = 0x{:X}", " ss = 0x{:08X}, size = 0x{:X}, shift = 0x{:X}",
ss, ss_size, ss_shift ss, ss_size, ss_shift
); ));
} }
// ---- PE32 fixed offsets ---- // ---- PE32 fixed offsets ----
@@ -304,11 +305,11 @@ impl<'a> Unpacker<'a> {
info_table as u64, info_table as u64,
); );
if verbose { if verbose {
println!("[4/9] Decrypting stages (PE32)..."); crate::progress::step(4, 9, Step::Pe32Stages);
println!( crate::progress::detail(format_args!(
" thirdStage start = 0x{:X}, infoTable = 0x{:X}", " thirdStage start = 0x{:X}, infoTable = 0x{:X}",
ts, info_table ts, info_table
); ));
} }
// ---- Process infoTable ---- // ---- Process infoTable ----
@@ -372,7 +373,9 @@ impl<'a> Unpacker<'a> {
forth_key_rounds, forth_key_rounds,
); );
if verbose { if verbose {
println!(" fourth-stage key rounds = {forth_key_rounds}"); crate::progress::detail(format_args!(
" fourth-stage key rounds = {forth_key_rounds}"
));
} }
let forth_addr = dp_base.wrapping_add(0x40); let forth_addr = dp_base.wrapping_add(0x40);
let fk = header_checksum ^ second_stage_cs ^ forth_stage_key; let fk = header_checksum ^ second_stage_cs ^ forth_stage_key;
@@ -433,11 +436,11 @@ impl<'a> Unpacker<'a> {
// ---- EighthStage ---- // ---- EighthStage ----
let seven_start_actual = get_u32(&self.decompressed, seven_addr); let seven_start_actual = get_u32(&self.decompressed, seven_addr);
if verbose { if verbose {
println!("[5/9] Decrypting eighthStage (PE32)..."); crate::progress::step(5, 9, Step::Pe32EighthStage);
println!( crate::progress::detail(format_args!(
" sevenStart = 0x{:X}, sevenDsz = 0x{:X}", " sevenStart = 0x{:X}, sevenDsz = 0x{:X}",
seven_start_actual, seven_dsz seven_start_actual, seven_dsz
); ));
} }
// Locate the customDecryptor LFSR block (scan backward from middle, then // Locate the customDecryptor LFSR block (scan backward from middle, then
// forward as fallback). // forward as fallback).
@@ -470,7 +473,9 @@ impl<'a> Unpacker<'a> {
let eighth_key_rounds = let eighth_key_rounds =
stage_key_rounds(&self.decompressed, dp_base.wrapping_add(0x80), 4)?; stage_key_rounds(&self.decompressed, dp_base.wrapping_add(0x80), 4)?;
if verbose { if verbose {
println!(" eighth-stage key rounds = {eighth_key_rounds}"); crate::progress::detail(format_args!(
" eighth-stage key rounds = {eighth_key_rounds}"
));
} }
let eighth_addr = dp_base.wrapping_add(0xC0); let eighth_addr = dp_base.wrapping_add(0xC0);
let eighth_dsz = get_u32(&self.decompressed, eighth_addr.wrapping_add(12)); let eighth_dsz = get_u32(&self.decompressed, eighth_addr.wrapping_add(12));
@@ -568,10 +573,10 @@ impl<'a> Unpacker<'a> {
); );
let eighth_start = get_u32(&self.decompressed, eighth_addr); let eighth_start = get_u32(&self.decompressed, eighth_addr);
if verbose { if verbose {
println!( crate::progress::detail(format_args!(
" eighthStart = 0x{:08X}, dsz = 0x{:X}", " eighthStart = 0x{:08X}, dsz = 0x{:X}",
eighth_start, eighth_dsz eighth_start, eighth_dsz
); ));
} }
// ---- Final processing offsets (anchored on the eighthStage config cluster) ---- // ---- Final processing offsets (anchored on the eighthStage config cluster) ----
@@ -637,10 +642,10 @@ impl<'a> Unpacker<'a> {
} }
if let Some((dist, base)) = best { if let Some((dist, base)) = best {
if verbose { if verbose {
println!( crate::progress::detail(format_args!(
" pe32 cluster via fileCS (no 0x7679): base=+0x{:X} dist_info3=0x{:X}", " pe32 cluster via fileCS (no 0x7679): base=+0x{:X} dist_info3=0x{:X}",
base, dist base, dist
); ));
} }
m = Some(base); m = Some(base);
} }
@@ -723,10 +728,10 @@ impl<'a> Unpacker<'a> {
} }
if let Some(c) = chosen { if let Some(c) = chosen {
if verbose { if verbose {
println!( crate::progress::detail(format_args!(
" pe32 fileLFSR via trial-validate: +0x{:X} (expected +0x{:X}, considered {})", " pe32 fileLFSR via trial-validate: +0x{:X} (expected +0x{:X}, considered {})",
c, off_file_lfsr, considered c, off_file_lfsr, considered
); ));
} }
lfsr_off = c; lfsr_off = c;
} else { } else {
@@ -818,7 +823,7 @@ impl<'a> Unpacker<'a> {
// ---- File data decompression ---- // ---- File data decompression ----
if verbose { if verbose {
println!("[6/9] Loading and decompressing file data (PE32)..."); crate::progress::step(6, 9, Step::Pe32Load);
} }
let compress_data_offset = (!get_u32(self.file_data, 0x1080)).wrapping_add(0x1000); let compress_data_offset = (!get_u32(self.file_data, 0x1080)).wrapping_add(0x1000);
let compressed_info_addr = eighth_start.wrapping_add(off_compressed_info); let compressed_info_addr = eighth_start.wrapping_add(off_compressed_info);
@@ -1026,9 +1031,12 @@ impl<'a> Unpacker<'a> {
); );
if let Some(big) = selection { if let Some(big) = selection {
if verbose { if verbose {
println!( crate::progress::step(
"[7/9] Decrypting .text (PE32 dd8, formula={})...", 7,
if big { "0x8000*(page+1)" } else { "page+1" } 9,
Step::Pe32Text {
formula: if big { "0x8000*(page+1)" } else { "page+1" },
},
); );
} }
research::emit_text( research::emit_text(
@@ -1070,7 +1078,7 @@ impl<'a> Unpacker<'a> {
} }
} }
} else if verbose { } else if verbose {
println!("[7/9] Skipping .text dd8 (already plaintext)..."); crate::progress::step(7, 9, Step::Pe32TextSkip);
} }
} }
@@ -1249,14 +1257,17 @@ impl<'a> Unpacker<'a> {
block = block.wrapping_add(block_size); block = block.wrapping_add(block_size);
} }
if verbose && rearmed > 0 { if verbose && rearmed > 0 {
println!(" re-armed {} TLS field relocations", rearmed); crate::progress::detail(format_args!(
" re-armed {} TLS field relocations",
rearmed
));
} }
} }
} }
// ---- Import table (PE32, 4-byte thunks) ---- // ---- Import table (PE32, 4-byte thunks) ----
if verbose { if verbose {
println!("[8/9] Decrypting import strings (PE32)..."); crate::progress::step(8, 9, Step::Pe32Imports);
} }
let import_table_addr = eighth_start.wrapping_add(off_import_table); let import_table_addr = eighth_start.wrapping_add(off_import_table);
let mut import_table_ptr = get_u32(&self.decompressed, import_table_addr); let mut import_table_ptr = get_u32(&self.decompressed, import_table_addr);
@@ -1361,7 +1372,7 @@ impl<'a> Unpacker<'a> {
// ---- Output transforms ---- // ---- Output transforms ----
if verbose { if verbose {
println!("[9/9] Rebuilding PE file layout (PE32)..."); crate::progress::step(9, 9, Step::Pe32Rebuild);
} }
let mut out = std::mem::take(&mut self.decompressed); let mut out = std::mem::take(&mut self.decompressed);
// kmiat import relocation is an EXE-only fixup: it discards the original // kmiat import relocation is an EXE-only fixup: it discards the original
+49 -66
View File
@@ -18,6 +18,8 @@
//! //!
//! All reads are bounds-checked; the check never panics on any input. //! All reads are bounds-checked; the check never panics on any input.
use senbei_i18n::{Message, Msg};
mod clr; mod clr;
mod directories; mod directories;
@@ -48,7 +50,7 @@ pub enum IntegritySeverity {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct IntegrityFinding { pub struct IntegrityFinding {
pub severity: IntegritySeverity, pub severity: IntegritySeverity,
pub message: String, pub message: Message,
} }
/// Result of a static integrity check over an unpacked image. /// Result of a static integrity check over an unpacked image.
@@ -56,7 +58,7 @@ pub struct IntegrityFinding {
pub struct IntegrityReport { pub struct IntegrityReport {
/// Each entry describes one detected defect. Empty means no defect found. /// Each entry describes one detected defect. Empty means no defect found.
/// Order and wording match [`IntegrityReport::findings`]. /// Order and wording match [`IntegrityReport::findings`].
pub issues: Vec<String>, pub issues: Vec<Message>,
/// The same defects as `issues`, each tagged fatal or warning. /// The same defects as `issues`, each tagged fatal or warning.
pub findings: Vec<IntegrityFinding>, pub findings: Vec<IntegrityFinding>,
} }
@@ -78,7 +80,7 @@ impl IntegrityReport {
.any(|finding| finding.severity == IntegritySeverity::Fatal) .any(|finding| finding.severity == IntegritySeverity::Fatal)
} }
fn push(&mut self, severity: IntegritySeverity, message: impl Into<String>) { fn push(&mut self, severity: IntegritySeverity, message: impl Into<Message>) {
let message = message.into(); let message = message.into();
self.issues.push(message.clone()); self.issues.push(message.clone());
self.findings.push(IntegrityFinding { severity, message }); self.findings.push(IntegrityFinding { severity, message });
@@ -152,9 +154,10 @@ fn check_common_entry_branches(
if !valid { if !valid {
report.push( report.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!( Msg::EntryStubTargetOutsideCode {
"entry point {name} target 0x{target:X} is outside executable sections (DD8 selection is likely wrong)" branch: name,
), target,
},
); );
} }
} }
@@ -168,23 +171,20 @@ pub fn check(out: &[u8]) -> IntegrityReport {
// --- DOS + PE headers --------------------------------------------------- // --- DOS + PE headers ---------------------------------------------------
if rd_u16(out, 0) != Some(0x5A4D) { if rd_u16(out, 0) != Some(0x5A4D) {
r.push(IntegritySeverity::Fatal, "missing 'MZ' DOS signature"); r.push(IntegritySeverity::Fatal, Msg::MissingMz);
return r; // nothing else is meaningful return r; // nothing else is meaningful
} }
let pe_off = match rd_u32(out, 0x3C) { let pe_off = match rd_u32(out, 0x3C) {
Some(v) => v, Some(v) => v,
None => { None => {
r.push( r.push(IntegritySeverity::Fatal, Msg::TruncatedDosHeader);
IntegritySeverity::Fatal,
"truncated DOS header (no e_lfanew)",
);
return r; return r;
} }
}; };
if rd_u32(out, pe_off) != Some(0x0000_4550) { if rd_u32(out, pe_off) != Some(0x0000_4550) {
r.push( r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!("missing 'PE\\0\\0' signature at 0x{pe_off:X}"), Msg::MissingPeSignature { offset: pe_off },
); );
return r; return r;
} }
@@ -192,7 +192,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
let num_sections = match rd_u16(out, pe_off.wrapping_add(6)) { let num_sections = match rd_u16(out, pe_off.wrapping_add(6)) {
Some(v) => v as u32, Some(v) => v as u32,
None => { None => {
r.push(IntegritySeverity::Fatal, "truncated COFF header"); r.push(IntegritySeverity::Fatal, Msg::TruncatedCoffHeader);
return r; return r;
} }
}; };
@@ -200,7 +200,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
let magic = match rd_u16(out, opt) { let magic = match rd_u16(out, opt) {
Some(v) => v, Some(v) => v,
None => { None => {
r.push(IntegritySeverity::Fatal, "truncated optional header"); r.push(IntegritySeverity::Fatal, Msg::TruncatedOptionalHeader);
return r; return r;
} }
}; };
@@ -210,7 +210,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
other => { other => {
r.push( r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!("bad optional-header magic 0x{other:X}"), Msg::BadOptionalMagic { magic: other },
); );
return r; return r;
} }
@@ -219,33 +219,29 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if num_sections == 0 || num_sections > 96 { if num_sections == 0 || num_sections > 96 {
r.push( r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!("implausible section count {num_sections}"), Msg::ImplausibleSectionCount {
count: num_sections,
},
); );
} }
let size_of_image = rd_u32(out, pe_off.wrapping_add(80)).unwrap_or(0); let size_of_image = rd_u32(out, pe_off.wrapping_add(80)).unwrap_or(0);
if size_of_image == 0 { if size_of_image == 0 {
r.push(IntegritySeverity::Fatal, "SizeOfImage is zero"); r.push(IntegritySeverity::Fatal, Msg::ZeroSizeOfImage);
} }
// --- Section table ------------------------------------------------------ // --- Section table ------------------------------------------------------
let headers = match senbei_pe::parse(out) { let headers = match senbei_pe::parse(out) {
Ok(headers) => headers, Ok(headers) => headers,
Err(_) => { Err(_) => {
r.push( r.push(IntegritySeverity::Fatal, Msg::SectionTablePastEof);
IntegritySeverity::Fatal,
"section table extends past end of file",
);
return r; return r;
} }
}; };
let parsed_sections = match senbei_pe::sections(out, headers) { let parsed_sections = match senbei_pe::sections(out, headers) {
Ok(sections) => sections, Ok(sections) => sections,
Err(_) => { Err(_) => {
r.push( r.push(IntegritySeverity::Fatal, Msg::SectionTablePastEof);
IntegritySeverity::Fatal,
"section table extends past end of file",
);
return r; return r;
} }
}; };
@@ -258,10 +254,12 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if end > file_len { if end > file_len {
r.push( r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!( Msg::SectionRawPastEof {
"section #{i} raw data [0x{:X}..0x{end:X}] exceeds file size 0x{file_len:X}", index: i,
section.raw_offset start: section.raw_offset,
), end,
file_len,
},
); );
} }
} }
@@ -303,10 +301,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
// (`IMAGE_FILE_RELOCS_STRIPPED`, or a module that is only ever loaded // (`IMAGE_FILE_RELOCS_STRIPPED`, or a module that is only ever loaded
// at its preferred base). Rejecting the layout here would fall back // at its preferred base). Rejecting the layout here would fall back
// to the other pipeline and change bytes that previously unpacked. // to the other pipeline and change bytes that previously unpacked.
r.push( r.push(IntegritySeverity::Warning, Msg::NoBaseRelocations);
IntegritySeverity::Warning,
"native DLL has no base relocation table (DD[5] is zero) — will crash when loaded at a non-preferred base",
);
} }
} }
@@ -318,15 +313,12 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if ep == 0 { if ep == 0 {
// A DLL may legitimately have no entry point; an EXE never does. // A DLL may legitimately have no entry point; an EXE never does.
if !is_dll { if !is_dll {
r.push(IntegritySeverity::Fatal, "entry point RVA is zero"); r.push(IntegritySeverity::Fatal, Msg::ZeroEntryPoint);
} }
} else if !is_managed { } else if !is_managed {
match rva_to_off(out, headers, ep, 16) { match rva_to_off(out, headers, ep, 16) {
None => { None => {
r.push( r.push(IntegritySeverity::Fatal, Msg::EntryUnmapped { rva: ep });
IntegritySeverity::Fatal,
format!("entry point RVA 0x{ep:X} does not map into any section"),
);
} }
Some(off) => { Some(off) => {
let stub = &out[off as usize..off as usize + 16]; let stub = &out[off as usize..off as usize + 16];
@@ -335,21 +327,13 @@ pub fn check(out: &[u8]) -> IntegrityReport {
// were not recovered. That is the suspect signal for an // were not recovered. That is the suspect signal for an
// already-chosen layout, not proof another layout is the // already-chosen layout, not proof another layout is the
// right one. // right one.
r.push( r.push(IntegritySeverity::Warning, Msg::EntryAllZeros { rva: ep });
IntegritySeverity::Warning,
format!("entry point at RVA 0x{ep:X} is all zeros (stub not recovered)"),
);
} else if stub.iter().all(|&b| b == 0xCC) { } else if stub.iter().all(|&b| b == 0xCC) {
// 16 bytes of int3 padding where the entry stub should be: // 16 bytes of int3 padding where the entry stub should be:
// the stub region was never recovered, the loader walks // the stub region was never recovered, the loader walks
// straight into a debug-break wall. Same severity as a // straight into a debug-break wall. Same severity as a
// zeroed stub: the image is mapped, the bytes look unrestored. // zeroed stub: the image is mapped, the bytes look unrestored.
r.push( r.push(IntegritySeverity::Warning, Msg::EntryAllInt3 { rva: ep });
IntegritySeverity::Warning,
format!(
"entry point at RVA 0x{ep:X} is all int3 padding (stub not recovered)"
),
);
} }
// The entry must live in an executable section. // The entry must live in an executable section.
let exec = secs.iter().any(|s| { let exec = secs.iter().any(|s| {
@@ -361,7 +345,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if !exec { if !exec {
r.push( r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!("entry point RVA 0x{ep:X} is not in an executable section"), Msg::EntryNotExecutable { rva: ep },
); );
} }
if let Some(entry_stub) = out.get(off as usize..off as usize + 18) { if let Some(entry_stub) = out.get(off as usize..off as usize + 18) {
@@ -387,7 +371,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
match rva_to_off(out, headers, imp_rva, 20) { match rva_to_off(out, headers, imp_rva, 20) {
None => r.push( None => r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!("import directory RVA 0x{imp_rva:X} does not map into any section"), Msg::ImportDirectoryUnmapped { rva: imp_rva },
), ),
Some(desc_off) => { Some(desc_off) => {
// 256 descriptors is far beyond any real import table; the // 256 descriptors is far beyond any real import table; the
@@ -403,9 +387,10 @@ pub fn check(out: &[u8]) -> IntegrityReport {
match rva_to_off(out, headers, name_rva, 1) { match rva_to_off(out, headers, name_rva, 1) {
None => r.push( None => r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!( Msg::ImportNameUnmapped {
"import descriptor {i} DLL name RVA 0x{name_rva:X} does not map into any section" index: i,
), rva: name_rva,
},
), ),
Some(noff) => { Some(noff) => {
if !looks_like_dll_name(out, noff) { if !looks_like_dll_name(out, noff) {
@@ -415,9 +400,10 @@ pub fn check(out: &[u8]) -> IntegrityReport {
// suspect signal, not an unmapped PE. // suspect signal, not an unmapped PE.
r.push( r.push(
IntegritySeverity::Warning, IntegritySeverity::Warning,
format!( Msg::ImportNameUnreadable {
"import descriptor {i} DLL name at RVA 0x{name_rva:X} is not readable ASCII (imports left encrypted?)" index: i,
), rva: name_rva,
},
); );
} }
} }
@@ -441,16 +427,17 @@ pub fn check(out: &[u8]) -> IntegrityReport {
match rva_to_off(out, headers, clr_rva, 0x48) { match rva_to_off(out, headers, clr_rva, 0x48) {
None => r.push( None => r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!("CLR (COR20) directory RVA 0x{clr_rva:X} does not map into any section"), Msg::ClrDirectoryUnmapped { rva: clr_rva },
), ),
Some(coff) => { Some(coff) => {
let cb = rd_u32(out, coff).unwrap_or(0); let cb = rd_u32(out, coff).unwrap_or(0);
if cb != 0x48 { if cb != 0x48 {
r.push( r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!( Msg::ClrHeaderBadSize {
"COR20 header at RVA 0x{clr_rva:X} has cb 0x{cb:X} (expected 0x48) — CLR header corrupt" rva: clr_rva,
), size: cb,
},
); );
} else { } else {
// MetaData RVA/size live at COR20 + 0x08 / + 0x0C. // MetaData RVA/size live at COR20 + 0x08 / + 0x0C.
@@ -459,18 +446,14 @@ pub fn check(out: &[u8]) -> IntegrityReport {
match rva_to_off(out, headers, md_rva, 4) { match rva_to_off(out, headers, md_rva, 4) {
None => r.push( None => r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!( Msg::ClrMetadataUnmapped { rva: md_rva },
"CLR MetaData RVA 0x{md_rva:X} does not map into any section"
),
), ),
Some(moff) => { Some(moff) => {
let sig = out.get(moff as usize..moff as usize + 4); let sig = out.get(moff as usize..moff as usize + 4);
if sig != Some(b"BSJB") { if sig != Some(b"BSJB") {
r.push( r.push(
IntegritySeverity::Fatal, IntegritySeverity::Fatal,
format!( Msg::ClrMetadataNoBsjb { rva: md_rva },
"CLR MetaData at RVA 0x{md_rva:X} lacks 'BSJB' signature (metadata corrupt — managed image will not load)"
),
); );
} }
} }
+8 -7
View File
@@ -10,6 +10,7 @@ pub(crate) mod parallel;
pub mod research; pub mod research;
use senbei_crypto::primitives; use senbei_crypto::primitives;
use senbei_i18n::Message;
use serde::Serialize; use serde::Serialize;
use crate::profile::{ use crate::profile::{
@@ -309,7 +310,7 @@ pub fn unpack_auto_profiled_v(
let mut profile = inspect_detected(input, detected); let mut profile = inspect_detected(input, detected);
let Some(detected) = detected else { let Some(detected) = detected else {
let error = UnpackError::NotCrackProof; let error = UnpackError::NotCrackProof;
profile.push_error(error.to_string()); profile.push_error(error.message());
return (profile, Err(error)); return (profile, Err(error));
}; };
let result = match detected.kind { let result = match detected.kind {
@@ -343,7 +344,7 @@ pub fn unpack_exe_profiled_v(
let mut profile = inspect_detected(input, detected); let mut profile = inspect_detected(input, detected);
if detected.is_none() { if detected.is_none() {
let error = UnpackError::NotCrackProof; let error = UnpackError::NotCrackProof;
profile.push_error(error.to_string()); profile.push_error(error.message());
return (profile, Err(error)); return (profile, Err(error));
} }
// This entry point will never run the DLL route, so a DLL-kind detection's // This entry point will never run the DLL route, so a DLL-kind detection's
@@ -383,10 +384,10 @@ fn run_exe_attempt(
LayoutKind::ExeStyle, LayoutKind::ExeStyle,
AttemptOutcome::Failed, AttemptOutcome::Failed,
Vec::new(), Vec::new(),
vec![error.to_string()], vec![error.message()],
); );
profile.recovery = RecoveryStatus::Failed; profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_string()); profile.push_error(error.message());
Err(error) Err(error)
} }
} }
@@ -431,7 +432,7 @@ where
dll: Box::new(dll.error), dll: Box::new(dll.error),
exe: Box::new(exe.error), exe: Box::new(exe.error),
}; };
profile.push_error(error.to_string()); profile.push_error(error.message());
Err(error) Err(error)
} }
} }
@@ -453,7 +454,7 @@ fn record_rejected(profile: &mut ProtectionProfile, layout: LayoutKind, failure:
profile_messages(report, ProfileSeverity::Warning), profile_messages(report, ProfileSeverity::Warning),
profile_messages(report, ProfileSeverity::Fatal), profile_messages(report, ProfileSeverity::Fatal),
), ),
None => (Vec::new(), vec![failure.error.to_string()]), None => (Vec::new(), vec![failure.error.message()]),
}; };
let outcome = if failure.report.is_some() { let outcome = if failure.report.is_some() {
AttemptOutcome::Rejected AttemptOutcome::Rejected
@@ -463,7 +464,7 @@ fn record_rejected(profile: &mut ProtectionProfile, layout: LayoutKind, failure:
profile.record_attempt(layout, outcome, warnings, errors); profile.record_attempt(layout, outcome, warnings, errors);
} }
fn profile_messages(report: &IntegrityReport, severity: ProfileSeverity) -> Vec<String> { fn profile_messages(report: &IntegrityReport, severity: ProfileSeverity) -> Vec<Message> {
report report
.findings .findings
.iter() .iter()
+1
View File
@@ -12,6 +12,7 @@ indicatif.workspace = true
memmap2.workspace = true memmap2.workspace = true
owo-colors.workspace = true owo-colors.workspace = true
senbei-engine.workspace = true senbei-engine.workspace = true
senbei-i18n.workspace = true
senbei-elf.workspace = true senbei-elf.workspace = true
senbei-pe.workspace = true senbei-pe.workspace = true
senbei-metadata.workspace = true senbei-metadata.workspace = true
+28 -10
View File
@@ -40,7 +40,9 @@ use sha2::{Digest, Sha256};
use zip::ZipArchive; use zip::ZipArchive;
pub use crate::METADATA_FILE_NAME; pub use crate::METADATA_FILE_NAME;
use crate::message::Coded;
use crate::report::{ContainerReport, ManifestReport}; use crate::report::{ContainerReport, ManifestReport};
use senbei_i18n::Msg;
/// Package extensions recognised as Android app packages. Packages are /// Package extensions recognised as Android app packages. Packages are
/// *containers*: membership is decided by extension plus the ZIP magic, while /// *containers*: membership is decided by extension plus the ZIP magic, while
@@ -114,7 +116,9 @@ pub fn inspect_package(package: &Path, limits: &ResourceLimits) -> Result<Contai
continue; continue;
} }
let Some(name) = name else { let Some(name) = name else {
bail!("unsafe entry path in package `{}`", package.display()); bail!(Coded::new(Msg::UnsafePackageEntry {
package: package.display().to_string(),
}));
}; };
if bundle { if bundle {
if name if name
@@ -642,7 +646,7 @@ pub(crate) fn restore_loose_metadata(
), ),
Err(ambiguity) => { Err(ambiguity) => {
let provenance = context::provenance_for(modules.as_ref(), Some(&ambiguity)); let provenance = context::provenance_for(modules.as_ref(), Some(&ambiguity));
bail!(provenance_error(&provenance)); bail!(provenance_error(&provenance, &ambiguity));
} }
} }
} else { } else {
@@ -657,7 +661,7 @@ pub(crate) fn restore_loose_metadata(
if report.remapped > 0 { if report.remapped > 0 {
write_metadata_blob(dest, &out)?; write_metadata_blob(dest, &out)?;
if verbose { if verbose {
println!("Write to {}", dest.display()); crate::ui::write_to(dest, false);
} }
} }
Ok(LooseMetadataOutcome { Ok(LooseMetadataOutcome {
@@ -995,7 +999,7 @@ pub(crate) fn restore_metadata_with_module(
// version" and could be mistaken for a clean skip. No module is a // version" and could be mistaken for a clean skip. No module is a
// failed binding, not an unsupported layout. // failed binding, not an unsupported layout.
let Some(module) = method_index_module else { let Some(module) = method_index_module else {
let error = anyhow::anyhow!("no module 0x0C for v24.1 metadata"); let error = anyhow::Error::new(Coded::new(Msg::NoModule0c));
return Err(fail(&mut facts, error)); return Err(fail(&mut facts, error));
}; };
let (out, report) = senbei_metadata::android::restore_method_indices_v24_1(data, module) let (out, report) = senbei_metadata::android::restore_method_indices_v24_1(data, module)
@@ -1335,7 +1339,9 @@ fn restore_package_pass<R: context::LibraryRestorer>(
continue; continue;
} }
let Some(name) = name else { let Some(name) = name else {
bail!("unsafe entry path in package `{}`", package.display()); bail!(Coded::new(Msg::UnsafePackageEntry {
package: package.display().to_string(),
}));
}; };
if bundle { if bundle {
if name if name
@@ -1436,7 +1442,9 @@ fn restore_package_pass<R: context::LibraryRestorer>(
}; };
if !is_dir { if !is_dir {
let Some(entry_name) = entry_name else { let Some(entry_name) = entry_name else {
bail!("unsafe entry path in `{}`", nested_label.display()); bail!(Coded::new(Msg::UnsafeNestedEntry {
path: nested_label.display().to_string(),
}));
}; };
if is_android_entry_name(&entry_name) { if is_android_entry_name(&entry_name) {
entries.push((nested_index, entry_name)); entries.push((nested_index, entry_name));
@@ -1674,7 +1682,10 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
let provenance = context::provenance_for(modules.as_ref(), Some(&ambiguity)); let provenance = context::provenance_for(modules.as_ref(), Some(&ambiguity));
return Ok(vec![outcome( return Ok(vec![outcome(
EntryKind::Metadata { remapped: 0 }, EntryKind::Metadata { remapped: 0 },
EntryStatus::Failed(anyhow::anyhow!(provenance_error(&provenance))), EntryStatus::Failed(anyhow::Error::new(provenance_error(
&provenance,
&ambiguity,
))),
provenance_labels(&provenance), provenance_labels(&provenance),
)]); )]);
} }
@@ -1792,13 +1803,20 @@ fn provenance_labels(provenance: &context::MetadataProvenance) -> Vec<String> {
.collect() .collect()
} }
fn provenance_error(provenance: &context::MetadataProvenance) -> String { fn provenance_error(
provenance: &context::MetadataProvenance,
ambiguity: &context::ContextAmbiguity,
) -> Coded {
let msg = match ambiguity {
context::ContextAmbiguity::Missing => Msg::NoModule0c,
context::ContextAmbiguity::Conflicting { .. } => Msg::AmbiguousModule0c,
};
let why = provenance let why = provenance
.note .note
.clone() .clone()
.unwrap_or_else(|| "ambiguous module 0x0C binding".to_owned()); .unwrap_or_else(|| "ambiguous module 0x0C binding".to_owned());
if provenance.sources.is_empty() { if provenance.sources.is_empty() {
return why; return Coded::with_text(msg, why);
} }
let sources = provenance let sources = provenance
.sources .sources
@@ -1806,7 +1824,7 @@ fn provenance_error(provenance: &context::MetadataProvenance) -> String {
.map(|source| source.label.as_str()) .map(|source| source.label.as_str())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
format!("{why}; modules from {sources}") Coded::with_text(msg, format!("{why}; modules from {sources}"))
} }
/// Output path for a metadata blob unwrapped from a restored library: next to /// Output path for a metadata blob unwrapped from a restored library: next to
+233 -115
View File
@@ -1,7 +1,10 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::Instant; use std::time::Instant;
use senbei_i18n::{Cli, Lang, Localize, Message, Msg};
use crate::atomic::write_atomic; use crate::atomic::write_atomic;
use crate::message::{Coded, of_error};
pub use crate::report::{Collector, Mode, REPORT_FORMAT_VERSION, Report}; pub use crate::report::{Collector, Mode, REPORT_FORMAT_VERSION, Report};
use crate::report::{ use crate::report::{
CompanionReport, CompanionState, ContainerReport, Digest, EntryKind, EntryReport, EntryStatus, CompanionReport, CompanionState, ContainerReport, Digest, EntryKind, EntryReport, EntryStatus,
@@ -34,30 +37,31 @@ pub struct Summary {
} }
impl Summary { impl Summary {
/// The plain summary line shared by CLI output and the log file. /// The plain English summary line, as the log file records it.
pub fn line(&self) -> String { pub fn line(&self) -> String {
self.line_with_palette(crate::ui::Palette::plain()) self.line_in(crate::ui::Palette::plain(), Lang::En)
} }
/// Console rendering without adding presentation escapes to log data. /// Console rendering in the process language, without adding
/// presentation escapes to log data.
pub fn line_with_palette(&self, palette: crate::ui::Palette) -> String { pub fn line_with_palette(&self, palette: crate::ui::Palette) -> String {
use crate::ui::{Tone, count}; self.line_in(palette, senbei_i18n::current())
}
let mut line = format!( /// The summary line in `lang`.
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata", pub fn line_in(&self, palette: crate::ui::Palette, lang: Lang) -> String {
count(palette, self.unpacked, Tone::Success), crate::ui::summary_line(
count(palette, self.skipped, Tone::Muted), palette,
count(palette, self.errors, Tone::Error), lang,
count(palette, self.suspect, Tone::Warning), [
count(palette, self.metadata, Tone::Success) self.unpacked,
); self.skipped,
if self.packages > 0 { self.errors,
line.push_str(&format!( self.suspect,
" · {} packages", self.metadata,
palette.paint(Tone::Value, self.packages) self.packages,
)); ],
} )
line
} }
} }
@@ -176,7 +180,7 @@ pub fn run_folder_reported(
/// ///
/// Used when a run cannot start at all (an unreadable input, a rejected /// Used when a run cannot start at all (an unreadable input, a rejected
/// command line), so `--json` callers still receive one versioned document. /// command line), so `--json` callers still receive one versioned document.
pub fn error_report(mode: Mode, message: &str) -> Report { pub fn error_report(mode: Mode, message: impl Into<Message>) -> Report {
let mut collector = Collector::new(mode); let mut collector = Collector::new(mode);
collector.push_error(message); collector.push_error(message);
collector.finish() collector.finish()
@@ -188,6 +192,61 @@ pub fn error_report(mode: Mode, message: &str) -> Report {
/// [`run_folder_with_limits`]; the collector only observes. /// [`run_folder_with_limits`]; the collector only observes.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn run_folder_inner( fn run_folder_inner(
root: &Path,
out_dir: Option<&Path>,
quiet: u8,
verbose: bool,
no_log: bool,
scan_all: bool,
limits: &senbei_engine::android::ResourceLimits,
reporter: Option<&mut Collector>,
) -> anyhow::Result<Summary> {
observed(reporter, |reporter| {
run_folder_body(
root, out_dir, quiet, verbose, no_log, scan_all, limits, reporter,
)
})
}
/// Run `body` with the pipelines' verbose progress sent to the collector's
/// observer, when it has one. Without an observer progress prints as before.
fn observed<R>(
reporter: Option<&mut Collector>,
body: impl FnOnce(Option<&mut Collector>) -> R,
) -> R {
match reporter.as_deref().and_then(Collector::observer).cloned() {
Some(observer) => senbei_engine::progress::with_sink(
move |event| observer.progress(event),
|| body(reporter),
),
None => body(reporter),
}
}
/// True once the run's front end asked it to stop. Checked before each input.
fn stop(reporter: &mut Option<&mut Collector>) -> bool {
reporter.as_deref_mut().is_some_and(Collector::should_stop)
}
/// Tell the run's observer that work on `path` began.
fn started(reporter: &Option<&mut Collector>, path: &Path) {
if let Some(observer) = reporter.as_deref().and_then(Collector::observer) {
observer.input_started(path);
}
}
/// Verbose pipeline steps are shown on an unquiet console, or sent to an
/// observer, which never prints them.
fn verbose_steps(verbose: bool, quiet: u8, reporter: &Option<&mut Collector>) -> bool {
verbose
&& (quiet == 0
|| reporter
.as_deref()
.is_some_and(|reporter| reporter.observer().is_some()))
}
#[allow(clippy::too_many_arguments)]
fn run_folder_body(
root: &Path, root: &Path,
out_dir: Option<&Path>, out_dir: Option<&Path>,
quiet: u8, quiet: u8,
@@ -229,10 +288,11 @@ fn run_folder_inner(
// fail the run (exit 1) rather than report "0 errors" over a partial scan. // fail the run (exit 1) rather than report "0 errors" over a partial scan.
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 {
let lang = senbei_i18n::current();
eprintln!( eprintln!(
"{}: {} file(s) could not be read during the scan and may be missed targets", "{}: {}",
Palette::stderr().paint(Tone::Warning, "warning"), Palette::stderr().paint(Tone::Warning, Cli::Warning.localize(lang)),
scan_failed Cli::ScanUnreadable { count: scan_failed }.localize(lang)
); );
} }
if let Some(log) = &log { if let Some(log) = &log {
@@ -252,7 +312,8 @@ fn run_folder_inner(
let suppress_file_lines = quiet >= 1; let suppress_file_lines = quiet >= 1;
// Quiet wins over verbose: step progress only when quiet == 0 (spec: verbose // Quiet wins over verbose: step progress only when quiet == 0 (spec: verbose
// lines only when quiet == 0; quiet ≥ 2 must stay fully silent even with -v). // lines only when quiet == 0; quiet ≥ 2 must stay fully silent even with -v).
let verbose_steps = verbose && quiet == 0; // An observer receives the steps instead of the console.
let verbose_steps = verbose_steps(verbose, quiet, &reporter);
// Verbose mode prints multi-line `[N/9]` step output per file straight to // Verbose mode prints multi-line `[N/9]` step output per file straight to
// stdout; an active progress bar would be clobbered by it, so hide the bar // stdout; an active progress bar would be clobbered by it, so hide the bar
// (its per-file ok/err lines still print) when verbose is on. // (its per-file ok/err lines still print) when verbose is on.
@@ -277,9 +338,21 @@ fn run_folder_inner(
walk_errors: scan_stats.walk_errors, walk_errors: scan_stats.walk_errors,
probe_errors: scan_stats.probe_errors, probe_errors: scan_stats.probe_errors,
}); });
if let Some(observer) = reporter.observer() {
observer.scanned(
candidates.len()
+ scan.android_so.len()
+ scan.android_packages.len()
+ metas.len(),
);
}
} }
for input in candidates { for input in candidates {
if stop(&mut reporter) {
break;
}
started(&reporter, input);
let rel = rel_in_tree(root, input); let rel = rel_in_tree(root, input);
let dest = out_root.join(out_name(&rel)); let dest = out_root.join(out_name(&rel));
let started = Instant::now(); let started = Instant::now();
@@ -346,7 +419,7 @@ fn run_folder_inner(
} }
Err(panic) => { Err(panic) => {
s.errors += 1; s.errors += 1;
let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic)); let e = anyhow::Error::new(Coded::panic("", panic_payload(&panic)));
crate::ui::err(&bar, suppress_file_lines, &rel, &e); crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log { if let Some(log) = &log {
log.step(&format!( log.step(&format!(
@@ -378,6 +451,10 @@ fn run_folder_inner(
.iter() .iter()
.any(|library| library == &scoped.path) .any(|library| library == &scoped.path)
}) { }) {
if stop(&mut reporter) {
break;
}
started(&reporter, &scoped.path);
let rel = rel_in_tree(root, &scoped.path); let rel = rel_in_tree(root, &scoped.path);
let dest = out_root.join(out_name(&rel)); let dest = out_root.join(out_name(&rel));
let input_owned = scoped.path.clone(); let input_owned = scoped.path.clone();
@@ -487,7 +564,7 @@ fn run_folder_inner(
} }
Err(panic) => { Err(panic) => {
s.errors += 1; s.errors += 1;
let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic)); let e = anyhow::Error::new(Coded::panic("", panic_payload(&panic)));
crate::ui::err(&bar, suppress_file_lines, &rel, &e); crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log { if let Some(log) = &log {
log.step(&format!( log.step(&format!(
@@ -516,7 +593,14 @@ fn run_folder_inner(
let package_groups = let package_groups =
crate::android::loose_apk_groups_cached(&scan.android_packages, &mut android_cache); crate::android::loose_apk_groups_cached(&scan.android_packages, &mut android_cache);
for group in &package_groups { for group in &package_groups {
if stop(&mut reporter) {
break;
}
if group.len() > 1 { if group.len() > 1 {
// A split set restores as one unit and reports each member.
for package in group {
started(&reporter, package);
}
s.packages += group.len(); s.packages += group.len();
// Relative output paths are computed here, by the same helper the // Relative output paths are computed here, by the same helper the
// rest of the driver uses: they must stay relative so joining them // rest of the driver uses: they must stay relative so joining them
@@ -588,10 +672,10 @@ fn run_folder_inner(
} }
} }
Err(panic) => { Err(panic) => {
let e = anyhow::anyhow!( let e = anyhow::Error::new(Coded::panic(
"unexpected panic during package restore: {}", " during package restore",
panic_payload(&panic) panic_payload(&panic),
); ));
s.errors += 1; s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e); crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log { if let Some(log) = &log {
@@ -608,6 +692,10 @@ fn run_folder_inner(
continue; continue;
} }
for package in group { for package in group {
if stop(&mut reporter) {
break;
}
started(&reporter, package);
let rel = rel_in_tree(root, package); let rel = rel_in_tree(root, package);
s.packages += 1; s.packages += 1;
let package_owned = package.clone(); let package_owned = package.clone();
@@ -648,7 +736,7 @@ fn run_folder_inner(
Err(panic) => { Err(panic) => {
// A panic may leave a partial module recorded. Keeping the cache // A panic may leave a partial module recorded. Keeping the cache
// preserves successful dedup; a conflict still fails closed. // preserves successful dedup; a conflict still fails closed.
let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic)); let e = anyhow::Error::new(Coded::panic("", panic_payload(&panic)));
s.errors += 1; s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e); crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log { if let Some(log) = &log {
@@ -675,6 +763,10 @@ fn run_folder_inner(
.iter() .iter()
.filter(|scoped| metas.iter().any(|meta| meta == &scoped.path)) .filter(|scoped| metas.iter().any(|meta| meta == &scoped.path))
{ {
if stop(&mut reporter) {
break;
}
started(&reporter, &scoped.path);
let rel = rel_in_tree(root, &scoped.path); let rel = rel_in_tree(root, &scoped.path);
let dest = out_root.join(out_name(&rel)); let dest = out_root.join(out_name(&rel));
let meta_owned = scoped.path.clone(); let meta_owned = scoped.path.clone();
@@ -740,9 +832,11 @@ 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", "{} {} {}",
Palette::stderr().paint(Tone::Warning, "-"), Palette::stderr().paint(Tone::Warning, "-"),
rel.display() rel.display(),
Cli::MetadataUnsupportedLine { version: v }
.localize(senbei_i18n::current())
); );
} }
if let Some(log) = &log { if let Some(log) = &log {
@@ -768,10 +862,10 @@ fn run_folder_inner(
} }
Err(panic) => { Err(panic) => {
s.errors += 1; s.errors += 1;
let e = anyhow::anyhow!( let e = anyhow::Error::new(Coded::panic(
"unexpected panic during de-obfuscation: {}", " during de-obfuscation",
panic_payload(&panic) panic_payload(&panic),
); ));
crate::ui::err(&bar, suppress_file_lines, &rel, &e); crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log { if let Some(log) = &log {
log.step(&format!( log.step(&format!(
@@ -847,6 +941,21 @@ pub fn run_file_reported(
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn run_file_inner( fn run_file_inner(
input: &Path,
out_dir: Option<&Path>,
quiet: u8,
verbose: bool,
no_log: bool,
limits: &senbei_engine::android::ResourceLimits,
reporter: Option<&mut Collector>,
) -> anyhow::Result<Summary> {
observed(reporter, |reporter| {
run_file_body(input, out_dir, quiet, verbose, no_log, limits, reporter)
})
}
#[allow(clippy::too_many_arguments)]
fn run_file_body(
input: &Path, input: &Path,
out_dir: Option<&Path>, out_dir: Option<&Path>,
quiet: u8, quiet: u8,
@@ -883,6 +992,11 @@ fn run_file_inner(
let research = reporter let research = reporter
.as_deref() .as_deref()
.is_some_and(|reporter| reporter.mode() == Mode::Inspect); .is_some_and(|reporter| reporter.mode() == Mode::Inspect);
let verbose_steps = verbose_steps(verbose, quiet, &reporter);
if let Some(observer) = reporter.as_deref().and_then(Collector::observer) {
observer.scanned(1);
}
started(&reporter, input);
let prefix = { let prefix = {
use std::io::Read; use std::io::Read;
@@ -906,7 +1020,7 @@ fn run_file_inner(
let is_android_package = !is_android_so && crate::android::is_app_package(input, &prefix); let is_android_package = !is_android_so && crate::android::is_app_package(input, &prefix);
if is_meta { if is_meta {
match deobfuscate_metadata_researched(input, &dest, verbose && quiet == 0, research, None) { match deobfuscate_metadata_researched(input, &dest, verbose_steps, research, None) {
Ok((report, layout, metadata_research)) if report.remapped > 0 => { Ok((report, layout, metadata_research)) if report.remapped > 0 => {
s.metadata = 1; s.metadata = 1;
if let Some(log) = &log { if let Some(log) = &log {
@@ -916,12 +1030,16 @@ fn run_file_inner(
)); ));
} }
if quiet == 0 { if quiet == 0 {
let palette = Palette::stdout();
let line = Cli::MetadataVersionLine {
version: palette.paint(Tone::Value, report.version).to_string(),
dest: palette.paint(Tone::Value, format!("{dest:?}")).to_string(),
remapped: palette.paint(Tone::Value, report.remapped).to_string(),
};
println!( println!(
"{} metadata v{} -> {} ({} method fields remapped)", "{} {}",
Palette::stdout().paint(Tone::Success, "✓"), palette.paint(Tone::Success, "✓"),
Palette::stdout().paint(Tone::Value, report.version), line.localize(senbei_i18n::current())
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() {
@@ -939,11 +1057,15 @@ fn run_file_inner(
)); ));
} }
if quiet == 0 { if quiet == 0 {
let lang = senbei_i18n::current();
let palette = Palette::stdout();
let version = Cli::MetadataAlreadyClean {
version: palette.paint(Tone::Value, report.version).to_string(),
};
println!( println!(
"metadata v{}: {}", "{} {}",
Palette::stdout().paint(Tone::Value, report.version), version.localize(lang),
Palette::stdout() palette.paint(Tone::Muted, Cli::MetadataNothingToDo.localize(lang))
.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() {
@@ -960,7 +1082,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!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error")); crate::ui::print_anyhow(&e);
} }
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 +1095,7 @@ fn run_file_inner(
crate::android::restore_so_file_researched( crate::android::restore_so_file_researched(
input, input,
&dest, &dest,
verbose && quiet == 0, verbose_steps,
limits, limits,
research, research,
) )
@@ -985,13 +1107,8 @@ fn run_file_inner(
) )
}) })
} else { } else {
crate::android::restore_so_file_with_diagnostics( crate::android::restore_so_file_with_diagnostics(input, &dest, verbose_steps, limits)
input, .map(|(embedded, validation)| (embedded, validation, None))
&dest,
verbose && quiet == 0,
limits,
)
.map(|(embedded, validation)| (embedded, validation, None))
}; };
match restore { match restore {
Ok((embedded, validation, android_research)) => { Ok((embedded, validation, android_research)) => {
@@ -1015,11 +1132,15 @@ fn run_file_inner(
log.step(&format!("META {:?} (embedded) -> {:?}", input, meta_dest)); log.step(&format!("META {:?} (embedded) -> {:?}", input, meta_dest));
} }
if quiet == 0 { if quiet == 0 {
let palette = Palette::stdout();
let line = Cli::EmbeddedMetadataLine {
input: palette.paint(Tone::Label, input.display()).to_string(),
dest: palette.paint(Tone::Value, meta_dest.display()).to_string(),
};
println!( println!(
"{} metadata {} (embedded) -> {}", "{} {}",
Palette::stdout().paint(Tone::Success, "✓"), palette.paint(Tone::Success, "✓"),
Palette::stdout().paint(Tone::Label, input.display()), line.localize(senbei_i18n::current())
Palette::stdout().paint(Tone::Value, meta_dest.display())
); );
} }
} }
@@ -1030,10 +1151,7 @@ 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!( crate::ui::print_error_about(Cli::EmbeddedMetadataFailed, &e);
"{}: embedded metadata: {e:#}",
Palette::stderr().paint(Tone::Error, "error")
);
} }
} }
} }
@@ -1050,7 +1168,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input)); log.step(&format!("ERR {:?}: {e:#}", input));
} }
if quiet == 0 { if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error")); crate::ui::print_anyhow(&e);
} }
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(
@@ -1082,7 +1200,7 @@ fn run_file_inner(
&rel, &rel,
&out_root, &out_root,
&mut seen, &mut seen,
verbose && quiet == 0, verbose_steps,
limits, limits,
research, research,
) { ) {
@@ -1104,7 +1222,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input)); log.step(&format!("ERR {:?}: {e:#}", input));
} }
if quiet == 0 { if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error")); crate::ui::print_anyhow(&e);
} }
if let Some(reporter) = reporter { if let Some(reporter) = reporter {
reporter.push(failed_input(input, &e, t0)); reporter.push(failed_input(input, &e, t0));
@@ -1118,14 +1236,10 @@ fn run_file_inner(
let (profile, observed, result) = match reporter.is_some() { let (profile, observed, result) = match reporter.is_some() {
true => { true => {
let (profile, observed, result) = let (profile, observed, result) =
unpack_one_researched(input, &dest, verbose && quiet == 0, research); unpack_one_researched(input, &dest, verbose_steps, research);
(Some(profile), observed, result) (Some(profile), observed, result)
} }
false => ( false => (None, None, unpack_one_v(input, &dest, verbose_steps)),
None,
None,
unpack_one_v(input, &dest, verbose && quiet == 0),
),
}; };
match result { match result {
Ok((kind, report)) => { Ok((kind, report)) => {
@@ -1151,13 +1265,14 @@ fn run_file_inner(
)); ));
} }
if quiet == 0 { if quiet == 0 {
let lang = senbei_i18n::current();
eprintln!( eprintln!(
"{}: {}", "{}: {}",
Palette::stderr().paint( Palette::stderr().paint(
Tone::Warning, Tone::Warning,
"! integrity check failed (likely to crash at runtime)" Cli::IntegrityFailedLikelyCrash.localize(lang)
), ),
report.issues.join("; ") crate::ui::issues(&report, lang)
); );
} }
} }
@@ -1173,7 +1288,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input)); log.step(&format!("ERR {:?}: {e:#}", input));
} }
if quiet == 0 { if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error")); crate::ui::print_anyhow(&e);
} }
if let Some(reporter) = reporter { if let Some(reporter) = reporter {
let mut reported = match profile { let mut reported = match profile {
@@ -1321,10 +1436,7 @@ fn deobfuscate_metadata_researched(
} }
write_atomic(dest, &out)?; write_atomic(dest, &out)?;
if verbose { if verbose {
println!( crate::ui::write_to(dest, true);
"Write to {}",
Palette::stdout().paint(Tone::Value, dest.display())
);
} }
} }
Ok((report, layout, metadata_research)) Ok((report, layout, metadata_research))
@@ -1676,7 +1788,7 @@ fn unpack_one_researched(
Err(error) => { Err(error) => {
let mut profile = observed_profile(input); let mut profile = observed_profile(input);
profile.recovery = senbei_engine::RecoveryStatus::Blocked; profile.recovery = senbei_engine::RecoveryStatus::Blocked;
profile.push_error(format!("{error:#}")); profile.push_error(of_error(&error));
return (profile, None, Err(error)); return (profile, None, Err(error));
} }
}; };
@@ -1755,10 +1867,7 @@ fn unpack_one_researched(
return (profile, observed, Err(error.into())); return (profile, observed, Err(error.into()));
} }
if verbose { if verbose {
println!( crate::ui::write_to(dest, true);
"Write to {}",
Palette::stdout().paint(Tone::Value, dest.display())
);
} }
(profile, observed, Ok((image.kind, image.integrity))) (profile, observed, Ok((image.kind, image.integrity)))
} }
@@ -1869,13 +1978,11 @@ pub(crate) fn companion_report(
_ => path.map(|path| path.display().to_string()), _ => path.map(|path| path.display().to_string()),
}, },
detail: match state { detail: match state {
CompanionState::Unmatched => { CompanionState::Unmatched => Some(Message::new(Msg::CompanionUnmatched)),
Some("a sibling `._` exists but is not this stub's payload".to_owned()) CompanionState::Unreadable => Some(Message::new(match unreadable {
} Some(reason) => Msg::CompanionUnreadable { reason },
CompanionState::Unreadable => Some(match unreadable { None => Msg::CompanionUnreadableUnknown,
Some(reason) => format!("the sibling `._` could not be read: {reason}"), })),
None => "the sibling `._` could not be read".to_owned(),
}),
_ => None, _ => None,
}, },
source, source,
@@ -1971,7 +2078,7 @@ fn failed_input(input: &Path, error: &anyhow::Error, started: Instant) -> InputR
let mut entry = InputReport::new(input, Role::Content); let mut entry = InputReport::new(input, Role::Content);
entry.status = InputStatus::Error; entry.status = InputStatus::Error;
entry.analysis_incomplete = analysis_incomplete(error); entry.analysis_incomplete = analysis_incomplete(error);
let detail = format!("{error:#}"); let detail = of_error(error);
entry.error(detail.clone()); entry.error(detail.clone());
entry.profile = Some(failure_profile(input, &detail)); entry.profile = Some(failure_profile(input, &detail));
entry entry
@@ -1994,7 +2101,7 @@ fn failed_input_with_profile(
let mut entry = InputReport::new(input, Role::Content); let mut entry = InputReport::new(input, Role::Content);
entry.status = InputStatus::Error; entry.status = InputStatus::Error;
entry.analysis_incomplete = analysis_incomplete(error); entry.analysis_incomplete = analysis_incomplete(error);
let detail = format!("{error:#}"); let detail = of_error(error);
entry.error(detail.clone()); entry.error(detail.clone());
entry.companion = crate::windows::is_pe_extension(input).then(|| { entry.companion = crate::windows::is_pe_extension(input).then(|| {
let (state, source, unreadable) = let (state, source, unreadable) =
@@ -2055,13 +2162,13 @@ fn observed_profile(input: &Path) -> senbei_engine::ProtectionProfile {
} }
/// Profile of an input whose recovery failed. /// Profile of an input whose recovery failed.
fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfile { fn failure_profile(input: &Path, detail: &Message) -> senbei_engine::ProtectionProfile {
use senbei_engine::{AttemptOutcome, LayoutKind, ProtectionProfile, RecoveryStatus}; use senbei_engine::{AttemptOutcome, LayoutKind, ProtectionProfile, RecoveryStatus};
let Ok(prefix) = read_prefix(input) else { let Ok(prefix) = read_prefix(input) else {
let mut profile = let mut profile =
ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)); ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None));
profile.recovery = RecoveryStatus::Failed; profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned()); profile.push_error(detail.clone());
return profile; return profile;
}; };
if senbei_metadata::is_metadata(&prefix) { if senbei_metadata::is_metadata(&prefix) {
@@ -2092,8 +2199,8 @@ fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfi
.find(|candidate| candidate.outcome == AttemptOutcome::NotAttempted) .find(|candidate| candidate.outcome == AttemptOutcome::NotAttempted)
.map(|candidate| candidate.layout) .map(|candidate| candidate.layout)
{ {
Some(layout) => (layout, vec![detail.to_owned()]), Some(layout) => (layout, vec![detail.clone()]),
None => (LayoutKind::ExeStyle, vec![detail.to_owned()]), None => (LayoutKind::ExeStyle, vec![detail.clone()]),
}; };
if let Some(attempt) = profile.attempt_mut(layout) { if let Some(attempt) = profile.attempt_mut(layout) {
attempt.outcome = AttemptOutcome::Failed; attempt.outcome = AttemptOutcome::Failed;
@@ -2107,7 +2214,7 @@ fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfi
}); });
} }
profile.recovery = RecoveryStatus::Failed; profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned()); profile.push_error(detail.clone());
return profile; return profile;
} }
if crate::android::is_elf64_aarch64(&prefix) { if crate::android::is_elf64_aarch64(&prefix) {
@@ -2115,7 +2222,7 @@ fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfi
} }
let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)); let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None));
profile.recovery = RecoveryStatus::Failed; profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned()); profile.push_error(detail.clone());
profile profile
} }
@@ -2156,7 +2263,11 @@ fn android_library_input_with_error(
.push(StageReport::new(Stage::Recovery, StageStatus::Skipped)); .push(StageReport::new(Stage::Recovery, StageStatus::Skipped));
} }
_ => { _ => {
let detail = entry.errors.first().cloned().unwrap_or_default(); let detail = entry
.errors
.first()
.cloned()
.unwrap_or_else(|| Message::raw(""));
entry.profile = Some(crate::report::android_failed_profile(&detail)); entry.profile = Some(crate::report::android_failed_profile(&detail));
entry entry
.stages .stages
@@ -2190,8 +2301,12 @@ fn apply_android_validation(
} else { } else {
senbei_engine::ValidationStatus::Warnings senbei_engine::ValidationStatus::Warnings
}; };
profile.warnings.extend(validation.messages.iter().cloned()); profile
report.warnings.extend(validation.messages.iter().cloned()); .warnings
.extend(validation.messages.iter().cloned().map(Message::from));
report
.warnings
.extend(validation.messages.iter().cloned().map(Message::from));
// The stage itself succeeded — the restore validated the output. Findings // The stage itself succeeded — the restore validated the output. Findings
// are carried as detail and warnings, not as a failed stage. // are carried as detail and warnings, not as a failed stage.
let mut stage = StageReport::new(Stage::StaticValidation, StageStatus::Ok); let mut stage = StageReport::new(Stage::StaticValidation, StageStatus::Ok);
@@ -2265,8 +2380,7 @@ fn metadata_input(
None => crate::report::metadata_unchanged_profile(identity), None => crate::report::metadata_unchanged_profile(identity),
}); });
entry.stages.push( entry.stages.push(
StageReport::new(Stage::Recovery, StageStatus::Skipped) StageReport::new(Stage::Recovery, StageStatus::Skipped).detail(Msg::TransformNoop),
.detail("the transform ran and validated; nothing needed rewriting"),
); );
} }
entry.duration_ms = crate::report::now_ms(started); entry.duration_ms = crate::report::now_ms(started);
@@ -2346,14 +2460,12 @@ fn metadata_failure_input(
report.status = InputStatus::Skipped; report.status = InputStatus::Skipped;
report.errors.clear(); report.errors.clear();
report.profile = Some(crate::report::metadata_unchanged_profile(identity)); report.profile = Some(crate::report::metadata_unchanged_profile(identity));
report.warning(format!( report.warning(Msg::MetadataLeftUntouched { version });
"unsupported metadata version {version}, left untouched"
));
} else { } else {
report.profile = Some(crate::report::metadata_failed_profile( report.profile = Some(crate::report::metadata_failed_profile(
identity, identity,
senbei_engine::LayoutKind::MetadataStructural, senbei_engine::LayoutKind::MetadataStructural,
&format!("{error:#}"), &of_error(error),
)); ));
} }
report report
@@ -2416,7 +2528,9 @@ fn package_input(
.flat_map(|validation| validation.messages.iter().cloned()) .flat_map(|validation| validation.messages.iter().cloned())
.collect(); .collect();
if !diagnostics.is_empty() { if !diagnostics.is_empty() {
entry.warnings.extend(diagnostics.clone()); entry
.warnings
.extend(diagnostics.iter().cloned().map(Message::from));
entry.stages.push( entry.stages.push(
StageReport::new(Stage::StaticValidation, StageStatus::Ok) StageReport::new(Stage::StaticValidation, StageStatus::Ok)
.detail(diagnostics.join("; ")), .detail(diagnostics.join("; ")),
@@ -2475,7 +2589,7 @@ fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport {
report.output = Some(OutputFile::from_path(&outcome.dest)); report.output = Some(OutputFile::from_path(&outcome.dest));
} }
if let crate::android::EntryStatus::Failed(error) = &outcome.status { if let crate::android::EntryStatus::Failed(error) = &outcome.status {
report.errors.push(format!("{error:#}")); report.errors.push(of_error(error));
// A resource or I/O ceiling stopped this entry before its structure // A resource or I/O ceiling stopped this entry before its structure
// could be judged; a structural rejection is an observed finding. // could be judged; a structural rejection is an observed finding.
report.analysis_incomplete = analysis_incomplete(error); report.analysis_incomplete = analysis_incomplete(error);
@@ -2485,7 +2599,9 @@ fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport {
if status == EntryStatus::Restored if status == EntryStatus::Restored
&& let Some(validation) = &outcome.validation && let Some(validation) = &outcome.validation
{ {
report.warnings.extend(validation.messages.iter().cloned()); report
.warnings
.extend(validation.messages.iter().cloned().map(Message::from));
} }
report report
} }
@@ -2814,7 +2930,7 @@ mod incomplete_analysis_tests {
std::fs::write(&path, b"not really an ELF").unwrap(); std::fs::write(&path, b"not really an ELF").unwrap();
let mut input = InputReport::new(&path, Role::Content); let mut input = InputReport::new(&path, Role::Content);
input.status = InputStatus::Error; input.status = InputStatus::Error;
input.profile = Some(crate::report::android_failed_profile("limit")); input.profile = Some(crate::report::android_failed_profile(&"limit".into()));
input.analysis_incomplete = true; input.analysis_incomplete = true;
let reported = inspect_status(input); let reported = inspect_status(input);
assert_eq!(reported.status, InputStatus::Error); assert_eq!(reported.status, InputStatus::Error);
@@ -2823,7 +2939,9 @@ mod incomplete_analysis_tests {
// The same target without an incompleteness marker is a finding. // The same target without an incompleteness marker is a finding.
let mut complete = InputReport::new(&path, Role::Content); let mut complete = InputReport::new(&path, Role::Content);
complete.status = InputStatus::Error; complete.status = InputStatus::Error;
complete.profile = Some(crate::report::android_failed_profile("layout rejected")); complete.profile = Some(crate::report::android_failed_profile(
&"layout rejected".into(),
));
let reported = inspect_status(complete); let reported = inspect_status(complete);
assert_eq!(reported.status, InputStatus::Recognized); assert_eq!(reported.status, InputStatus::Recognized);
assert!(!reported.analysis_incomplete); assert!(!reported.analysis_incomplete);
@@ -2834,7 +2952,7 @@ mod incomplete_analysis_tests {
fn a_container_inherits_an_incomplete_entry() { fn a_container_inherits_an_incomplete_entry() {
let mut entry = EntryReport::new("app.apk::lib/arm64-v8a/libil2cpp.so", EntryStatus::Error); let mut entry = EntryReport::new("app.apk::lib/arm64-v8a/libil2cpp.so", EntryStatus::Error);
entry.analysis_incomplete = true; entry.analysis_incomplete = true;
entry.errors.push("resource limit".to_owned()); entry.errors.push("resource limit".into());
let td = tempfile::tempdir().unwrap(); let td = tempfile::tempdir().unwrap();
let path = td.path().join("app.apk"); let path = td.path().join("app.apk");
std::fs::write(&path, b"PK").unwrap(); std::fs::write(&path, b"PK").unwrap();
+3
View File
@@ -6,7 +6,10 @@ pub const METADATA_FILE_NAME: &str = "global-metadata.dat";
pub mod android; pub mod android;
mod atomic; mod atomic;
pub mod job; pub mod job;
pub mod locale;
pub mod logfile; pub mod logfile;
pub mod message;
pub mod observe;
pub mod pause; pub mod pause;
pub mod report; pub mod report;
pub mod scan; pub mod scan;
+89
View File
@@ -0,0 +1,89 @@
//! The display language for console output.
//!
//! Only console text follows it. Logs and `--json` reports are English in every
//! language, so their contents never depend on the machine they ran on.
use senbei_i18n::Lang;
/// Environment variable that overrides the system display language.
pub const LANG_VAR: &str = "SENBEI_LANG";
/// The display language: `SENBEI_LANG` when it is set, otherwise the system's
/// preferred UI language, otherwise English.
///
/// A `SENBEI_LANG` value that names no supported language selects English, so
/// `SENBEI_LANG=C` behaves as it does for other tools.
pub fn detect() -> Lang {
match std::env::var(LANG_VAR) {
Ok(value) if !value.trim().is_empty() => Lang::from_tag(&value).unwrap_or_default(),
_ => system().unwrap_or_default(),
}
}
/// The first supported language among the user's preferred UI languages.
#[cfg(windows)]
fn system() -> Option<Lang> {
use windows::Win32::Globalization::{GetUserPreferredUILanguages, MUI_LANGUAGE_NAME};
use windows::core::PWSTR;
let mut count = 0u32;
let mut len = 0u32;
// SAFETY: the first call only reports the buffer length; the second writes
// at most `len` UTF-16 units into a buffer of exactly that length.
unsafe { GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &mut count, None, &mut len) }.ok()?;
let mut buffer = vec![0u16; len as usize];
unsafe {
GetUserPreferredUILanguages(
MUI_LANGUAGE_NAME,
&mut count,
Some(PWSTR(buffer.as_mut_ptr())),
&mut len,
)
}
.ok()?;
first_supported(String::from_utf16_lossy(&buffer).split('\0'))
}
/// The language of the POSIX message locale. `LANGUAGE` is a GNU priority
/// list that applies unless the locale is `C` or `POSIX`.
#[cfg(all(not(windows), not(target_arch = "wasm32")))]
fn system() -> Option<Lang> {
let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty());
let locale = var("LC_ALL")
.or_else(|| var("LC_MESSAGES"))
.or_else(|| var("LANG"))?;
let base = locale.split(['.', '@']).next().unwrap_or_default();
if base == "C" || base == "POSIX" {
return Some(Lang::En);
}
var("LANGUAGE")
.and_then(|list| first_supported(list.split(':')))
.or_else(|| Lang::from_tag(&locale))
}
#[cfg(target_arch = "wasm32")]
fn system() -> Option<Lang> {
None
}
#[cfg(any(test, not(target_arch = "wasm32")))]
fn first_supported<'a>(tags: impl IntoIterator<Item = &'a str>) -> Option<Lang> {
tags.into_iter()
.filter(|tag| !tag.is_empty())
.find_map(Lang::from_tag)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_first_supported_preference_wins() {
assert_eq!(
first_supported(["fr-FR", "zh-TW", "en-US", ""]),
Some(Lang::ZhTw)
);
assert_eq!(first_supported(["fr-FR", "de-DE"]), None);
assert_eq!(first_supported([]), None);
}
}
+172
View File
@@ -0,0 +1,172 @@
//! Translatable messages for errors that reach the I/O layer.
//!
//! Reports, logs, and `--json` keep an error's English exactly as `{error:#}`
//! prints its chain. A front end showing another language translates the first
//! cause in the chain that has a message code, and keeps the English as detail.
use std::fmt;
use senbei_i18n::{Message, Msg};
/// An error raised by the I/O layer itself, carrying its message code.
#[derive(Debug)]
pub(crate) struct Coded(Message);
impl Coded {
pub(crate) fn new(msg: Msg) -> Self {
Self(Message::new(msg))
}
/// A panic caught while `context` ran (for example " during de-obfuscation",
/// or "" when nothing more specific is known).
pub(crate) fn panic(context: &str, payload: String) -> Self {
let text = format!("unexpected panic{context}: {payload}");
Self(Message::with_text(
Msg::UnexpectedPanic { message: payload },
text,
))
}
/// A message whose English differs from the catalog wording for `msg`.
pub(crate) fn with_text(msg: Msg, text: String) -> Self {
Self(Message::with_text(msg, text))
}
}
impl fmt::Display for Coded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.0.text())
}
}
impl std::error::Error for Coded {}
/// The message for `error`: its English chain, translated through the first
/// cause that has a message code.
pub fn of_error(error: &anyhow::Error) -> Message {
let text = format!("{error:#}");
match error.chain().find_map(code) {
Some(msg) => Message::with_text(msg, text),
None => Message::raw(text),
}
}
fn code(cause: &(dyn std::error::Error + 'static)) -> Option<Msg> {
use senbei_engine::android::{ExtractionError, LimitExceeded, RestoreError};
use senbei_metadata::android::{Error as TokenError, MethodIndexError};
if let Some(coded) = cause.downcast_ref::<Coded>() {
return coded.0.msg().cloned();
}
if let Some(error) = cause.downcast_ref::<senbei_engine::windows::UnpackError>() {
return error.message().msg().cloned();
}
let limit = cause.downcast_ref::<LimitExceeded>().or_else(|| {
match cause.downcast_ref::<ExtractionError>() {
Some(ExtractionError::Limit(limit)) => Some(limit),
_ => match cause.downcast_ref::<RestoreError>() {
Some(RestoreError::Limit(limit)) => Some(limit),
_ => None,
},
}
});
if let Some(limit) = limit {
return limit.message().msg().cloned();
}
if let Some(error) = cause.downcast_ref::<senbei_pe::Error>() {
return match error {
senbei_pe::Error::Invalid => Some(Msg::NotPe),
senbei_pe::Error::OutOfBounds => None,
};
}
if let Some(error) = cause.downcast_ref::<senbei_elf::Error>() {
return match error {
senbei_elf::Error::NotElf64 => Some(Msg::NotElf64),
senbei_elf::Error::NotAarch64 => Some(Msg::NotAarch64),
_ => None,
};
}
if let Some(error) = cause.downcast_ref::<senbei_metadata::Error>() {
return Some(match error {
senbei_metadata::Error::NotMetadata => Msg::NotMetadata,
senbei_metadata::Error::UnsupportedVersion(version) => {
Msg::UnsupportedMetadataVersion { version: *version }
}
senbei_metadata::Error::Malformed => Msg::MetadataTransformFailed,
});
}
if let Some(error) = cause.downcast_ref::<TokenError>() {
return Some(match error {
TokenError::NotMetadata => Msg::NotIl2cppMetadata,
TokenError::UnsupportedVersion(version) => {
Msg::UnsupportedMetadataVersion { version: *version }
}
TokenError::Malformed(_) | TokenError::Validation(_) => Msg::MetadataTransformFailed,
});
}
if let Some(error) = cause.downcast_ref::<MethodIndexError>() {
return Some(match error {
MethodIndexError::NotMetadata => Msg::NotIl2cppMetadata,
MethodIndexError::UnsupportedVersion(version) => {
Msg::UnsupportedMetadataVersion { version: *version }
}
_ => Msg::MetadataTransformFailed,
});
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use senbei_i18n::Lang;
#[test]
fn the_english_is_the_whole_chain_and_the_code_its_first_known_cause() {
let error = anyhow::Error::new(senbei_engine::android::LimitExceeded::Entry {
requested: 10,
limit: 4,
})
.context("extract `a.so`");
let message = of_error(&error);
assert_eq!(message.text(), format!("{error:#}"));
assert_eq!(
message.msg(),
Some(&Msg::LimitEntry {
requested: 10,
limit: 4
})
);
assert_eq!(message.detail(Lang::En), None);
assert_eq!(message.detail(Lang::Ko), Some(message.text()));
}
#[test]
fn unknown_chains_stay_raw_and_io_codes_survive_anyhow() {
let raw = of_error(&anyhow::anyhow!("couldn't read companion x"));
assert_eq!(raw.msg(), None);
assert_eq!(raw.text(), "couldn't read companion x");
let panic = anyhow::Error::new(Coded::panic(" during de-obfuscation", "boom".into()));
let message = of_error(&panic);
assert_eq!(
message.text(),
"unexpected panic during de-obfuscation: boom"
);
assert_eq!(
message.msg(),
Some(&Msg::UnexpectedPanic {
message: "boom".into()
})
);
let unpack = anyhow::Error::new(senbei_engine::windows::UnpackError::NotCrackProof);
assert_eq!(of_error(&unpack).msg(), Some(&Msg::NotProtected));
let metadata = anyhow::Error::new(senbei_metadata::Error::UnsupportedVersion(27))
.context("\"global-metadata.dat\"");
assert_eq!(
of_error(&metadata).msg(),
Some(&Msg::UnsupportedMetadataVersion { version: 27 })
);
}
}
+48
View File
@@ -0,0 +1,48 @@
//! Live progress and cancellation for front ends that show a run as it happens.
//!
//! The CLI prints its own lines and uses neither. A front end attaches both to
//! the [`Collector`](crate::report::Collector) it passes to a reporting run.
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::report::InputReport;
/// Receives a run's progress on the thread doing the work. Every method has an
/// empty default, so an observer implements only what it shows.
pub trait RunObserver: Send + Sync {
/// The scan finished: `inputs` targets were found and will be processed.
fn scanned(&self, _inputs: usize) {}
/// Work on `path` began.
fn input_started(&self, _path: &Path) {}
/// A verbose pipeline event for the input being processed. Sent only when
/// the run was started with `verbose`.
fn progress(&self, _event: &senbei_engine::progress::Event) {}
/// One input finished. This is the report the run keeps for it.
fn input_finished(&self, _input: &InputReport) {}
}
/// A request to stop a run, checked before each input.
///
/// Cancelling never interrupts an input mid-recovery: the input in progress
/// finishes and is reported, and no later input starts.
#[derive(Debug, Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);
impl CancelToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
}
+5 -1
View File
@@ -16,8 +16,12 @@ pub fn maybe_pause(force_skip: bool) {
if force_skip || !should_pause() { if force_skip || !should_pause() {
return; return;
} }
use senbei_i18n::Localize;
use std::io::Write; use std::io::Write;
eprint!("\nPress Enter to exit…"); eprint!(
"{}",
senbei_i18n::Cli::PressEnter.localize(senbei_i18n::current())
);
let _ = std::io::stderr().flush(); let _ = std::io::stderr().flush();
let mut buf = String::new(); let mut buf = String::new();
let _ = std::io::stdin().read_line(&mut buf); let _ = std::io::stdin().read_line(&mut buf);
+114 -57
View File
@@ -24,11 +24,14 @@
//! mistaken for inspected protected content. //! mistaken for inspected protected content.
use std::path::Path; use std::path::Path;
use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
use serde::Serialize; use serde::Serialize;
use sha2::{Digest as _, Sha256}; use sha2::{Digest as _, Sha256};
use senbei_i18n::{Cli, Lang, Localize, Message, Msg};
use senbei_engine::{ use senbei_engine::{
AttemptOutcome, LayoutKind, ProtectionEvidence, ProtectionProfile, RecognitionStatus, AttemptOutcome, LayoutKind, ProtectionEvidence, ProtectionProfile, RecognitionStatus,
RecoveryStatus, ValidationStatus, RecoveryStatus, ValidationStatus,
@@ -211,7 +214,7 @@ pub struct ScanReport {
pub struct CompanionReport { pub struct CompanionReport {
pub state: CompanionState, pub state: CompanionState,
pub path: Option<String>, pub path: Option<String>,
pub detail: Option<String>, pub detail: Option<Message>,
/// Identity of the physical companion, distinct from the spliced view. /// Identity of the physical companion, distinct from the spliced view.
pub source: Option<Digest>, pub source: Option<Digest>,
} }
@@ -275,7 +278,7 @@ pub struct ContainerReport {
pub struct StageReport { pub struct StageReport {
pub stage: Stage, pub stage: Stage,
pub status: StageStatus, pub status: StageStatus,
pub detail: Option<String>, pub detail: Option<Message>,
pub duration_ms: Option<u64>, pub duration_ms: Option<u64>,
} }
@@ -289,7 +292,7 @@ impl StageReport {
} }
} }
pub fn detail(mut self, detail: impl Into<String>) -> Self { pub fn detail(mut self, detail: impl Into<Message>) -> Self {
self.detail = Some(detail.into()); self.detail = Some(detail.into());
self self
} }
@@ -318,8 +321,8 @@ pub struct EntryReport {
pub provenance: Vec<String>, pub provenance: Vec<String>,
/// Where the restored bytes were written (absent in dry-run/inspect). /// Where the restored bytes were written (absent in dry-run/inspect).
pub output: Option<OutputFile>, pub output: Option<OutputFile>,
pub warnings: Vec<String>, pub warnings: Vec<Message>,
pub errors: Vec<String>, pub errors: Vec<Message>,
} }
impl EntryReport { impl EntryReport {
@@ -373,8 +376,8 @@ pub struct InputReport {
/// Libraries whose decoded module was paired with this metadata input. /// Libraries whose decoded module was paired with this metadata input.
pub provenance: Vec<String>, pub provenance: Vec<String>,
pub stages: Vec<StageReport>, pub stages: Vec<StageReport>,
pub warnings: Vec<String>, pub warnings: Vec<Message>,
pub errors: Vec<String>, pub errors: Vec<Message>,
pub duration_ms: u64, pub duration_ms: u64,
} }
@@ -405,11 +408,11 @@ impl InputReport {
} }
} }
pub fn warning(&mut self, message: impl Into<String>) { pub fn warning(&mut self, message: impl Into<Message>) {
self.warnings.push(message.into()); self.warnings.push(message.into());
} }
pub fn error(&mut self, message: impl Into<String>) { pub fn error(&mut self, message: impl Into<Message>) {
self.errors.push(message.into()); self.errors.push(message.into());
} }
} }
@@ -454,8 +457,12 @@ pub struct Report {
pub inputs: Vec<InputReport>, pub inputs: Vec<InputReport>,
pub summary: SummaryReport, pub summary: SummaryReport,
/// Run-level failures that are not attributable to one input. /// Run-level failures that are not attributable to one input.
pub errors: Vec<String>, pub errors: Vec<Message>,
pub duration_ms: u64, pub duration_ms: u64,
/// The run was cancelled before every input was processed. Only a front
/// end can cancel, so the CLI's JSON never carries this field.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub cancelled: bool,
} }
impl Report { impl Report {
@@ -469,64 +476,75 @@ impl Report {
}) })
} }
/// Plain summary in the same shape as [`crate::job::Summary::line`]. /// Plain English 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()) self.summary_line_in(crate::ui::Palette::plain(), Lang::En)
} }
/// Console summary with colors for actual nonzero outcomes. /// Console summary in the process language, with colors for actual
/// nonzero outcomes.
pub fn summary_line_with_palette(&self, palette: crate::ui::Palette) -> String { pub fn summary_line_with_palette(&self, palette: crate::ui::Palette) -> String {
use crate::ui::{Tone, count}; self.summary_line_in(palette, senbei_i18n::current())
}
/// The summary line in `lang`.
pub fn summary_line_in(&self, palette: crate::ui::Palette, lang: Lang) -> String {
let s = &self.summary; let s = &self.summary;
let mut line = format!( crate::ui::summary_line(
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata", palette,
count(palette, s.recovered, Tone::Success), lang,
count(palette, s.skipped, Tone::Muted), [
count(palette, s.errors, Tone::Error), s.recovered,
count(palette, s.suspect, Tone::Warning), s.skipped,
count(palette, s.metadata, Tone::Success) s.errors,
); s.suspect,
if s.packages > 0 { s.metadata,
line.push_str(&format!( s.packages,
" · {} packages", ],
palette.paint(Tone::Value, s.packages) )
));
}
line
} }
/// Plain human-readable rendering, independent of the destination terminal. /// Plain English 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()) self.render_text_in(crate::ui::Palette::plain(), Lang::En)
} }
/// Human-readable rendering with an explicit console palette. Report data /// Console rendering in the process language. Report data and JSON remain
/// and JSON remain unstyled; callers select the destination's color policy. /// unstyled; callers select the destination's color policy.
pub fn render_text_with_palette(&self, palette: crate::ui::Palette) -> String { pub fn render_text_with_palette(&self, palette: crate::ui::Palette) -> String {
self.render_text_in(palette, senbei_i18n::current())
}
/// Human-readable rendering in `lang`. Only the summary lines are
/// translated; structural research evidence stays English.
pub fn render_text_in(&self, palette: crate::ui::Palette, lang: Lang) -> String {
use crate::ui::Tone; 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!(
"{}: {} probed non-targets · {} walk errors · {} probe errors\n", "{}: {}\n",
palette.paint(Tone::Heading, "scan"), palette.paint(Tone::Heading, Cli::ReportScanHeading.localize(lang)),
scan.non_target_skipped, Cli::ReportScan {
scan.walk_errors, skipped: scan.non_target_skipped,
scan.probe_errors walk_errors: scan.walk_errors,
probe_errors: scan.probe_errors,
}
.localize(lang)
)); ));
if scan.walk_errors > 0 || scan.probe_errors > 0 { if scan.walk_errors > 0 || scan.probe_errors > 0 {
text.push_str(&format!("{}: analysis is incomplete; some directory entries or selected files could not be examined\n", palette.paint(Tone::Warning, "warning"))); text.push_str(&format!(
"{}: {}\n",
palette.paint(Tone::Warning, Cli::Warning.localize(lang)),
Cli::ReportScanIncomplete.localize(lang)
));
} }
} }
for input in &self.inputs { for input in &self.inputs {
text.push_str(&text::render_input(input, palette)); text.push_str(&text::render_input(input, palette, lang));
} }
for error in &self.errors { for error in &self.errors {
text.push_str(&format!( text.push_str(&crate::ui::error_lines(palette, lang, error));
"{}: {error}\n",
palette.paint(Tone::Error, "error")
));
} }
text text
} }
@@ -539,7 +557,10 @@ pub struct Collector {
scan: Option<ScanReport>, scan: Option<ScanReport>,
inputs: Vec<InputReport>, inputs: Vec<InputReport>,
summary: SummaryReport, summary: SummaryReport,
errors: Vec<String>, errors: Vec<Message>,
observer: Option<Arc<dyn crate::observe::RunObserver>>,
cancel: Option<crate::observe::CancelToken>,
cancelled: bool,
} }
impl Collector { impl Collector {
@@ -551,9 +572,41 @@ impl Collector {
inputs: Vec::new(), inputs: Vec::new(),
summary: SummaryReport::default(), summary: SummaryReport::default(),
errors: Vec::new(), errors: Vec::new(),
observer: None,
cancel: None,
cancelled: false,
} }
} }
/// Tell `observer` about each input as the run reaches and finishes it.
pub fn with_observer(mut self, observer: Arc<dyn crate::observe::RunObserver>) -> Self {
self.observer = Some(observer);
self
}
/// Stop the run at the next input once `cancel` is set.
pub fn with_cancel(mut self, cancel: crate::observe::CancelToken) -> Self {
self.cancel = Some(cancel);
self
}
pub(crate) fn observer(&self) -> Option<&Arc<dyn crate::observe::RunObserver>> {
self.observer.as_ref()
}
/// True once cancellation was requested. The report then records that the
/// run stopped early.
pub(crate) fn should_stop(&mut self) -> bool {
if self
.cancel
.as_ref()
.is_some_and(crate::observe::CancelToken::is_cancelled)
{
self.cancelled = true;
}
self.cancelled
}
pub fn mode(&self) -> Mode { pub fn mode(&self) -> Mode {
self.mode self.mode
} }
@@ -585,9 +638,9 @@ impl Collector {
// Research inspection and dry runs keep their actual recovery // Research inspection and dry runs keep their actual recovery
// outcomes, but never advertise temporary artifacts as outputs. // outcomes, but never advertise temporary artifacts as outputs.
let discarded = if self.mode == Mode::Inspect { let discarded = if self.mode == Mode::Inspect {
"research inspection: no output file was retained" Msg::OutputNotRetained
} else { } else {
"dry run: the produced output was discarded" Msg::DryRunDiscarded
}; };
if !input.outputs.is_empty() { if !input.outputs.is_empty() {
// The produced byte count is a real result of the attempt even // The produced byte count is a real result of the attempt even
@@ -605,7 +658,7 @@ impl Collector {
for stage in &mut input.stages { for stage in &mut input.stages {
if stage.stage == Stage::OutputWrite { if stage.stage == Stage::OutputWrite {
stage.status = StageStatus::Skipped; stage.status = StageStatus::Skipped;
stage.detail = Some(discarded.to_owned()); stage.detail = Some(Message::new(discarded.clone()));
} }
} }
if !input if !input
@@ -650,6 +703,9 @@ impl Collector {
InputStatus::Skipped => self.summary.skipped += 1, InputStatus::Skipped => self.summary.skipped += 1,
InputStatus::Error => self.summary.errors += 1, InputStatus::Error => self.summary.errors += 1,
} }
if let Some(observer) = &self.observer {
observer.input_finished(&input);
}
self.inputs.push(input); self.inputs.push(input);
} }
@@ -658,7 +714,7 @@ impl Collector {
} }
/// Record a run-level failure that is not attributable to one input. /// Record a run-level failure that is not attributable to one input.
pub fn push_error(&mut self, message: impl Into<String>) { pub fn push_error(&mut self, message: impl Into<Message>) {
self.errors.push(message.into()); self.errors.push(message.into());
} }
@@ -675,6 +731,7 @@ impl Collector {
summary: self.summary, summary: self.summary,
errors: self.errors, errors: self.errors,
duration_ms: self.started.elapsed().as_millis() as u64, duration_ms: self.started.elapsed().as_millis() as u64,
cancelled: self.cancelled,
} }
} }
} }
@@ -715,17 +772,17 @@ pub(crate) fn android_recovered_profile() -> ProtectionProfile {
/// ///
/// Recognition is inherited from the scan probe that selected the file; the /// Recognition is inherited from the scan probe that selected the file; the
/// route is recorded as failed with the error that stopped it. /// route is recorded as failed with the error that stopped it.
pub(crate) fn android_failed_profile(error: &str) -> ProtectionProfile { pub(crate) fn android_failed_profile(error: &Message) -> ProtectionProfile {
let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::android(None)); let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::android(None));
profile.recognition = RecognitionStatus::Recognized; profile.recognition = RecognitionStatus::Recognized;
profile.candidates = vec![senbei_engine::LayoutAttempt { profile.candidates = vec![senbei_engine::LayoutAttempt {
layout: LayoutKind::AndroidStaged, layout: LayoutKind::AndroidStaged,
outcome: AttemptOutcome::Failed, outcome: AttemptOutcome::Failed,
warnings: Vec::new(), warnings: Vec::new(),
errors: vec![error.to_owned()], errors: vec![error.clone()],
}]; }];
profile.recovery = RecoveryStatus::Failed; profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_owned()); profile.push_error(error.clone());
profile profile
} }
@@ -773,7 +830,7 @@ pub(crate) fn metadata_unchanged_profile(
pub(crate) fn metadata_failed_profile( pub(crate) fn metadata_failed_profile(
identity: Option<senbei_metadata::MetadataIdentity>, identity: Option<senbei_metadata::MetadataIdentity>,
route: LayoutKind, route: LayoutKind,
error: &str, error: &Message,
) -> ProtectionProfile { ) -> ProtectionProfile {
let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata( let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata(
identity.map(|identity| identity.raw_version), identity.map(|identity| identity.raw_version),
@@ -785,10 +842,10 @@ pub(crate) fn metadata_failed_profile(
layout: route, layout: route,
outcome: AttemptOutcome::Failed, outcome: AttemptOutcome::Failed,
warnings: Vec::new(), warnings: Vec::new(),
errors: vec![error.to_owned()], errors: vec![error.clone()],
}]; }];
profile.recovery = RecoveryStatus::Failed; profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_owned()); profile.push_error(error.clone());
profile.static_validation = ValidationStatus::NotRun; profile.static_validation = ValidationStatus::NotRun;
profile profile
} }
@@ -812,7 +869,7 @@ mod tests {
let profile = metadata_failed_profile( let profile = metadata_failed_profile(
senbei_metadata::identify(&header), senbei_metadata::identify(&header),
LayoutKind::MetadataStructural, LayoutKind::MetadataStructural,
"transform did not validate", &"transform did not validate".into(),
); );
assert_eq!(profile.observed.metadata_version, Some(version)); assert_eq!(profile.observed.metadata_version, Some(version));
assert_eq!(profile.recognition, RecognitionStatus::Blocked); assert_eq!(profile.recognition, RecognitionStatus::Blocked);
@@ -932,7 +989,7 @@ mod tests {
entry.analysis_incomplete = true; entry.analysis_incomplete = true;
entry entry
.errors .errors
.push("resource ceiling prevented restoration".to_owned()); .push("resource ceiling prevented restoration".into());
input.entries.push(entry); input.entries.push(entry);
let mut collector = Collector::new(Mode::Inspect); let mut collector = Collector::new(Mode::Inspect);
collector.push(input); collector.push(input);
+264 -165
View File
@@ -1,8 +1,14 @@
//! Human-readable research reports. JSON retains the same underlying evidence. //! Human-readable research reports. JSON retains the same underlying evidence.
//!
//! The summary lines of an input (target, recognition, routes, stages, and
//! findings) follow the reader's language. The structural research sections
//! (PE layout, recovery trace, Android and metadata evidence) are technical
//! dumps and stay English, like the JSON they mirror.
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use senbei_engine::windows::{ResearchTrace, TraceValue, WindowsInspection}; use senbei_engine::windows::{ResearchTrace, TraceValue, WindowsInspection};
use senbei_i18n::{Cli, Lang, Localize, Message, Term};
use serde::Serialize; use serde::Serialize;
use serde_json::Value; use serde_json::Value;
@@ -12,15 +18,26 @@ use crate::ui::{Painted, Palette, Tone};
struct Text { struct Text {
contents: String, contents: String,
palette: Palette, palette: Palette,
lang: Lang,
} }
impl Text { impl Text {
#[cfg(test)]
fn new(palette: Palette) -> Self { fn new(palette: Palette) -> Self {
Self::in_language(palette, Lang::En)
}
fn in_language(palette: Palette, lang: Lang) -> Self {
Self { Self {
contents: String::new(), contents: String::new(),
palette, palette,
lang,
} }
} }
fn say(&self, line: Cli) -> String {
line.localize(self.lang).into_owned()
}
} }
impl Write for Text { impl Write for Text {
@@ -34,8 +51,12 @@ fn status(palette: Palette, value: &impl Serialize) -> Painted<String> {
} }
fn status_text(palette: Palette, value: String) -> Painted<String> { fn status_text(palette: Palette, value: String) -> Painted<String> {
let normalized = value.replace('_', " "); palette.paint(tone_of(&value), value)
let tone = match normalized.as_str() { }
/// The tone of a report value, judged by its English meaning.
fn tone_of(value: &str) -> Tone {
match value.replace('_', " ").as_str() {
"ok" | "clean" | "succeeded" | "restored" | "unchanged" | "accepted" | "matched" "ok" | "clean" | "succeeded" | "restored" | "unchanged" | "accepted" | "matched"
| "validated" => Tone::Success, | "validated" => Tone::Success,
"error" | "failed" | "unreadable" | "rejected" => Tone::Error, "error" | "failed" | "unreadable" | "rejected" => Tone::Error,
@@ -45,8 +66,7 @@ fn status_text(palette: Palette, value: String) -> Painted<String> {
"skipped" | "not run" | "not attempted" | "unavailable" | "absent" | "duplicate" "skipped" | "not run" | "not attempted" | "unavailable" | "absent" | "duplicate"
| "not recognized" => Tone::Muted, | "not recognized" => Tone::Muted,
_ => Tone::Value, _ => Tone::Value,
}; }
palette.paint(tone, value)
} }
fn label(value: &impl Serialize) -> String { fn label(value: &impl Serialize) -> String {
@@ -57,6 +77,23 @@ fn label(value: &impl Serialize) -> String {
} }
} }
/// [`label`] in `lang`, for the values the catalog names.
fn term(lang: Lang, value: &impl Serialize) -> String {
if let Ok(Value::String(wire)) = serde_json::to_value(value)
&& let Some(term) = Term::from_value(&wire)
{
return term.localize(lang).into_owned();
}
label(value)
}
/// [`status`] in the reader's language: toned by the English value.
fn term_status(text: &Text, value: &impl Serialize) -> String {
text.palette
.paint(tone_of(&label(value)), term(text.lang, value))
.to_string()
}
fn hex<T: Into<u64>>(palette: Palette, value: Option<T>) -> Painted<String> { fn hex<T: Into<u64>>(palette: Palette, value: Option<T>) -> Painted<String> {
let tone = if value.is_some() { let tone = if value.is_some() {
Tone::Value Tone::Value
@@ -83,22 +120,72 @@ fn diagnostic(text: &mut Text, indent: &str, kind: &str, message: &str) {
} }
} }
pub(super) fn render_input(input: &InputReport, palette: Palette) -> String { /// How a finding is labelled in the summary part of a report.
let mut text = Text::new(palette); #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
let _ = writeln!(text, "{}", palette.paint(Tone::Heading, &input.path)); enum Finding {
if input.analysis_incomplete { Warning,
Error,
Reason,
Detail,
}
impl Finding {
fn label(self) -> Cli {
match self {
Self::Warning => Cli::DiagnosticWarning,
Self::Error => Cli::DiagnosticError,
Self::Reason => Cli::DiagnosticReason,
Self::Detail => Cli::DiagnosticDetail,
}
}
fn tone(self) -> Tone {
match self {
Self::Error => Tone::Error,
Self::Warning | Self::Reason => Tone::Warning,
Self::Detail => Tone::Muted,
}
}
}
/// A finding in the reader's language. When the translation does not show
/// everything the English said, the English follows on its own muted line.
fn finding(text: &mut Text, indent: &str, kind: Finding, message: &Message) {
let palette = text.palette;
let label = text.say(kind.label());
for line in message.localized(text.lang).lines() {
let _ = writeln!( let _ = writeln!(
text, text,
" {}: I/O, resource limits or infrastructure prevented the requested work", "{indent}{}: {line}",
palette.paint(Tone::Error, "analysis incomplete") palette.paint(kind.tone(), &label)
); );
} }
if let Some(source) = &input.source { if let Some(english) = message.detail(text.lang) {
let _ = writeln!( let label = text.say(Cli::DiagnosticEnglish);
text, for line in english.lines() {
" source: {} bytes (0x{:X})", let _ = writeln!(
source.size, source.size text,
"{indent} {}",
palette.paint(Tone::Muted, format!("{label}: {line}"))
);
}
}
}
pub(super) fn render_input(input: &InputReport, palette: Palette, lang: Lang) -> String {
let mut text = Text::in_language(palette, lang);
let _ = writeln!(text, "{}", palette.paint(Tone::Heading, &input.path));
if input.analysis_incomplete {
let line = format!(
" {}: {}",
palette.paint(Tone::Error, text.say(Cli::AnalysisIncomplete)),
text.say(Cli::AnalysisIncompleteInput)
); );
let _ = writeln!(text, "{line}");
}
if let Some(source) = &input.source {
let line = text.say(Cli::Source { size: source.size });
let _ = writeln!(text, " {line}");
let _ = writeln!( let _ = writeln!(
text, text,
" SHA-256: {}", " SHA-256: {}",
@@ -107,72 +194,73 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
} }
if let Some(profile) = &input.profile { if let Some(profile) = &input.profile {
let target = &profile.observed; let target = &profile.observed;
let _ = writeln!( let line = text.say(Cli::Target {
text, platform: term(lang, &target.platform),
" target: {} · {} · {}", format: target
label(&target.platform),
target
.format .format
.as_ref() .as_ref()
.map(label) .map(|format| term(lang, format))
.unwrap_or_else(|| "format unavailable".to_owned()), .unwrap_or_else(|| text.say(Cli::FormatUnavailable)),
target kind: target
.kind .kind
.as_ref() .as_ref()
.map(label) .map(|kind| term(lang, kind))
.unwrap_or_else(|| "kind not applicable or unavailable".to_owned()) .unwrap_or_else(|| text.say(Cli::KindUnavailable)),
); });
let _ = writeln!( let _ = writeln!(text, " {line}");
text, let line = text.say(Cli::ProtectionRecognition {
" protection recognition: {}", status: term_status(&text, &profile.recognition),
status(palette, &profile.recognition) });
); let _ = writeln!(text, " {line}");
if !profile.evidence.is_empty() { if !profile.evidence.is_empty() {
let evidence = profile let evidence = profile
.evidence .evidence
.iter() .iter()
.map(label) .map(|evidence| term(lang, evidence))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
let _ = writeln!(text, " evidence: {evidence}"); let line = text.say(Cli::Evidence { evidence });
let _ = writeln!(text, " {line}");
} }
for candidate in &profile.candidates { for candidate in &profile.candidates {
let _ = writeln!( let line = text.say(Cli::Route {
text, route: palette
" route {}: {}", .paint(Tone::Label, term(lang, &candidate.layout))
palette.paint(Tone::Label, label(&candidate.layout)), .to_string(),
status(palette, &candidate.outcome) outcome: term_status(&text, &candidate.outcome),
); });
let _ = writeln!(text, " {line}");
for message in &candidate.warnings { for message in &candidate.warnings {
diagnostic(&mut text, " ", "warning", message); finding(&mut text, " ", Finding::Warning, message);
} }
for message in &candidate.errors { for message in &candidate.errors {
diagnostic(&mut text, " ", "reason", message); finding(&mut text, " ", Finding::Reason, message);
} }
} }
if let Some(selected) = profile.selected { if let Some(selected) = profile.selected {
let _ = writeln!( let line = text.say(Cli::SelectedRoute {
text, route: palette
" selected route: {}", .paint(Tone::Success, term(lang, &selected))
palette.paint(Tone::Success, label(&selected)) .to_string(),
); });
let _ = writeln!(text, " {line}");
} }
let _ = writeln!( let line = text.say(Cli::StaticRecovery {
text, status: term_status(&text, &profile.recovery),
" static recovery: {}", });
status(palette, &profile.recovery) let _ = writeln!(text, " {line}");
); let line = text.say(Cli::OutputValidation {
let _ = writeln!( status: term_status(&text, &profile.static_validation),
text, });
" output static validation: {}", let _ = writeln!(text, " {line}");
status(palette, &profile.static_validation)
);
} }
if let Some(companion) = &input.companion { if let Some(companion) = &input.companion {
let line = text.say(Cli::Companion {
state: term_status(&text, &companion.state),
});
let _ = writeln!( let _ = writeln!(
text, text,
" companion: {}{}", " {line}{}",
status(palette, &companion.state),
companion companion
.path .path
.as_ref() .as_ref()
@@ -180,27 +268,24 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
.unwrap_or_default() .unwrap_or_default()
); );
if let Some(source) = &companion.source { if let Some(source) = &companion.source {
let _ = writeln!( let line = text.say(Cli::CompanionIdentity {
text, size: source.size,
" {} bytes · SHA-256 {}", sha256: source.sha256.clone(),
source.size, source.sha256 });
); let _ = writeln!(text, " {line}");
} }
if let Some(detail) = &companion.detail { if let Some(detail) = &companion.detail {
diagnostic(&mut text, " ", "detail", detail); finding(&mut text, " ", Finding::Detail, detail);
} }
} }
if let Some(research) = &input.research { if let Some(research) = &input.research {
let _ = writeln!( let line = text.say(Cli::InputView {
text, view: term(lang, &research.input_view),
" analysis input view: {}", });
label(&research.input_view) let _ = writeln!(text, " {line}");
);
if research.input_view == super::ResearchInputView::SplicedCompanion { if research.input_view == super::ResearchInputView::SplicedCompanion {
let _ = writeln!( let line = text.say(Cli::InputViewSplicedNote);
text, let _ = writeln!(text, " {line}");
" file offsets below 0x1000 address the stub; offsets at/above 0x1000 address companion offset (file offset - 0x1000)"
);
} }
render_windows(&mut text, "protected input", &research.input); render_windows(&mut text, "protected input", &research.input);
render_trace(&mut text, &research.trace); render_trace(&mut text, &research.trace);
@@ -227,67 +312,69 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
} }
} }
if let Some(metadata) = &input.metadata { if let Some(metadata) = &input.metadata {
let _ = writeln!( let identity = text.say(Cli::MetadataIdentity {
text, version: metadata.raw_version,
" IL2CPP metadata version: {} · layout definition {}", layout: term(lang, &metadata.layout),
metadata.raw_version, });
label(&metadata.layout) let _ = writeln!(text, " {identity}");
); let capabilities = &metadata.capabilities;
let _ = writeln!( for line in [
text, Cli::SeededTokens {
" seeded method tokens: {}", value: capabilities.seeded_method_tokens,
metadata.capabilities.seeded_method_tokens },
); Cli::StructuralTokens {
let _ = writeln!( value: capabilities.structural_method_tokens,
text, },
" structural method tokens: {}", Cli::MethodIndexRestore {
metadata.capabilities.structural_method_tokens value: capabilities.method_index_restore,
); context: capabilities.method_index_requires_context,
let _ = writeln!( },
text, ] {
" method-index restoration: {} · application context required: {}", let line = text.say(line);
metadata.capabilities.method_index_restore, let _ = writeln!(text, " {line}");
metadata.capabilities.method_index_requires_context }
);
} }
if let Some(container) = &input.container { if let Some(container) = &input.container {
let _ = writeln!( let line = text.say(Cli::Container {
text, kind: container.kind.clone(),
" container: {} · {} entries · {} manifests", entries: container.entry_count,
container.kind, manifests: container.manifests.len(),
container.entry_count, });
container.manifests.len() let _ = writeln!(text, " {line}");
);
for manifest in &container.manifests { for manifest in &container.manifests {
let _ = writeln!( let line = text.say(Cli::Manifest {
text, source: manifest.source.clone(),
" manifest {} → {} {}", package: manifest
manifest.source, .package
manifest.package.as_deref().unwrap_or("<unnamed>"), .clone()
manifest.version.as_deref().unwrap_or("") .unwrap_or_else(|| text.say(Cli::Unnamed)),
); version: manifest.version.clone().unwrap_or_default(),
});
let _ = writeln!(text, " {line}");
} }
for entry in &container.candidate_entries { for entry in &container.candidate_entries {
let _ = writeln!(text, " candidate: {entry}"); let line = text.say(Cli::Candidate {
entry: entry.clone(),
});
let _ = writeln!(text, " {line}");
} }
} }
if let Some(research) = &input.android_research { if let Some(research) = &input.android_research {
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!( let heading = text.say(Cli::MetadataEvidence);
text, let _ = writeln!(text, " {}:", palette.paint(Tone::Heading, heading));
" {}:",
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 line = text.say(Cli::Entry {
name: palette.paint(Tone::Label, &entry.name).to_string(),
status: term_status(&text, &entry.status),
});
let _ = writeln!( let _ = writeln!(
text, text,
" entry {}: {}{}", " {line}{}",
palette.paint(Tone::Label, &entry.name),
status(palette, &entry.status),
entry entry
.output .output
.as_ref() .as_ref()
@@ -295,90 +382,102 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
.unwrap_or_default() .unwrap_or_default()
); );
if entry.analysis_incomplete { if entry.analysis_incomplete {
let _ = writeln!( let line = format!(
text, " {}: {}",
" {}: requested entry analysis could not finish", palette.paint(Tone::Error, text.say(Cli::AnalysisIncomplete)),
palette.paint(Tone::Error, "analysis incomplete") text.say(Cli::AnalysisIncompleteEntry)
); );
let _ = writeln!(text, "{line}");
} }
if let Some(layout) = entry.layout { if let Some(layout) = entry.layout {
let _ = writeln!(text, " route: {}", label(&layout)); let line = text.say(Cli::EntryRoute {
route: term(lang, &layout),
});
let _ = writeln!(text, " {line}");
} }
if let Some(version) = entry.metadata_version { if let Some(version) = entry.metadata_version {
let _ = writeln!(text, " metadata version: {version}"); let line = text.say(Cli::EntryMetadataVersion { version });
let _ = writeln!(text, " {line}");
} }
if let Some(remapped) = entry.remapped { if let Some(remapped) = entry.remapped {
let _ = writeln!(text, " remapped method fields: {remapped}"); let line = text.say(Cli::EntryRemapped { remapped });
let _ = writeln!(text, " {line}");
} }
for source in &entry.provenance { for source in &entry.provenance {
let _ = writeln!(text, " module context source: {source}"); let line = text.say(Cli::ModuleContextSource {
source: source.clone(),
});
let _ = writeln!(text, " {line}");
} }
for message in &entry.warnings { for message in &entry.warnings {
diagnostic(&mut text, " ", "warning", message); finding(&mut text, " ", Finding::Warning, message);
} }
for message in &entry.errors { for message in &entry.errors {
diagnostic(&mut text, " ", "error", message); finding(&mut text, " ", Finding::Error, message);
} }
if let Some(research) = &entry.android_research { if let Some(research) = &entry.android_research {
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!( let heading = text.say(Cli::MetadataEvidence);
text, let _ = writeln!(text, " {}:", palette.paint(Tone::Heading, heading));
" {}:",
palette.paint(Tone::Heading, "metadata transform evidence")
);
render_tree(&mut text, " ", research); render_tree(&mut text, " ", research);
} }
} }
for source in &input.provenance { for source in &input.provenance {
let _ = writeln!(text, " module context source: {source}"); let line = text.say(Cli::ModuleContextSource {
source: source.clone(),
});
let _ = writeln!(text, " {line}");
} }
for stage in &input.stages { for stage in &input.stages {
let line = text.say(Cli::StageLine {
stage: palette
.paint(Tone::Label, term(lang, &stage.stage))
.to_string(),
status: term_status(&text, &stage.status),
});
let _ = writeln!( let _ = writeln!(
text, text,
" stage {}: {}{}", " {line}{}",
palette.paint(Tone::Label, label(&stage.stage)),
status(palette, &stage.status),
stage stage
.duration_ms .duration_ms
.map(|elapsed| format!(" · {elapsed} ms")) .map(|elapsed| format!(" · {elapsed} ms"))
.unwrap_or_default() .unwrap_or_default()
); );
if let Some(detail) = &stage.detail { if let Some(detail) = &stage.detail {
diagnostic(&mut text, " ", "detail", detail); finding(&mut text, " ", Finding::Detail, detail);
} }
} }
// The profile repeats input-level findings; each is shown once.
let mut seen = std::collections::BTreeSet::new(); let mut seen = std::collections::BTreeSet::new();
for (kind, messages) in [("warning", &input.warnings), ("error", &input.errors)] { let mut findings = vec![
for message in messages { (Finding::Warning, &input.warnings),
if seen.insert((kind, message.as_str())) { (Finding::Error, &input.errors),
diagnostic(&mut text, " ", kind, message); ];
}
}
}
if let Some(profile) = &input.profile { if let Some(profile) = &input.profile {
for (kind, messages) in [("warning", &profile.warnings), ("error", &profile.errors)] { findings.push((Finding::Warning, &profile.warnings));
for message in messages { findings.push((Finding::Error, &profile.errors));
if seen.insert((kind, message.as_str())) { }
diagnostic(&mut text, " ", kind, message); for (kind, messages) in findings {
} for message in messages {
if seen.insert((kind, message.text())) {
finding(&mut text, " ", kind, message);
} }
} }
} }
if let Some(recovered) = &input.recovered { if let Some(recovered) = &input.recovered {
let _ = writeln!( let line = text.say(Cli::Recovered {
text, size: recovered.size,
" recovered: {} bytes · SHA-256 {}", sha256: recovered.sha256.clone(),
recovered.size, recovered.sha256 });
); let _ = writeln!(text, " {line}");
} }
let _ = writeln!( let line = text.say(Cli::InspectionStatus {
text, status: term_status(&text, &input.status),
" inspection status: {} · {} ms", ms: input.duration_ms,
status(palette, &input.status), });
input.duration_ms let _ = writeln!(text, " {line}");
);
text.contents text.contents
} }
@@ -921,8 +1020,8 @@ 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, Palette::plain()); let text = render_input(&input, Palette::plain(), Lang::En);
let colored = render_input(&input, Palette::colored()); let colored = render_input(&input, Palette::colored(), Lang::En);
assert!(colored.contains('\x1b')); assert!(colored.contains('\x1b'));
assert_eq!(strip_styles(&colored), text); assert_eq!(strip_styles(&colored), text);
for fact in [ for fact in [
@@ -991,8 +1090,8 @@ 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, Palette::plain()); let text = render_input(&input, Palette::plain(), Lang::En);
let colored = render_input(&input, Palette::colored()); let colored = render_input(&input, Palette::colored(), Lang::En);
assert!(colored.contains('\x1b')); assert!(colored.contains('\x1b'));
assert_eq!(strip_styles(&colored), text); assert_eq!(strip_styles(&colored), text);
for fact in [ for fact in [
+135 -9
View File
@@ -1,6 +1,7 @@
use indicatif::{ProgressBar, ProgressStyle}; use indicatif::{ProgressBar, ProgressStyle};
use owo_colors::Style; use owo_colors::Style;
use senbei_engine::{IntegrityReport, Kind}; use senbei_engine::{IntegrityReport, Kind};
use senbei_i18n::{Cli, Lang, Localize, Message, Step};
use std::cell::Cell; use std::cell::Cell;
use std::fmt::{self, Display}; use std::fmt::{self, Display};
use std::io::IsTerminal; use std::io::IsTerminal;
@@ -101,6 +102,111 @@ pub(crate) fn count(palette: Palette, value: usize, nonzero: Tone) -> Painted<us
palette.paint(if value == 0 { Tone::Muted } else { nonzero }, value) palette.paint(if value == 0 { Tone::Muted } else { nonzero }, value)
} }
/// The run summary in `lang`: unpacked, skipped, errors, suspect, metadata,
/// and packages (shown only when nonzero), each colored when nonzero.
pub(crate) fn summary_line(
palette: Palette,
lang: Lang,
[unpacked, skipped, errors, suspect, metadata, packages]: [usize; 6],
) -> String {
let mut line = Cli::Summary {
unpacked: count(palette, unpacked, Tone::Success).to_string(),
skipped: count(palette, skipped, Tone::Muted).to_string(),
errors: count(palette, errors, Tone::Error).to_string(),
suspect: count(palette, suspect, Tone::Warning).to_string(),
metadata: count(palette, metadata, Tone::Success).to_string(),
}
.localize(lang)
.into_owned();
if packages > 0 {
line.push_str(
&Cli::SummaryPackages {
packages: palette.paint(Tone::Value, packages).to_string(),
}
.localize(lang),
);
}
line
}
/// The muted line that shows the English a translated message came from.
fn english_line(palette: Palette, lang: Lang, english: &str) -> String {
palette
.paint(
Tone::Muted,
format!("{}: {english}", Cli::DiagnosticEnglish.localize(lang)),
)
.to_string()
}
/// `error: <message>` in `lang`, newline-terminated. When the translation
/// does not show everything the English said, the English follows.
pub(crate) fn error_lines(palette: Palette, lang: Lang, message: &Message) -> String {
let mut lines = format!(
"{}: {}\n",
palette.paint(Tone::Error, Cli::Error.localize(lang)),
message.localized(lang)
);
if let Some(english) = message.detail(lang) {
lines.push_str(&format!(" {}\n", english_line(palette, lang, english)));
}
lines
}
/// Print `error: <message>` to stderr in the process language.
pub fn print_error(message: &Message) {
eprint!(
"{}",
error_lines(Palette::stderr(), senbei_i18n::current(), message)
);
}
/// Print `error: <error chain>` to stderr in the process language.
pub fn print_anyhow(error: &anyhow::Error) {
print_error(&crate::message::of_error(error));
}
/// Print `error: <what>: <error chain>` to stderr in the process language.
pub(crate) fn print_error_about(what: Cli, error: &anyhow::Error) {
let lang = senbei_i18n::current();
let palette = Palette::stderr();
let message = crate::message::of_error(error);
eprintln!(
"{}: {}: {}",
palette.paint(Tone::Error, Cli::Error.localize(lang)),
what.localize(lang),
message.localized(lang)
);
if let Some(english) = message.detail(lang) {
eprintln!(" {}", english_line(palette, lang, english));
}
}
/// The verbose `Write to <dest>` line after an output was written, with the
/// destination colored when `painted`. A run with an observer receives it as
/// a progress event instead.
pub(crate) fn write_to(dest: &Path, painted: bool) {
let event = senbei_engine::progress::Event::Step {
step: Step::WriteTo {
dest: dest.display().to_string(),
},
position: None,
};
if !senbei_engine::progress::emit(&event) {
let dest = if painted {
Palette::stdout()
.paint(Tone::Value, dest.display())
.to_string()
} else {
dest.display().to_string()
};
println!(
"{}",
Step::WriteTo { dest }.localize(senbei_i18n::current())
);
}
}
fn color_enabled(mode: ColorMode, terminal: bool, no_color: bool, dumb: bool) -> bool { fn color_enabled(mode: ColorMode, terminal: bool, no_color: bool, dumb: bool) -> bool {
match mode { match mode {
ColorMode::Auto => terminal && !no_color && !dumb, ColorMode::Auto => terminal && !no_color && !dumb,
@@ -220,12 +326,15 @@ pub fn metadata(bar: &ProgressBar, quiet: bool, rel: &Path, remapped: usize, des
return; return;
} }
let palette = Palette::stdout(); let palette = Palette::stdout();
let line = Cli::MetadataLine {
rel: palette.paint(Tone::Label, rel.display()).to_string(),
dest: palette.paint(Tone::Value, dest.display()).to_string(),
remapped: palette.paint(Tone::Value, remapped).to_string(),
};
let msg = format!( let msg = format!(
"{} metadata {} -> {} ({} method fields remapped)", "{} {}",
palette.paint(Tone::Success, "✓"), palette.paint(Tone::Success, "✓"),
palette.paint(Tone::Label, rel.display()), line.localize(senbei_i18n::current())
palette.paint(Tone::Value, dest.display()),
palette.paint(Tone::Value, remapped)
); );
bar.suspend(|| println!("{msg}")); bar.suspend(|| println!("{msg}"));
} }
@@ -236,11 +345,17 @@ pub fn err(bar: &ProgressBar, quiet: bool, rel: &Path, e: &anyhow::Error) {
return; return;
} }
let palette = Palette::stderr(); let palette = Palette::stderr();
let msg = format!( let lang = senbei_i18n::current();
"{} {} {e:#}", let message = crate::message::of_error(e);
let mut msg = format!(
"{} {} {}",
palette.paint(Tone::Error, "✗"), palette.paint(Tone::Error, "✗"),
palette.paint(Tone::Label, rel.display()) palette.paint(Tone::Label, rel.display()),
message.localized(lang)
); );
if let Some(english) = message.detail(lang) {
msg.push_str(&format!("\n {}", english_line(palette, lang, english)));
}
bar.suspend(|| eprintln!("{msg}")); bar.suspend(|| eprintln!("{msg}"));
} }
@@ -251,16 +366,27 @@ pub fn suspect(bar: &ProgressBar, quiet: bool, rel: &Path, report: &IntegrityRep
return; return;
} }
let palette = Palette::stderr(); let palette = Palette::stderr();
let lang = senbei_i18n::current();
let msg = format!( let msg = format!(
"{} {} {}: {}", "{} {} {}: {}",
palette.paint(Tone::Warning, "!"), palette.paint(Tone::Warning, "!"),
palette.paint(Tone::Label, rel.display()), palette.paint(Tone::Label, rel.display()),
palette.paint(Tone::Warning, "integrity check failed"), palette.paint(Tone::Warning, Cli::IntegrityFailed.localize(lang)),
report.issues.join("; ") issues(report, lang)
); );
bar.suspend(|| eprintln!("{msg}")); bar.suspend(|| eprintln!("{msg}"));
} }
/// The static check's findings in `lang`, separated as in the log.
pub(crate) fn issues(report: &IntegrityReport, lang: Lang) -> String {
report
.issues
.iter()
.map(|issue| issue.localized(lang))
.collect::<Vec<_>>()
.join("; ")
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+1 -1
View File
@@ -672,7 +672,7 @@ pub fn unpack_one_v(
} }
write_atomic(dest, &out)?; write_atomic(dest, &out)?;
if verbose { if verbose {
println!("Write to {}", dest.display()); crate::ui::write_to(dest, false);
} }
Ok((kind, report)) Ok((kind, report))
} }
+9
View File
@@ -453,6 +453,7 @@ dependencies = [
"memmap2", "memmap2",
"senbei-crypto", "senbei-crypto",
"senbei-elf", "senbei-elf",
"senbei-i18n",
"senbei-pe", "senbei-pe",
"serde", "serde",
"serde_json", "serde_json",
@@ -461,6 +462,13 @@ dependencies = [
"thiserror", "thiserror",
] ]
[[package]]
name = "senbei-i18n"
version = "1.3.4"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "senbei-io" name = "senbei-io"
version = "1.3.4" version = "1.3.4"
@@ -473,6 +481,7 @@ dependencies = [
"senbei-crypto", "senbei-crypto",
"senbei-elf", "senbei-elf",
"senbei-engine", "senbei-engine",
"senbei-i18n",
"senbei-metadata", "senbei-metadata",
"senbei-pe", "senbei-pe",
"serde", "serde",
+6 -2
View File
@@ -157,7 +157,11 @@ fn kind_str(kind: senbei_engine::Kind) -> &'static str {
/// Copy an integrity report's findings into the parallel arrays the JS layer /// Copy an integrity report's findings into the parallel arrays the JS layer
/// reads (`issues[i]` and `severities[i]` describe the same defect). /// reads (`issues[i]` and `severities[i]` describe the same defect).
fn split_findings(report: &IntegrityReport) -> (Vec<String>, Vec<String>, bool) { fn split_findings(report: &IntegrityReport) -> (Vec<String>, Vec<String>, bool) {
let issues = report.issues.clone(); let issues: Vec<String> = report
.issues
.iter()
.map(|issue| issue.to_string())
.collect();
let mut severities = Vec::with_capacity(report.findings.len()); let mut severities = Vec::with_capacity(report.findings.len());
let mut fatal = false; let mut fatal = false;
for finding in &report.findings { for finding in &report.findings {
@@ -325,7 +329,7 @@ fn metadata_outcome(data: &[u8]) -> (Option<u32>, ProtectionProfile, MetadataTra
layout: route, layout: route,
outcome: AttemptOutcome::Failed, outcome: AttemptOutcome::Failed,
warnings: Vec::new(), warnings: Vec::new(),
errors: vec![error.to_string()], errors: vec![error.to_string().into()],
}]; }];
profile.recovery = RecoveryStatus::Failed; profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_string()); profile.push_error(error.to_string());