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 = [
"anyhow",
"senbei-engine",
"senbei-i18n",
"senbei-io",
"senbei-metadata",
"serde",
@@ -457,6 +458,7 @@ dependencies = [
"memmap2",
"senbei-crypto",
"senbei-elf",
"senbei-i18n",
"senbei-pe",
"serde",
"serde_json",
@@ -485,6 +487,7 @@ dependencies = [
"senbei-crypto",
"senbei-elf",
"senbei-engine",
"senbei-i18n",
"senbei-metadata",
"senbei-pe",
"serde",
+1
View File
@@ -38,6 +38,7 @@ thiserror = "2"
walkdir = "2"
windows = { version = "0.62", features = [
"Win32_Foundation",
"Win32_Globalization",
"Win32_System_Console",
"Win32_System_SystemInformation",
] }
+1
View File
@@ -14,6 +14,7 @@ path = "src/main.rs"
[dependencies]
senbei-io.workspace = true
senbei-engine.workspace = true
senbei-i18n.workspace = true
[dev-dependencies]
anyhow.workspace = true
+80 -106
View File
@@ -1,19 +1,26 @@
use senbei_engine::android::ResourceLimits;
use senbei_i18n::{Cli, Localize};
use senbei_io::{
job, pause, scan,
job,
message::of_error,
pause, scan,
ui::{self, ColorMode, Palette, Tone},
};
use std::num::NonZeroUsize;
use std::path::Path;
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)) {
Ok(Outcome::Run(options)) => options,
Ok(Outcome::Handled(code)) => return code,
Err(message) => {
let lang = senbei_i18n::current();
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);
}
@@ -67,7 +74,7 @@ enum Outcome {
}
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 command = Command::Unpack;
let mut subcommand: Option<String> = None;
@@ -114,11 +121,14 @@ impl Options {
}
"--out" => match args.next() {
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('-') => {
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
// positional word. `senbei inspect` therefore means the
@@ -137,9 +147,11 @@ impl Options {
}
other => {
if let Some(prev) = &path {
return Err(format!(
"multiple input paths given ('{prev}' and '{other}')"
));
return Err(Cli::MultipleInputs {
first: prev.clone(),
second: other.to_owned(),
}
.into());
}
path = Some(other.to_string());
}
@@ -150,7 +162,7 @@ impl Options {
// A subcommand with no path is a usage error; no arguments at all
// still prints help and exits 2, as before.
if let Some(subcommand) = subcommand {
return Err(format!("'{subcommand}' requires an input path"));
return Err(Cli::SubcommandNeedsPath { subcommand }.into());
}
print_help();
return Ok(Outcome::Handled(std::process::ExitCode::from(2)));
@@ -160,10 +172,10 @@ impl Options {
// rejected rather than guessed at.
if command == Command::Inspect {
if dry_run {
return Err("'inspect' writes nothing; drop --dry-run".to_owned());
return Err(Cli::InspectNoDryRun.into());
}
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
// static check and reports its verdict.
@@ -177,7 +189,7 @@ impl Options {
if dry_run {
// A dry run keeps nothing: no ordinary output directory, no log.
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;
}
@@ -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 {
Some("auto") => Ok(ColorMode::Auto),
Some("always") => Ok(ColorMode::Always),
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
.filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()))
.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
@@ -246,13 +258,10 @@ fn execute_inspect(options: &Options, path: &Path, scan_all: bool) -> u8 {
}
Err(error) => {
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());
} else if options.quiet < 2 {
eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
ui::print_anyhow(&error);
}
1
}
@@ -273,13 +282,10 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
}
Err(error) => {
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());
} else if options.quiet < 2 {
eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
ui::print_anyhow(&error);
}
1
}
@@ -350,10 +356,12 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
println!("{}", collector.finish().to_json());
} else if options.quiet < 2 {
println!("{}", summary.line_with_palette(Palette::stdout()));
let done = Cli::DoneIn {
ms: summary.duration_ms,
};
println!(
"{}",
Palette::stdout()
.paint(Tone::Muted, format!("done in {} ms", summary.duration_ms))
Palette::stdout().paint(Tone::Muted, done.localize(senbei_i18n::current()))
);
}
exit_code(&summary, options.strict_integrity)
@@ -361,13 +369,10 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
Err(error) => {
if options.machine {
let mut failed = collector;
failed.push_error(format!("{error:#}"));
failed.push_error(of_error(&error));
println!("{}", failed.finish().to_json());
} else if options.quiet < 2 {
eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
ui::print_anyhow(&error);
}
1
}
@@ -400,20 +405,27 @@ fn set_resource_limit(
limits: &mut ResourceLimits,
flag: &str,
value: Option<&str>,
) -> Result<(), String> {
let invalid = || format!("{flag} requires an unsigned integer argument");
) -> Result<(), Box<Cli>> {
let invalid = || Cli::LimitRequiresInteger {
flag: flag.to_owned(),
};
let text = value
.filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()))
.ok_or_else(invalid)?;
let value: u64 = text.parse().map_err(|_| invalid())?;
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 {
"--max-entry-mib" | "--max-total-mib" => {
let bytes = value
.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" {
limits.max_entry_bytes = bytes;
} else {
@@ -422,7 +434,12 @@ fn set_resource_limit(
}
"--max-entries" => limits.max_entries = 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(())
}
@@ -431,73 +448,28 @@ fn print_help() {
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]"
);
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();
println!(
" Android resource limits (MiB = 1048576 bytes):\n\
\x20 --max-entry-mib N single archive entry/decoded buffer/output (default {})\n\
\x20 --max-total-mib N cumulative archive bytes and per-engine task budget (default {})\n\
\x20 --max-entries N archive entries/stage-2 records (default {})\n\
\x20 --max-depth N nesting depth, root = 0 (default {})\n\
\x20 Limits are checked before extraction/allocation; they are not a peak-RSS cap.",
defaults.max_entry_bytes / (1024 * 1024),
defaults.max_total_bytes / (1024 * 1024),
defaults.max_entries,
defaults.max_depth,
);
println!(
" Exit codes: 0 success, 1 a target failed (or a suspect with\n\
\x20 --strict-integrity), 2 the command line was rejected."
);
let lang = senbei_i18n::current();
for block in [
Cli::HelpPath,
Cli::HelpInspect,
Cli::HelpUnpack,
Cli::HelpJson,
Cli::HelpDryRun,
Cli::HelpThreads,
Cli::HelpColor,
Cli::HelpScanAll,
Cli::HelpStrictIntegrity,
Cli::HelpLimits {
entry_mib: defaults.max_entry_bytes / (1024 * 1024),
total_mib: defaults.max_total_bytes / (1024 * 1024),
entries: defaults.max_entries,
depth: defaults.max_depth,
},
Cli::HelpExitCodes,
] {
println!("{}", block.localize(lang));
}
}
#[cfg(test)]
@@ -641,7 +613,9 @@ mod command_line {
use super::*;
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::Handled(code) => Err(format!(
"handled: {}",
+1
View File
@@ -10,6 +10,7 @@ fn senbei() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command
.arg("--no-pause")
.env("SENBEI_LANG", "en")
.env_remove("NO_COLOR")
.env("TERM", "xterm-256color");
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 {
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command.arg("--no-pause");
command.arg("--no-pause").env("SENBEI_LANG", "en");
command
}
@@ -638,6 +638,7 @@ fn a_relative_path_is_reported_verbatim() {
let td = tempfile::tempdir().unwrap();
write_plain(td.path(), "plain.exe");
let output = Command::new(env!("CARGO_BIN_EXE_senbei"))
.env("SENBEI_LANG", "en")
.current_dir(td.path())
.args(["--no-pause", "inspect", "plain.exe", "--json"])
.output()
+3 -1
View File
@@ -2,7 +2,9 @@ use std::process::Command;
fn command() -> Command {
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
}
+3 -1
View File
@@ -10,7 +10,9 @@ use std::path::Path;
use std::process::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 {
+8 -8
View File
@@ -835,10 +835,16 @@ fn run_pe(
output.detected_kind = Some(kind_name(image.kind).to_owned());
output.bytes = Some(image.bytes.len() as u64);
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 {
ok: image.integrity.ok(),
fatal: image.integrity.has_fatal(),
issues: image.integrity.issues.clone(),
issues: issues.clone(),
});
if expect_failure {
output.fail("expected failure, but the input unpacked");
@@ -847,13 +853,7 @@ fn run_pe(
"expected failure, but the input unpacked",
);
} else {
compare_output(
&mut output,
&image.bytes,
expected,
allow_suspect,
&image.integrity.issues,
);
compare_output(&mut output, &image.bytes, expected, allow_suspect, &issues);
finish_case(report, &mut output, "unpacked");
}
}
+3 -1
View File
@@ -3,7 +3,9 @@
use std::process::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]
+1
View File
@@ -14,6 +14,7 @@ sha2.workspace = true
tempfile.workspace = true
thiserror.workspace = true
senbei-crypto.workspace = true
senbei-i18n.workspace = true
senbei-elf.workspace = true
senbei-pe.workspace = true
+4 -1
View File
@@ -84,7 +84,10 @@ pub fn probe_libil2cpp_profiled_with_limits(
}
Err(error) => {
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 {
profile
.candidates
+53
View File
@@ -110,6 +110,28 @@ pub enum LimitExceeded {
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.
///
/// Each call starts its own budget at zero. Charging checks the single-entry
@@ -213,6 +235,37 @@ impl EntryBudget {
mod tests {
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]
fn defaults_match_the_documented_ceilings() {
let limits = ResourceLimits::default();
@@ -8,6 +8,7 @@ use memmap2::{Mmap, MmapMut, MmapOptions};
use senbei_crypto::android::{
ContainerHeader, HuffmanLzDecoder, Module9bConfig, ProtectedDescriptor, transform_segment,
};
use senbei_i18n::Step;
use serde::Serialize;
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;
@@ -463,12 +464,12 @@ where
data_cursor = encoded_end;
}
if verbose {
eprintln!(
crate::progress::detail_err(format_args!(
"[{current:02}/{total:02}] writers={writer_count} encoded=0x{size:x}",
current = segment_index + 1,
total = header.segments.len(),
size = encoded.size,
);
));
}
}
Ok(statistics)
@@ -2671,7 +2672,7 @@ pub fn restore_libil2cpp_with_limits(
{
let mut output = map_mut(temporary.as_file(), private_size, &temporary_path)?;
if options.verbose {
eprintln!("Decoding primary 0x9D target-image container...");
crate::progress::stage(Step::AndroidPrimary);
}
let mut writer = FileLayoutWriter {
output: &mut output,
@@ -2711,7 +2712,7 @@ pub fn restore_libil2cpp_with_limits(
if !options.outer_only {
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 auxiliary_len = decoded.len();
@@ -2771,7 +2772,7 @@ pub fn restore_libil2cpp_with_limits(
.set_len(mapping_bytes)
.map_err(|error| Error::io("extend temporary output", &temporary_path, error))?;
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)?;
+1
View File
@@ -4,6 +4,7 @@ pub mod android;
mod findings;
mod panic_capture;
pub mod profile;
pub mod progress;
mod threading;
pub mod windows;
+13 -12
View File
@@ -13,6 +13,7 @@
//! vendor version, or runtime-behaviour claim. A caller can serialize it as-is;
//! the schema is versioned by [`PROFILE_FORMAT_VERSION`].
use senbei_i18n::Message;
use serde::Serialize;
use crate::windows::{IntegrityReport, IntegritySeverity, Kind};
@@ -180,8 +181,8 @@ impl ObservedTarget {
pub struct LayoutAttempt {
pub layout: LayoutKind,
pub outcome: AttemptOutcome,
pub warnings: Vec<String>,
pub errors: Vec<String>,
pub warnings: Vec<Message>,
pub errors: Vec<Message>,
}
impl LayoutAttempt {
@@ -211,10 +212,10 @@ pub struct ProtectionProfile {
/// The route whose output was accepted, when recovery succeeded.
pub selected: Option<LayoutKind>,
/// 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
/// accepted, or fatal findings on an accepted image. Empty when none.
pub errors: Vec<String>,
pub errors: Vec<Message>,
}
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());
}
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());
}
@@ -269,8 +270,8 @@ impl ProtectionProfile {
&mut self,
layout: LayoutKind,
outcome: AttemptOutcome,
warnings: Vec<String>,
errors: Vec<String>,
warnings: Vec<Message>,
errors: Vec<Message>,
) -> &mut LayoutAttempt {
if self.attempt_mut(layout).is_none() {
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
.findings
.iter()
@@ -330,13 +331,13 @@ mod tests {
IntegrityReport {
issues: findings
.iter()
.map(|(_, issue)| (*issue).to_owned())
.map(|(_, issue)| Message::raw(issue.to_string()))
.collect(),
findings: findings
.iter()
.map(|(severity, message)| IntegrityFinding {
severity: *severity,
message: (*message).to_owned(),
message: Message::raw(message.to_string()),
})
.collect(),
}
@@ -393,7 +394,7 @@ mod tests {
LayoutKind::Dll,
AttemptOutcome::Rejected,
Vec::new(),
vec!["bad".to_owned()],
vec![Message::raw("bad")],
);
profile.record_attempt(
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::primitives::{self, *};
use senbei_i18n::Step;
/// Per-code-block index for trace events. The four blocks share one research
/// 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 {
println!("[1/9] Initializing keys...");
println!(" keys[0] key = 0x{:08X}", keys[0] as u32);
println!(" keys[1] signature = 0x{:08X}", keys[1] as u32);
println!(" keys[3] base = 0x{:08X}", keys[3] as u32);
println!(" keys[4] src_off = 0x{:08X}", keys[4] as u32);
println!(" keys[5] size = 0x{:08X}", keys[5] as u32);
println!(" keys[6] anchor = 0x{:08X}", keys[6] as u32);
crate::progress::step(1, 9, Step::InitKeys);
crate::progress::detail(format_args!(
" keys[0] key = 0x{:08X}",
keys[0] as u32
));
crate::progress::detail(format_args!(
" 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) {
@@ -706,9 +725,15 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
);
}
if verbose {
println!("[2/9] Decrypting key table...");
println!(" size_of_image = 0x{:08X}", size_of_image as u32);
println!(" base_offset = 0x{:08X}", base_offset as u32);
crate::progress::step(2, 9, Step::DecryptKeyTable);
crate::progress::detail(format_args!(
" size_of_image = 0x{:08X}",
size_of_image as u32
));
crate::progress::detail(format_args!(
" base_offset = 0x{:08X}",
base_offset as u32
));
}
// 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);
}
if verbose {
println!("[3/9] Decrypting primary descriptor...");
println!(" xor_accumulator = 0x{:08X}", xor_accumulator);
println!(" checksum1 = 0x{:08X}", checksum1 as u32);
println!(" decrypted_addr1 = 0x{:08X}", decrypted_addr1 as u32);
crate::progress::step(3, 9, Step::DecryptPrimary);
crate::progress::detail(format_args!(
" xor_accumulator = 0x{:08X}",
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);
if decrypted_addr1 < keys[3]
@@ -939,15 +973,15 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
);
}
if verbose {
println!("[4/9] Processing relocations & decomp params...");
println!(" addr2 = 0x{:08X}", addr2 as u32);
println!(
crate::progress::step(4, 9, Step::RelocsParams);
crate::progress::detail(format_args!(" addr2 = 0x{:08X}", addr2 as u32));
crate::progress::detail(format_args!(
" decomp_params = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]",
decomp_params[0] as u32,
decomp_params[1] as u32,
decomp_params[2] as u32,
decomp_params[3] as u32
);
));
}
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);
if verbose {
println!("[5/9] Decrypting code block 1 (addr3)...");
println!(" checksum2 = 0x{:08X}", checksum2 as u32);
println!(" addr3b = 0x{:08X}", addr3b as u32);
crate::progress::step(5, 9, Step::DecryptBlock1);
crate::progress::detail(format_args!(" checksum2 = 0x{:08X}", checksum2 as u32));
crate::progress::detail(format_args!(" addr3b = 0x{:08X}", addr3b as u32));
}
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, "checksum3", checksum3 as u32);
if verbose {
println!("[6/9] Decrypting code blocks 2-3 (addr3b, addr4)...");
println!(" crc_val = 0x{:08X}", crc_val as u32);
println!(" checksum3 = 0x{:08X}", checksum3 as u32);
println!(" addr4 = 0x{:08X}", addr4 as u32);
crate::progress::step(6, 9, Step::DecryptBlocks2To3);
crate::progress::detail(format_args!(" crc_val = 0x{:08X}", crc_val as u32));
crate::progress::detail(format_args!(" checksum3 = 0x{:08X}", checksum3 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;
@@ -1108,9 +1142,9 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
DecompressionStage::DllCodeBlock4,
)?;
if verbose {
println!("[7/9] Decrypting code block 4 (addr5)...");
println!(" checksum4 = 0x{:08X}", checksum4 as u32);
println!(" addr5 = 0x{:08X}", addr5 as u32);
crate::progress::step(7, 9, Step::DecryptBlock4);
crate::progress::detail(format_args!(" checksum4 = 0x{:08X}", checksum4 as u32));
crate::progress::detail(format_args!(" addr5 = 0x{:08X}", addr5 as u32));
}
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),
);
if verbose {
println!("[8/9] Decrypting & decompressing sections...");
println!(
crate::progress::step(8, 9, Step::DllSections);
crate::progress::detail(format_args!(
" section_image_base = 0x{:08X}",
section_image_base as u32
);
println!(
));
crate::progress::detail(format_args!(
" section_data_offset = 0x{:08X}",
section_data_offset as u32
);
));
}
// 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]);
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;
+41 -1
View File
@@ -1,4 +1,5 @@
pub use senbei_crypto::{BufferOperation, DecompressionFailure};
use senbei_i18n::{Message, Msg};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecompressionStage {
@@ -225,7 +226,7 @@ pub enum UnpackError {
},
#[error("structurally invalid layout candidate: {}", issues.join("; "))]
InvalidLayoutCandidate { issues: Vec<String> },
InvalidLayoutCandidate { issues: Vec<Message> },
#[error(
"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 {
fn from(error: senbei_crypto::Error) -> Self {
match error {
+71 -54
View File
@@ -1,6 +1,7 @@
use senbei_crypto::bytecode::{Op, OpsLut, generate};
use senbei_crypto::primitives;
use senbei_crypto::primitives::*;
use senbei_i18n::Step;
use super::super::error::*;
use super::super::layout::{self, *};
@@ -362,15 +363,15 @@ impl<'a> Unpacker<'a> {
0x1004,
);
if verbose {
println!("[1/9] Decrypting file header...");
println!(" info[0] key = 0x{:08X}", u.info[0]);
println!(" info[1] signature = 0x{:08X}", u.info[1]);
println!(" info[2] = 0x{:08X}", u.info[2]);
println!(" info[3] base = 0x{:08X}", u.info[3]);
println!(" info[4] src_off = 0x{:08X}", u.info[4]);
println!(" info[5] total_size = 0x{:08X}", u.info[5]);
println!(" info[6] end_mark = 0x{:08X}", u.info[6]);
println!(" info[7] = 0x{:08X}", u.info[7]);
crate::progress::step(1, 9, Step::DecryptHeader);
crate::progress::detail(format_args!(" info[0] key = 0x{:08X}", u.info[0]));
crate::progress::detail(format_args!(" info[1] signature = 0x{:08X}", u.info[1]));
crate::progress::detail(format_args!(" info[2] = 0x{:08X}", u.info[2]));
crate::progress::detail(format_args!(" info[3] base = 0x{:08X}", u.info[3]));
crate::progress::detail(format_args!(" info[4] src_off = 0x{:08X}", u.info[4]));
crate::progress::detail(format_args!(" info[5] total_size = 0x{:08X}", u.info[5]));
crate::progress::detail(format_args!(" info[6] end_mark = 0x{:08X}", u.info[6]));
crate::progress::detail(format_args!(" info[7] = 0x{:08X}", u.info[7]));
}
if !super::super::is_supported_magic(u.info[1]) {
return Err(UnpackError::HeaderMagicMismatch { found: u.info[1] });
@@ -409,7 +410,7 @@ impl<'a> Unpacker<'a> {
u.info[5] as u64,
);
if verbose {
println!("[2/9] Decrypting payload...");
crate::progress::step(2, 9, Step::DecryptPayload);
}
let pe32_table = u.load_payload();
research::emit_u32(ResearchStage::Payload, "prefix_length", u.decrypt_size);
@@ -505,8 +506,8 @@ impl<'a> Unpacker<'a> {
);
if verbose {
println!(" anchor = 0x{anchor:08X}");
println!(" anchor layout offset = +0x{anchor_extra:X}");
crate::progress::detail(format_args!(" anchor = 0x{anchor:08X}"));
crate::progress::detail(format_args!(" anchor layout offset = +0x{anchor_extra:X}"));
}
let p1 = get_u32(&u.decompressed, anchor.wrapping_add(8));
@@ -555,14 +556,16 @@ impl<'a> Unpacker<'a> {
stage1_descriptor.to_vec(),
);
if verbose {
println!("[3/9] Locating config layout...");
println!(" stage1 = 0x{:08X}", stage1);
println!(" stage1_len = 0x{stage1_len:08X}");
println!(
crate::progress::step(3, 9, Step::LocateConfig);
crate::progress::detail(format_args!(" stage1 = 0x{:08X}", stage1));
crate::progress::detail(format_args!(" stage1_len = 0x{stage1_len:08X}"));
crate::progress::detail(format_args!(
" stage1 descriptor = [0x{:08X}, 0x{:08X}]",
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
@@ -653,11 +656,13 @@ impl<'a> Unpacker<'a> {
chk_src_start,
);
if verbose {
println!("[4/9] Decrypting stage2...");
println!(" stage2 = 0x{:08X}", stage2);
println!(" stage2_off = 0x{stage2_off:04X}");
println!(" checksum table = stage1+0x{chk_src_start:04X}");
println!(" stage2 key = 0x{key2:08X}");
crate::progress::step(4, 9, Step::DecryptStage2);
crate::progress::detail(format_args!(" stage2 = 0x{:08X}", stage2));
crate::progress::detail(format_args!(" stage2_off = 0x{stage2_off:04X}"));
crate::progress::detail(format_args!(
" 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
@@ -690,17 +695,21 @@ impl<'a> Unpacker<'a> {
let head_off = table_start.wrapping_add(32);
let walk2_off = head_off.wrapping_sub(88);
if verbose {
println!(" operation table = stage2+0x{table_start:04X}");
println!(" head/walk = +0x{head_off:04X}/+0x{walk2_off:04X}");
crate::progress::detail(format_args!(
" 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 {
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}]",
get_u32(&u.decompressed, entry),
get_u32(&u.decompressed, entry.wrapping_add(4)),
get_u32(&u.decompressed, entry.wrapping_add(8)),
get_u32(&u.decompressed, entry.wrapping_add(12)),
);
));
}
}
@@ -751,10 +760,10 @@ impl<'a> Unpacker<'a> {
u.key_offsets.to_vec(),
);
if verbose {
println!(
crate::progress::detail(format_args!(
" 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]
);
));
}
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_dlen = get_u32(&u.decompressed, at1.wrapping_add(12));
if verbose {
println!("[5/9] Decrypting stages 3-5...");
println!(" stage3 = 0x{:08X}", stage3_field);
println!(
crate::progress::step(5, 9, Step::DecryptStages3To5);
crate::progress::detail(format_args!(" stage3 = 0x{:08X}", stage3_field));
crate::progress::detail(format_args!(
" 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}");
println!(" stage3 accum seed = 0x{accum_seed:08X}");
));
crate::progress::detail(format_args!(
" 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;
research::emit_range(
@@ -858,7 +869,9 @@ impl<'a> Unpacker<'a> {
rounds,
);
if verbose {
println!(" selected stage3 accumulator rounds = {rounds}");
crate::progress::detail(format_args!(
" selected stage3 accumulator rounds = {rounds}"
));
}
} else {
restore_stage3(&mut u.decompressed);
@@ -873,7 +886,7 @@ impl<'a> Unpacker<'a> {
let stage3b_field = get_u32(&u.decompressed, at2);
let stage3b_dlen = get_u32(&u.decompressed, at2.wrapping_add(12));
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)));
// 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_dlen = get_u32(&u.decompressed, at3.wrapping_add(12));
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) {
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_dlen = get_u32(&u.decompressed, at4.wrapping_add(12));
if verbose {
println!(" stage5 = 0x{:08X}", stage5_field);
println!(
crate::progress::detail(format_args!(" stage5 = 0x{:08X}", stage5_field));
crate::progress::detail(format_args!(
" 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}");
println!(" stage5 accumulator seed = 0x{accum2_seed:08X} at 0x{v6:08X}");
));
crate::progress::detail(format_args!(" stage5 bytecode = 0x{data_offset: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_hi = stage5_field
@@ -1047,7 +1062,9 @@ impl<'a> Unpacker<'a> {
stage5_dlen as u64,
);
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
@@ -1185,10 +1202,10 @@ impl<'a> Unpacker<'a> {
Ok(next) => chain_crc = next,
Err(UnpackError::ExeChecksumRangeOutOfBounds { .. }) => {
if verbose {
println!(
crate::progress::detail(format_args!(
" checksum chain terminates at 0x{:08X}: descriptor payload is outside protected input",
walk3.wrapping_sub(16)
);
));
}
break;
}
@@ -1200,18 +1217,18 @@ impl<'a> Unpacker<'a> {
}
}
if verbose {
println!("[6/9] Decrypting section data...");
println!(
crate::progress::step(6, 9, Step::DecryptSections);
crate::progress::detail(format_args!(
" integrity = 0x{:08X}",
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 {
u.decompressed[addr..addr + 16].copy_from_slice(&bytes);
}
} else if verbose {
println!("[6/9] Decrypting section data (new layout)...");
crate::progress::step(6, 9, Step::DecryptSectionsNewLayout);
}
let data_offset2 = bc2_off;
@@ -1255,7 +1272,7 @@ impl<'a> Unpacker<'a> {
let at6 = walk4_slot;
if verbose {
println!("[7/9] Loading and decompressing sections...");
crate::progress::step(7, 9, Step::LoadSections);
}
let mut walk4 = get_u32(&u.decompressed, at6);
// Pass 1 (sequential): the 16-byte descriptors are decrypted in a
@@ -1402,7 +1419,7 @@ impl<'a> Unpacker<'a> {
let at7 = walk5_slot;
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
// layout has no such table — imports are rebuilt from the PE Import
@@ -1464,7 +1481,7 @@ impl<'a> Unpacker<'a> {
} // end !new_layout (walk5)
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]);
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::research::{self, AddressSpace, ResearchStage};
use super::*;
use senbei_i18n::Step;
/// Name of the dd8 formula the PE32 selector actually chose. `None` is the
/// selector's skip verdict, not "did not run".
@@ -209,8 +210,8 @@ impl<'a> Unpacker<'a> {
tbl as u64,
);
if verbose {
println!("[3/9] Locating config layout (PE32)...");
println!(" tbl = 0x{:X}, compact = {}", tbl, compact);
crate::progress::step(3, 9, Step::Pe32LocateConfig);
crate::progress::detail(format_args!(" tbl = 0x{:X}, compact = {}", tbl, compact));
}
// ---- Stage 3: SecondStage ----
@@ -234,10 +235,10 @@ impl<'a> Unpacker<'a> {
header_checksum,
);
if verbose {
println!(
crate::progress::detail(format_args!(
" ss = 0x{:08X}, size = 0x{:X}, shift = 0x{:X}",
ss, ss_size, ss_shift
);
));
}
// ---- PE32 fixed offsets ----
@@ -304,11 +305,11 @@ impl<'a> Unpacker<'a> {
info_table as u64,
);
if verbose {
println!("[4/9] Decrypting stages (PE32)...");
println!(
crate::progress::step(4, 9, Step::Pe32Stages);
crate::progress::detail(format_args!(
" thirdStage start = 0x{:X}, infoTable = 0x{:X}",
ts, info_table
);
));
}
// ---- Process infoTable ----
@@ -372,7 +373,9 @@ impl<'a> Unpacker<'a> {
forth_key_rounds,
);
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 fk = header_checksum ^ second_stage_cs ^ forth_stage_key;
@@ -433,11 +436,11 @@ impl<'a> Unpacker<'a> {
// ---- EighthStage ----
let seven_start_actual = get_u32(&self.decompressed, seven_addr);
if verbose {
println!("[5/9] Decrypting eighthStage (PE32)...");
println!(
crate::progress::step(5, 9, Step::Pe32EighthStage);
crate::progress::detail(format_args!(
" sevenStart = 0x{:X}, sevenDsz = 0x{:X}",
seven_start_actual, seven_dsz
);
));
}
// Locate the customDecryptor LFSR block (scan backward from middle, then
// forward as fallback).
@@ -470,7 +473,9 @@ impl<'a> Unpacker<'a> {
let eighth_key_rounds =
stage_key_rounds(&self.decompressed, dp_base.wrapping_add(0x80), 4)?;
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_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);
if verbose {
println!(
crate::progress::detail(format_args!(
" eighthStart = 0x{:08X}, dsz = 0x{:X}",
eighth_start, eighth_dsz
);
));
}
// ---- Final processing offsets (anchored on the eighthStage config cluster) ----
@@ -637,10 +642,10 @@ impl<'a> Unpacker<'a> {
}
if let Some((dist, base)) = best {
if verbose {
println!(
crate::progress::detail(format_args!(
" pe32 cluster via fileCS (no 0x7679): base=+0x{:X} dist_info3=0x{:X}",
base, dist
);
));
}
m = Some(base);
}
@@ -723,10 +728,10 @@ impl<'a> Unpacker<'a> {
}
if let Some(c) = chosen {
if verbose {
println!(
crate::progress::detail(format_args!(
" pe32 fileLFSR via trial-validate: +0x{:X} (expected +0x{:X}, considered {})",
c, off_file_lfsr, considered
);
));
}
lfsr_off = c;
} else {
@@ -818,7 +823,7 @@ impl<'a> Unpacker<'a> {
// ---- File data decompression ----
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 compressed_info_addr = eighth_start.wrapping_add(off_compressed_info);
@@ -1026,9 +1031,12 @@ impl<'a> Unpacker<'a> {
);
if let Some(big) = selection {
if verbose {
println!(
"[7/9] Decrypting .text (PE32 dd8, formula={})...",
if big { "0x8000*(page+1)" } else { "page+1" }
crate::progress::step(
7,
9,
Step::Pe32Text {
formula: if big { "0x8000*(page+1)" } else { "page+1" },
},
);
}
research::emit_text(
@@ -1070,7 +1078,7 @@ impl<'a> Unpacker<'a> {
}
}
} 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);
}
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) ----
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 mut import_table_ptr = get_u32(&self.decompressed, import_table_addr);
@@ -1361,7 +1372,7 @@ impl<'a> Unpacker<'a> {
// ---- Output transforms ----
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);
// 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.
use senbei_i18n::{Message, Msg};
mod clr;
mod directories;
@@ -48,7 +50,7 @@ pub enum IntegritySeverity {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IntegrityFinding {
pub severity: IntegritySeverity,
pub message: String,
pub message: Message,
}
/// Result of a static integrity check over an unpacked image.
@@ -56,7 +58,7 @@ pub struct IntegrityFinding {
pub struct IntegrityReport {
/// Each entry describes one detected defect. Empty means no defect found.
/// Order and wording match [`IntegrityReport::findings`].
pub issues: Vec<String>,
pub issues: Vec<Message>,
/// The same defects as `issues`, each tagged fatal or warning.
pub findings: Vec<IntegrityFinding>,
}
@@ -78,7 +80,7 @@ impl IntegrityReport {
.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();
self.issues.push(message.clone());
self.findings.push(IntegrityFinding { severity, message });
@@ -152,9 +154,10 @@ fn check_common_entry_branches(
if !valid {
report.push(
IntegritySeverity::Fatal,
format!(
"entry point {name} target 0x{target:X} is outside executable sections (DD8 selection is likely wrong)"
),
Msg::EntryStubTargetOutsideCode {
branch: name,
target,
},
);
}
}
@@ -168,23 +171,20 @@ pub fn check(out: &[u8]) -> IntegrityReport {
// --- DOS + PE headers ---------------------------------------------------
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
}
let pe_off = match rd_u32(out, 0x3C) {
Some(v) => v,
None => {
r.push(
IntegritySeverity::Fatal,
"truncated DOS header (no e_lfanew)",
);
r.push(IntegritySeverity::Fatal, Msg::TruncatedDosHeader);
return r;
}
};
if rd_u32(out, pe_off) != Some(0x0000_4550) {
r.push(
IntegritySeverity::Fatal,
format!("missing 'PE\\0\\0' signature at 0x{pe_off:X}"),
Msg::MissingPeSignature { offset: pe_off },
);
return r;
}
@@ -192,7 +192,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
let num_sections = match rd_u16(out, pe_off.wrapping_add(6)) {
Some(v) => v as u32,
None => {
r.push(IntegritySeverity::Fatal, "truncated COFF header");
r.push(IntegritySeverity::Fatal, Msg::TruncatedCoffHeader);
return r;
}
};
@@ -200,7 +200,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
let magic = match rd_u16(out, opt) {
Some(v) => v,
None => {
r.push(IntegritySeverity::Fatal, "truncated optional header");
r.push(IntegritySeverity::Fatal, Msg::TruncatedOptionalHeader);
return r;
}
};
@@ -210,7 +210,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
other => {
r.push(
IntegritySeverity::Fatal,
format!("bad optional-header magic 0x{other:X}"),
Msg::BadOptionalMagic { magic: other },
);
return r;
}
@@ -219,33 +219,29 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if num_sections == 0 || num_sections > 96 {
r.push(
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);
if size_of_image == 0 {
r.push(IntegritySeverity::Fatal, "SizeOfImage is zero");
r.push(IntegritySeverity::Fatal, Msg::ZeroSizeOfImage);
}
// --- Section table ------------------------------------------------------
let headers = match senbei_pe::parse(out) {
Ok(headers) => headers,
Err(_) => {
r.push(
IntegritySeverity::Fatal,
"section table extends past end of file",
);
r.push(IntegritySeverity::Fatal, Msg::SectionTablePastEof);
return r;
}
};
let parsed_sections = match senbei_pe::sections(out, headers) {
Ok(sections) => sections,
Err(_) => {
r.push(
IntegritySeverity::Fatal,
"section table extends past end of file",
);
r.push(IntegritySeverity::Fatal, Msg::SectionTablePastEof);
return r;
}
};
@@ -258,10 +254,12 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if end > file_len {
r.push(
IntegritySeverity::Fatal,
format!(
"section #{i} raw data [0x{:X}..0x{end:X}] exceeds file size 0x{file_len:X}",
section.raw_offset
),
Msg::SectionRawPastEof {
index: i,
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
// at its preferred base). Rejecting the layout here would fall back
// to the other pipeline and change bytes that previously unpacked.
r.push(
IntegritySeverity::Warning,
"native DLL has no base relocation table (DD[5] is zero) — will crash when loaded at a non-preferred base",
);
r.push(IntegritySeverity::Warning, Msg::NoBaseRelocations);
}
}
@@ -318,15 +313,12 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if ep == 0 {
// A DLL may legitimately have no entry point; an EXE never does.
if !is_dll {
r.push(IntegritySeverity::Fatal, "entry point RVA is zero");
r.push(IntegritySeverity::Fatal, Msg::ZeroEntryPoint);
}
} else if !is_managed {
match rva_to_off(out, headers, ep, 16) {
None => {
r.push(
IntegritySeverity::Fatal,
format!("entry point RVA 0x{ep:X} does not map into any section"),
);
r.push(IntegritySeverity::Fatal, Msg::EntryUnmapped { rva: ep });
}
Some(off) => {
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
// already-chosen layout, not proof another layout is the
// right one.
r.push(
IntegritySeverity::Warning,
format!("entry point at RVA 0x{ep:X} is all zeros (stub not recovered)"),
);
r.push(IntegritySeverity::Warning, Msg::EntryAllZeros { rva: ep });
} else if stub.iter().all(|&b| b == 0xCC) {
// 16 bytes of int3 padding where the entry stub should be:
// the stub region was never recovered, the loader walks
// straight into a debug-break wall. Same severity as a
// zeroed stub: the image is mapped, the bytes look unrestored.
r.push(
IntegritySeverity::Warning,
format!(
"entry point at RVA 0x{ep:X} is all int3 padding (stub not recovered)"
),
);
r.push(IntegritySeverity::Warning, Msg::EntryAllInt3 { rva: ep });
}
// The entry must live in an executable section.
let exec = secs.iter().any(|s| {
@@ -361,7 +345,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if !exec {
r.push(
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) {
@@ -387,7 +371,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
match rva_to_off(out, headers, imp_rva, 20) {
None => r.push(
IntegritySeverity::Fatal,
format!("import directory RVA 0x{imp_rva:X} does not map into any section"),
Msg::ImportDirectoryUnmapped { rva: imp_rva },
),
Some(desc_off) => {
// 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) {
None => r.push(
IntegritySeverity::Fatal,
format!(
"import descriptor {i} DLL name RVA 0x{name_rva:X} does not map into any section"
),
Msg::ImportNameUnmapped {
index: i,
rva: name_rva,
},
),
Some(noff) => {
if !looks_like_dll_name(out, noff) {
@@ -415,9 +400,10 @@ pub fn check(out: &[u8]) -> IntegrityReport {
// suspect signal, not an unmapped PE.
r.push(
IntegritySeverity::Warning,
format!(
"import descriptor {i} DLL name at RVA 0x{name_rva:X} is not readable ASCII (imports left encrypted?)"
),
Msg::ImportNameUnreadable {
index: i,
rva: name_rva,
},
);
}
}
@@ -441,16 +427,17 @@ pub fn check(out: &[u8]) -> IntegrityReport {
match rva_to_off(out, headers, clr_rva, 0x48) {
None => r.push(
IntegritySeverity::Fatal,
format!("CLR (COR20) directory RVA 0x{clr_rva:X} does not map into any section"),
Msg::ClrDirectoryUnmapped { rva: clr_rva },
),
Some(coff) => {
let cb = rd_u32(out, coff).unwrap_or(0);
if cb != 0x48 {
r.push(
IntegritySeverity::Fatal,
format!(
"COR20 header at RVA 0x{clr_rva:X} has cb 0x{cb:X} (expected 0x48) — CLR header corrupt"
),
Msg::ClrHeaderBadSize {
rva: clr_rva,
size: cb,
},
);
} else {
// 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) {
None => r.push(
IntegritySeverity::Fatal,
format!(
"CLR MetaData RVA 0x{md_rva:X} does not map into any section"
),
Msg::ClrMetadataUnmapped { rva: md_rva },
),
Some(moff) => {
let sig = out.get(moff as usize..moff as usize + 4);
if sig != Some(b"BSJB") {
r.push(
IntegritySeverity::Fatal,
format!(
"CLR MetaData at RVA 0x{md_rva:X} lacks 'BSJB' signature (metadata corrupt — managed image will not load)"
),
Msg::ClrMetadataNoBsjb { rva: md_rva },
);
}
}
+8 -7
View File
@@ -10,6 +10,7 @@ pub(crate) mod parallel;
pub mod research;
use senbei_crypto::primitives;
use senbei_i18n::Message;
use serde::Serialize;
use crate::profile::{
@@ -309,7 +310,7 @@ pub fn unpack_auto_profiled_v(
let mut profile = inspect_detected(input, detected);
let Some(detected) = detected else {
let error = UnpackError::NotCrackProof;
profile.push_error(error.to_string());
profile.push_error(error.message());
return (profile, Err(error));
};
let result = match detected.kind {
@@ -343,7 +344,7 @@ pub fn unpack_exe_profiled_v(
let mut profile = inspect_detected(input, detected);
if detected.is_none() {
let error = UnpackError::NotCrackProof;
profile.push_error(error.to_string());
profile.push_error(error.message());
return (profile, Err(error));
}
// 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,
AttemptOutcome::Failed,
Vec::new(),
vec![error.to_string()],
vec![error.message()],
);
profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_string());
profile.push_error(error.message());
Err(error)
}
}
@@ -431,7 +432,7 @@ where
dll: Box::new(dll.error),
exe: Box::new(exe.error),
};
profile.push_error(error.to_string());
profile.push_error(error.message());
Err(error)
}
}
@@ -453,7 +454,7 @@ fn record_rejected(profile: &mut ProtectionProfile, layout: LayoutKind, failure:
profile_messages(report, ProfileSeverity::Warning),
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() {
AttemptOutcome::Rejected
@@ -463,7 +464,7 @@ fn record_rejected(profile: &mut ProtectionProfile, layout: LayoutKind, failure:
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
.findings
.iter()
+1
View File
@@ -12,6 +12,7 @@ indicatif.workspace = true
memmap2.workspace = true
owo-colors.workspace = true
senbei-engine.workspace = true
senbei-i18n.workspace = true
senbei-elf.workspace = true
senbei-pe.workspace = true
senbei-metadata.workspace = true
+28 -10
View File
@@ -40,7 +40,9 @@ use sha2::{Digest, Sha256};
use zip::ZipArchive;
pub use crate::METADATA_FILE_NAME;
use crate::message::Coded;
use crate::report::{ContainerReport, ManifestReport};
use senbei_i18n::Msg;
/// Package extensions recognised as Android app packages. Packages are
/// *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;
}
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 name
@@ -642,7 +646,7 @@ pub(crate) fn restore_loose_metadata(
),
Err(ambiguity) => {
let provenance = context::provenance_for(modules.as_ref(), Some(&ambiguity));
bail!(provenance_error(&provenance));
bail!(provenance_error(&provenance, &ambiguity));
}
}
} else {
@@ -657,7 +661,7 @@ pub(crate) fn restore_loose_metadata(
if report.remapped > 0 {
write_metadata_blob(dest, &out)?;
if verbose {
println!("Write to {}", dest.display());
crate::ui::write_to(dest, false);
}
}
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
// failed binding, not an unsupported layout.
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));
};
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;
}
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 name
@@ -1436,7 +1442,9 @@ fn restore_package_pass<R: context::LibraryRestorer>(
};
if !is_dir {
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) {
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));
return Ok(vec![outcome(
EntryKind::Metadata { remapped: 0 },
EntryStatus::Failed(anyhow::anyhow!(provenance_error(&provenance))),
EntryStatus::Failed(anyhow::Error::new(provenance_error(
&provenance,
&ambiguity,
))),
provenance_labels(&provenance),
)]);
}
@@ -1792,13 +1803,20 @@ fn provenance_labels(provenance: &context::MetadataProvenance) -> Vec<String> {
.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
.note
.clone()
.unwrap_or_else(|| "ambiguous module 0x0C binding".to_owned());
if provenance.sources.is_empty() {
return why;
return Coded::with_text(msg, why);
}
let sources = provenance
.sources
@@ -1806,7 +1824,7 @@ fn provenance_error(provenance: &context::MetadataProvenance) -> String {
.map(|source| source.label.as_str())
.collect::<Vec<_>>()
.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
+233 -115
View File
@@ -1,7 +1,10 @@
use std::path::{Path, PathBuf};
use std::time::Instant;
use senbei_i18n::{Cli, Lang, Localize, Message, Msg};
use crate::atomic::write_atomic;
use crate::message::{Coded, of_error};
pub use crate::report::{Collector, Mode, REPORT_FORMAT_VERSION, Report};
use crate::report::{
CompanionReport, CompanionState, ContainerReport, Digest, EntryKind, EntryReport, EntryStatus,
@@ -34,30 +37,31 @@ pub struct 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 {
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 {
use crate::ui::{Tone, count};
self.line_in(palette, senbei_i18n::current())
}
let mut line = format!(
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
count(palette, self.unpacked, Tone::Success),
count(palette, self.skipped, Tone::Muted),
count(palette, self.errors, Tone::Error),
count(palette, self.suspect, Tone::Warning),
count(palette, self.metadata, Tone::Success)
);
if self.packages > 0 {
line.push_str(&format!(
" · {} packages",
palette.paint(Tone::Value, self.packages)
));
}
line
/// The summary line in `lang`.
pub fn line_in(&self, palette: crate::ui::Palette, lang: Lang) -> String {
crate::ui::summary_line(
palette,
lang,
[
self.unpacked,
self.skipped,
self.errors,
self.suspect,
self.metadata,
self.packages,
],
)
}
}
@@ -176,7 +180,7 @@ pub fn run_folder_reported(
///
/// Used when a run cannot start at all (an unreadable input, a rejected
/// 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);
collector.push_error(message);
collector.finish()
@@ -188,6 +192,61 @@ pub fn error_report(mode: Mode, message: &str) -> Report {
/// [`run_folder_with_limits`]; the collector only observes.
#[allow(clippy::too_many_arguments)]
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,
out_dir: Option<&Path>,
quiet: u8,
@@ -229,10 +288,11 @@ fn run_folder_inner(
// 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;
if scan_failed > 0 && quiet == 0 {
let lang = senbei_i18n::current();
eprintln!(
"{}: {} file(s) could not be read during the scan and may be missed targets",
Palette::stderr().paint(Tone::Warning, "warning"),
scan_failed
"{}: {}",
Palette::stderr().paint(Tone::Warning, Cli::Warning.localize(lang)),
Cli::ScanUnreadable { count: scan_failed }.localize(lang)
);
}
if let Some(log) = &log {
@@ -252,7 +312,8 @@ fn run_folder_inner(
let suppress_file_lines = quiet >= 1;
// 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).
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
// 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.
@@ -277,9 +338,21 @@ fn run_folder_inner(
walk_errors: scan_stats.walk_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 {
if stop(&mut reporter) {
break;
}
started(&reporter, input);
let rel = rel_in_tree(root, input);
let dest = out_root.join(out_name(&rel));
let started = Instant::now();
@@ -346,7 +419,7 @@ fn run_folder_inner(
}
Err(panic) => {
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);
if let Some(log) = &log {
log.step(&format!(
@@ -378,6 +451,10 @@ fn run_folder_inner(
.iter()
.any(|library| library == &scoped.path)
}) {
if stop(&mut reporter) {
break;
}
started(&reporter, &scoped.path);
let rel = rel_in_tree(root, &scoped.path);
let dest = out_root.join(out_name(&rel));
let input_owned = scoped.path.clone();
@@ -487,7 +564,7 @@ fn run_folder_inner(
}
Err(panic) => {
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);
if let Some(log) = &log {
log.step(&format!(
@@ -516,7 +593,14 @@ fn run_folder_inner(
let package_groups =
crate::android::loose_apk_groups_cached(&scan.android_packages, &mut android_cache);
for group in &package_groups {
if stop(&mut reporter) {
break;
}
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();
// Relative output paths are computed here, by the same helper the
// rest of the driver uses: they must stay relative so joining them
@@ -588,10 +672,10 @@ fn run_folder_inner(
}
}
Err(panic) => {
let e = anyhow::anyhow!(
"unexpected panic during package restore: {}",
panic_payload(&panic)
);
let e = anyhow::Error::new(Coded::panic(
" during package restore",
panic_payload(&panic),
));
s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
@@ -608,6 +692,10 @@ fn run_folder_inner(
continue;
}
for package in group {
if stop(&mut reporter) {
break;
}
started(&reporter, package);
let rel = rel_in_tree(root, package);
s.packages += 1;
let package_owned = package.clone();
@@ -648,7 +736,7 @@ fn run_folder_inner(
Err(panic) => {
// A panic may leave a partial module recorded. Keeping the cache
// 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;
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
@@ -675,6 +763,10 @@ fn run_folder_inner(
.iter()
.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 dest = out_root.join(out_name(&rel));
let meta_owned = scoped.path.clone();
@@ -740,9 +832,11 @@ fn run_folder_inner(
s.skipped += 1;
if !suppress_file_lines {
eprintln!(
"{} {} unsupported metadata version {v}, left untouched",
"{} {} {}",
Palette::stderr().paint(Tone::Warning, "-"),
rel.display()
rel.display(),
Cli::MetadataUnsupportedLine { version: v }
.localize(senbei_i18n::current())
);
}
if let Some(log) = &log {
@@ -768,10 +862,10 @@ fn run_folder_inner(
}
Err(panic) => {
s.errors += 1;
let e = anyhow::anyhow!(
"unexpected panic during de-obfuscation: {}",
panic_payload(&panic)
);
let e = anyhow::Error::new(Coded::panic(
" during de-obfuscation",
panic_payload(&panic),
));
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!(
@@ -847,6 +941,21 @@ pub fn run_file_reported(
#[allow(clippy::too_many_arguments)]
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,
out_dir: Option<&Path>,
quiet: u8,
@@ -883,6 +992,11 @@ fn run_file_inner(
let research = reporter
.as_deref()
.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 = {
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);
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 => {
s.metadata = 1;
if let Some(log) = &log {
@@ -916,12 +1030,16 @@ fn run_file_inner(
));
}
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!(
"{} metadata v{} -> {} ({} method fields remapped)",
Palette::stdout().paint(Tone::Success, "✓"),
Palette::stdout().paint(Tone::Value, report.version),
Palette::stdout().paint(Tone::Value, format!("{dest:?}")),
Palette::stdout().paint(Tone::Value, report.remapped)
"{} {}",
palette.paint(Tone::Success, "✓"),
line.localize(senbei_i18n::current())
);
}
if let Some(reporter) = reporter.as_deref_mut() {
@@ -939,11 +1057,15 @@ fn run_file_inner(
));
}
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!(
"metadata v{}: {}",
Palette::stdout().paint(Tone::Value, report.version),
Palette::stdout()
.paint(Tone::Muted, "already de-obfuscated, nothing to do")
"{} {}",
version.localize(lang),
palette.paint(Tone::Muted, Cli::MetadataNothingToDo.localize(lang))
);
}
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).
if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
crate::ui::print_anyhow(&e);
}
if let Some(reporter) = reporter.as_deref_mut() {
let unsupported = unsupported_version(&e);
@@ -973,7 +1095,7 @@ fn run_file_inner(
crate::android::restore_so_file_researched(
input,
&dest,
verbose && quiet == 0,
verbose_steps,
limits,
research,
)
@@ -985,13 +1107,8 @@ fn run_file_inner(
)
})
} else {
crate::android::restore_so_file_with_diagnostics(
input,
&dest,
verbose && quiet == 0,
limits,
)
.map(|(embedded, validation)| (embedded, validation, None))
crate::android::restore_so_file_with_diagnostics(input, &dest, verbose_steps, limits)
.map(|(embedded, validation)| (embedded, validation, None))
};
match restore {
Ok((embedded, validation, android_research)) => {
@@ -1015,11 +1132,15 @@ fn run_file_inner(
log.step(&format!("META {:?} (embedded) -> {:?}", input, meta_dest));
}
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!(
"{} metadata {} (embedded) -> {}",
Palette::stdout().paint(Tone::Success, "✓"),
Palette::stdout().paint(Tone::Label, input.display()),
Palette::stdout().paint(Tone::Value, meta_dest.display())
"{} {}",
palette.paint(Tone::Success, "✓"),
line.localize(senbei_i18n::current())
);
}
}
@@ -1030,10 +1151,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: embedded metadata: {e:#}", input));
}
if quiet == 0 {
eprintln!(
"{}: embedded metadata: {e:#}",
Palette::stderr().paint(Tone::Error, "error")
);
crate::ui::print_error_about(Cli::EmbeddedMetadataFailed, &e);
}
}
}
@@ -1050,7 +1168,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input));
}
if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
crate::ui::print_anyhow(&e);
}
if let Some(reporter) = reporter.as_deref_mut() {
let mut reported = android_library_input_with_error(
@@ -1082,7 +1200,7 @@ fn run_file_inner(
&rel,
&out_root,
&mut seen,
verbose && quiet == 0,
verbose_steps,
limits,
research,
) {
@@ -1104,7 +1222,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input));
}
if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
crate::ui::print_anyhow(&e);
}
if let Some(reporter) = reporter {
reporter.push(failed_input(input, &e, t0));
@@ -1118,14 +1236,10 @@ fn run_file_inner(
let (profile, observed, result) = match reporter.is_some() {
true => {
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)
}
false => (
None,
None,
unpack_one_v(input, &dest, verbose && quiet == 0),
),
false => (None, None, unpack_one_v(input, &dest, verbose_steps)),
};
match result {
Ok((kind, report)) => {
@@ -1151,13 +1265,14 @@ fn run_file_inner(
));
}
if quiet == 0 {
let lang = senbei_i18n::current();
eprintln!(
"{}: {}",
Palette::stderr().paint(
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));
}
if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
crate::ui::print_anyhow(&e);
}
if let Some(reporter) = reporter {
let mut reported = match profile {
@@ -1321,10 +1436,7 @@ fn deobfuscate_metadata_researched(
}
write_atomic(dest, &out)?;
if verbose {
println!(
"Write to {}",
Palette::stdout().paint(Tone::Value, dest.display())
);
crate::ui::write_to(dest, true);
}
}
Ok((report, layout, metadata_research))
@@ -1676,7 +1788,7 @@ fn unpack_one_researched(
Err(error) => {
let mut profile = observed_profile(input);
profile.recovery = senbei_engine::RecoveryStatus::Blocked;
profile.push_error(format!("{error:#}"));
profile.push_error(of_error(&error));
return (profile, None, Err(error));
}
};
@@ -1755,10 +1867,7 @@ fn unpack_one_researched(
return (profile, observed, Err(error.into()));
}
if verbose {
println!(
"Write to {}",
Palette::stdout().paint(Tone::Value, dest.display())
);
crate::ui::write_to(dest, true);
}
(profile, observed, Ok((image.kind, image.integrity)))
}
@@ -1869,13 +1978,11 @@ pub(crate) fn companion_report(
_ => path.map(|path| path.display().to_string()),
},
detail: match state {
CompanionState::Unmatched => {
Some("a sibling `._` exists but is not this stub's payload".to_owned())
}
CompanionState::Unreadable => Some(match unreadable {
Some(reason) => format!("the sibling `._` could not be read: {reason}"),
None => "the sibling `._` could not be read".to_owned(),
}),
CompanionState::Unmatched => Some(Message::new(Msg::CompanionUnmatched)),
CompanionState::Unreadable => Some(Message::new(match unreadable {
Some(reason) => Msg::CompanionUnreadable { reason },
None => Msg::CompanionUnreadableUnknown,
})),
_ => None,
},
source,
@@ -1971,7 +2078,7 @@ fn failed_input(input: &Path, error: &anyhow::Error, started: Instant) -> InputR
let mut entry = InputReport::new(input, Role::Content);
entry.status = InputStatus::Error;
entry.analysis_incomplete = analysis_incomplete(error);
let detail = format!("{error:#}");
let detail = of_error(error);
entry.error(detail.clone());
entry.profile = Some(failure_profile(input, &detail));
entry
@@ -1994,7 +2101,7 @@ fn failed_input_with_profile(
let mut entry = InputReport::new(input, Role::Content);
entry.status = InputStatus::Error;
entry.analysis_incomplete = analysis_incomplete(error);
let detail = format!("{error:#}");
let detail = of_error(error);
entry.error(detail.clone());
entry.companion = crate::windows::is_pe_extension(input).then(|| {
let (state, source, unreadable) =
@@ -2055,13 +2162,13 @@ fn observed_profile(input: &Path) -> senbei_engine::ProtectionProfile {
}
/// 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};
let Ok(prefix) = read_prefix(input) else {
let mut profile =
ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None));
profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned());
profile.push_error(detail.clone());
return profile;
};
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)
.map(|candidate| candidate.layout)
{
Some(layout) => (layout, vec![detail.to_owned()]),
None => (LayoutKind::ExeStyle, vec![detail.to_owned()]),
Some(layout) => (layout, vec![detail.clone()]),
None => (LayoutKind::ExeStyle, vec![detail.clone()]),
};
if let Some(attempt) = profile.attempt_mut(layout) {
attempt.outcome = AttemptOutcome::Failed;
@@ -2107,7 +2214,7 @@ fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfi
});
}
profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned());
profile.push_error(detail.clone());
return profile;
}
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));
profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned());
profile.push_error(detail.clone());
profile
}
@@ -2156,7 +2263,11 @@ fn android_library_input_with_error(
.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
.stages
@@ -2190,8 +2301,12 @@ fn apply_android_validation(
} else {
senbei_engine::ValidationStatus::Warnings
};
profile.warnings.extend(validation.messages.iter().cloned());
report.warnings.extend(validation.messages.iter().cloned());
profile
.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
// are carried as detail and warnings, not as a failed stage.
let mut stage = StageReport::new(Stage::StaticValidation, StageStatus::Ok);
@@ -2265,8 +2380,7 @@ fn metadata_input(
None => crate::report::metadata_unchanged_profile(identity),
});
entry.stages.push(
StageReport::new(Stage::Recovery, StageStatus::Skipped)
.detail("the transform ran and validated; nothing needed rewriting"),
StageReport::new(Stage::Recovery, StageStatus::Skipped).detail(Msg::TransformNoop),
);
}
entry.duration_ms = crate::report::now_ms(started);
@@ -2346,14 +2460,12 @@ fn metadata_failure_input(
report.status = InputStatus::Skipped;
report.errors.clear();
report.profile = Some(crate::report::metadata_unchanged_profile(identity));
report.warning(format!(
"unsupported metadata version {version}, left untouched"
));
report.warning(Msg::MetadataLeftUntouched { version });
} else {
report.profile = Some(crate::report::metadata_failed_profile(
identity,
senbei_engine::LayoutKind::MetadataStructural,
&format!("{error:#}"),
&of_error(error),
));
}
report
@@ -2416,7 +2528,9 @@ fn package_input(
.flat_map(|validation| validation.messages.iter().cloned())
.collect();
if !diagnostics.is_empty() {
entry.warnings.extend(diagnostics.clone());
entry
.warnings
.extend(diagnostics.iter().cloned().map(Message::from));
entry.stages.push(
StageReport::new(Stage::StaticValidation, StageStatus::Ok)
.detail(diagnostics.join("; ")),
@@ -2475,7 +2589,7 @@ fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport {
report.output = Some(OutputFile::from_path(&outcome.dest));
}
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
// could be judged; a structural rejection is an observed finding.
report.analysis_incomplete = analysis_incomplete(error);
@@ -2485,7 +2599,9 @@ fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport {
if status == EntryStatus::Restored
&& let Some(validation) = &outcome.validation
{
report.warnings.extend(validation.messages.iter().cloned());
report
.warnings
.extend(validation.messages.iter().cloned().map(Message::from));
}
report
}
@@ -2814,7 +2930,7 @@ mod incomplete_analysis_tests {
std::fs::write(&path, b"not really an ELF").unwrap();
let mut input = InputReport::new(&path, Role::Content);
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;
let reported = inspect_status(input);
assert_eq!(reported.status, InputStatus::Error);
@@ -2823,7 +2939,9 @@ mod incomplete_analysis_tests {
// The same target without an incompleteness marker is a finding.
let mut complete = InputReport::new(&path, Role::Content);
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);
assert_eq!(reported.status, InputStatus::Recognized);
assert!(!reported.analysis_incomplete);
@@ -2834,7 +2952,7 @@ mod incomplete_analysis_tests {
fn a_container_inherits_an_incomplete_entry() {
let mut entry = EntryReport::new("app.apk::lib/arm64-v8a/libil2cpp.so", EntryStatus::Error);
entry.analysis_incomplete = true;
entry.errors.push("resource limit".to_owned());
entry.errors.push("resource limit".into());
let td = tempfile::tempdir().unwrap();
let path = td.path().join("app.apk");
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;
mod atomic;
pub mod job;
pub mod locale;
pub mod logfile;
pub mod message;
pub mod observe;
pub mod pause;
pub mod report;
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() {
return;
}
use senbei_i18n::Localize;
use std::io::Write;
eprint!("\nPress Enter to exit…");
eprint!(
"{}",
senbei_i18n::Cli::PressEnter.localize(senbei_i18n::current())
);
let _ = std::io::stderr().flush();
let mut buf = String::new();
let _ = std::io::stdin().read_line(&mut buf);
+114 -57
View File
@@ -24,11 +24,14 @@
//! mistaken for inspected protected content.
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;
use serde::Serialize;
use sha2::{Digest as _, Sha256};
use senbei_i18n::{Cli, Lang, Localize, Message, Msg};
use senbei_engine::{
AttemptOutcome, LayoutKind, ProtectionEvidence, ProtectionProfile, RecognitionStatus,
RecoveryStatus, ValidationStatus,
@@ -211,7 +214,7 @@ pub struct ScanReport {
pub struct CompanionReport {
pub state: CompanionState,
pub path: Option<String>,
pub detail: Option<String>,
pub detail: Option<Message>,
/// Identity of the physical companion, distinct from the spliced view.
pub source: Option<Digest>,
}
@@ -275,7 +278,7 @@ pub struct ContainerReport {
pub struct StageReport {
pub stage: Stage,
pub status: StageStatus,
pub detail: Option<String>,
pub detail: Option<Message>,
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
}
@@ -318,8 +321,8 @@ pub struct EntryReport {
pub provenance: Vec<String>,
/// Where the restored bytes were written (absent in dry-run/inspect).
pub output: Option<OutputFile>,
pub warnings: Vec<String>,
pub errors: Vec<String>,
pub warnings: Vec<Message>,
pub errors: Vec<Message>,
}
impl EntryReport {
@@ -373,8 +376,8 @@ pub struct InputReport {
/// Libraries whose decoded module was paired with this metadata input.
pub provenance: Vec<String>,
pub stages: Vec<StageReport>,
pub warnings: Vec<String>,
pub errors: Vec<String>,
pub warnings: Vec<Message>,
pub errors: Vec<Message>,
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());
}
pub fn error(&mut self, message: impl Into<String>) {
pub fn error(&mut self, message: impl Into<Message>) {
self.errors.push(message.into());
}
}
@@ -454,8 +457,12 @@ pub struct Report {
pub inputs: Vec<InputReport>,
pub summary: SummaryReport,
/// Run-level failures that are not attributable to one input.
pub errors: Vec<String>,
pub errors: Vec<Message>,
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 {
@@ -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 {
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 {
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 mut line = format!(
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
count(palette, s.recovered, Tone::Success),
count(palette, s.skipped, Tone::Muted),
count(palette, s.errors, Tone::Error),
count(palette, s.suspect, Tone::Warning),
count(palette, s.metadata, Tone::Success)
);
if s.packages > 0 {
line.push_str(&format!(
" · {} packages",
palette.paint(Tone::Value, s.packages)
));
}
line
crate::ui::summary_line(
palette,
lang,
[
s.recovered,
s.skipped,
s.errors,
s.suspect,
s.metadata,
s.packages,
],
)
}
/// Plain human-readable rendering, independent of the destination terminal.
/// Plain English rendering, independent of the destination terminal.
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
/// and JSON remain unstyled; callers select the destination's color policy.
/// Console rendering in the process language. Report data and JSON remain
/// unstyled; callers select the destination's color policy.
pub fn render_text_with_palette(&self, palette: crate::ui::Palette) -> String {
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;
let mut text = String::new();
if let Some(scan) = self.scan {
text.push_str(&format!(
"{}: {} probed non-targets · {} walk errors · {} probe errors\n",
palette.paint(Tone::Heading, "scan"),
scan.non_target_skipped,
scan.walk_errors,
scan.probe_errors
"{}: {}\n",
palette.paint(Tone::Heading, Cli::ReportScanHeading.localize(lang)),
Cli::ReportScan {
skipped: scan.non_target_skipped,
walk_errors: scan.walk_errors,
probe_errors: scan.probe_errors,
}
.localize(lang)
));
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 {
text.push_str(&text::render_input(input, palette));
text.push_str(&text::render_input(input, palette, lang));
}
for error in &self.errors {
text.push_str(&format!(
"{}: {error}\n",
palette.paint(Tone::Error, "error")
));
text.push_str(&crate::ui::error_lines(palette, lang, error));
}
text
}
@@ -539,7 +557,10 @@ pub struct Collector {
scan: Option<ScanReport>,
inputs: Vec<InputReport>,
summary: SummaryReport,
errors: Vec<String>,
errors: Vec<Message>,
observer: Option<Arc<dyn crate::observe::RunObserver>>,
cancel: Option<crate::observe::CancelToken>,
cancelled: bool,
}
impl Collector {
@@ -551,9 +572,41 @@ impl Collector {
inputs: Vec::new(),
summary: SummaryReport::default(),
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 {
self.mode
}
@@ -585,9 +638,9 @@ impl Collector {
// Research inspection and dry runs keep their actual recovery
// outcomes, but never advertise temporary artifacts as outputs.
let discarded = if self.mode == Mode::Inspect {
"research inspection: no output file was retained"
Msg::OutputNotRetained
} else {
"dry run: the produced output was discarded"
Msg::DryRunDiscarded
};
if !input.outputs.is_empty() {
// The produced byte count is a real result of the attempt even
@@ -605,7 +658,7 @@ impl Collector {
for stage in &mut input.stages {
if stage.stage == Stage::OutputWrite {
stage.status = StageStatus::Skipped;
stage.detail = Some(discarded.to_owned());
stage.detail = Some(Message::new(discarded.clone()));
}
}
if !input
@@ -650,6 +703,9 @@ impl Collector {
InputStatus::Skipped => self.summary.skipped += 1,
InputStatus::Error => self.summary.errors += 1,
}
if let Some(observer) = &self.observer {
observer.input_finished(&input);
}
self.inputs.push(input);
}
@@ -658,7 +714,7 @@ impl Collector {
}
/// 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());
}
@@ -675,6 +731,7 @@ impl Collector {
summary: self.summary,
errors: self.errors,
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
/// 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));
profile.recognition = RecognitionStatus::Recognized;
profile.candidates = vec![senbei_engine::LayoutAttempt {
layout: LayoutKind::AndroidStaged,
outcome: AttemptOutcome::Failed,
warnings: Vec::new(),
errors: vec![error.to_owned()],
errors: vec![error.clone()],
}];
profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_owned());
profile.push_error(error.clone());
profile
}
@@ -773,7 +830,7 @@ pub(crate) fn metadata_unchanged_profile(
pub(crate) fn metadata_failed_profile(
identity: Option<senbei_metadata::MetadataIdentity>,
route: LayoutKind,
error: &str,
error: &Message,
) -> ProtectionProfile {
let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata(
identity.map(|identity| identity.raw_version),
@@ -785,10 +842,10 @@ pub(crate) fn metadata_failed_profile(
layout: route,
outcome: AttemptOutcome::Failed,
warnings: Vec::new(),
errors: vec![error.to_owned()],
errors: vec![error.clone()],
}];
profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_owned());
profile.push_error(error.clone());
profile.static_validation = ValidationStatus::NotRun;
profile
}
@@ -812,7 +869,7 @@ mod tests {
let profile = metadata_failed_profile(
senbei_metadata::identify(&header),
LayoutKind::MetadataStructural,
"transform did not validate",
&"transform did not validate".into(),
);
assert_eq!(profile.observed.metadata_version, Some(version));
assert_eq!(profile.recognition, RecognitionStatus::Blocked);
@@ -932,7 +989,7 @@ mod tests {
entry.analysis_incomplete = true;
entry
.errors
.push("resource ceiling prevented restoration".to_owned());
.push("resource ceiling prevented restoration".into());
input.entries.push(entry);
let mut collector = Collector::new(Mode::Inspect);
collector.push(input);
+264 -165
View File
@@ -1,8 +1,14 @@
//! 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 senbei_engine::windows::{ResearchTrace, TraceValue, WindowsInspection};
use senbei_i18n::{Cli, Lang, Localize, Message, Term};
use serde::Serialize;
use serde_json::Value;
@@ -12,15 +18,26 @@ use crate::ui::{Painted, Palette, Tone};
struct Text {
contents: String,
palette: Palette,
lang: Lang,
}
impl Text {
#[cfg(test)]
fn new(palette: Palette) -> Self {
Self::in_language(palette, Lang::En)
}
fn in_language(palette: Palette, lang: Lang) -> Self {
Self {
contents: String::new(),
palette,
lang,
}
}
fn say(&self, line: Cli) -> String {
line.localize(self.lang).into_owned()
}
}
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> {
let normalized = value.replace('_', " ");
let tone = match normalized.as_str() {
palette.paint(tone_of(&value), value)
}
/// 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"
| "validated" => Tone::Success,
"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"
| "not recognized" => Tone::Muted,
_ => Tone::Value,
};
palette.paint(tone, value)
}
}
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> {
let tone = if value.is_some() {
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 {
let mut text = Text::new(palette);
let _ = writeln!(text, "{}", palette.paint(Tone::Heading, &input.path));
if input.analysis_incomplete {
/// How a finding is labelled in the summary part of a report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Finding {
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!(
text,
" {}: I/O, resource limits or infrastructure prevented the requested work",
palette.paint(Tone::Error, "analysis incomplete")
"{indent}{}: {line}",
palette.paint(kind.tone(), &label)
);
}
if let Some(source) = &input.source {
let _ = writeln!(
text,
" source: {} bytes (0x{:X})",
source.size, source.size
if let Some(english) = message.detail(text.lang) {
let label = text.say(Cli::DiagnosticEnglish);
for line in english.lines() {
let _ = writeln!(
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!(
text,
" SHA-256: {}",
@@ -107,72 +194,73 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
}
if let Some(profile) = &input.profile {
let target = &profile.observed;
let _ = writeln!(
text,
" target: {} · {} · {}",
label(&target.platform),
target
let line = text.say(Cli::Target {
platform: term(lang, &target.platform),
format: target
.format
.as_ref()
.map(label)
.unwrap_or_else(|| "format unavailable".to_owned()),
target
.map(|format| term(lang, format))
.unwrap_or_else(|| text.say(Cli::FormatUnavailable)),
kind: target
.kind
.as_ref()
.map(label)
.unwrap_or_else(|| "kind not applicable or unavailable".to_owned())
);
let _ = writeln!(
text,
" protection recognition: {}",
status(palette, &profile.recognition)
);
.map(|kind| term(lang, kind))
.unwrap_or_else(|| text.say(Cli::KindUnavailable)),
});
let _ = writeln!(text, " {line}");
let line = text.say(Cli::ProtectionRecognition {
status: term_status(&text, &profile.recognition),
});
let _ = writeln!(text, " {line}");
if !profile.evidence.is_empty() {
let evidence = profile
.evidence
.iter()
.map(label)
.map(|evidence| term(lang, evidence))
.collect::<Vec<_>>()
.join(", ");
let _ = writeln!(text, " evidence: {evidence}");
let line = text.say(Cli::Evidence { evidence });
let _ = writeln!(text, " {line}");
}
for candidate in &profile.candidates {
let _ = writeln!(
text,
" route {}: {}",
palette.paint(Tone::Label, label(&candidate.layout)),
status(palette, &candidate.outcome)
);
let line = text.say(Cli::Route {
route: palette
.paint(Tone::Label, term(lang, &candidate.layout))
.to_string(),
outcome: term_status(&text, &candidate.outcome),
});
let _ = writeln!(text, " {line}");
for message in &candidate.warnings {
diagnostic(&mut text, " ", "warning", message);
finding(&mut text, " ", Finding::Warning, message);
}
for message in &candidate.errors {
diagnostic(&mut text, " ", "reason", message);
finding(&mut text, " ", Finding::Reason, message);
}
}
if let Some(selected) = profile.selected {
let _ = writeln!(
text,
" selected route: {}",
palette.paint(Tone::Success, label(&selected))
);
let line = text.say(Cli::SelectedRoute {
route: palette
.paint(Tone::Success, term(lang, &selected))
.to_string(),
});
let _ = writeln!(text, " {line}");
}
let _ = writeln!(
text,
" static recovery: {}",
status(palette, &profile.recovery)
);
let _ = writeln!(
text,
" output static validation: {}",
status(palette, &profile.static_validation)
);
let line = text.say(Cli::StaticRecovery {
status: term_status(&text, &profile.recovery),
});
let _ = writeln!(text, " {line}");
let line = text.say(Cli::OutputValidation {
status: term_status(&text, &profile.static_validation),
});
let _ = writeln!(text, " {line}");
}
if let Some(companion) = &input.companion {
let line = text.say(Cli::Companion {
state: term_status(&text, &companion.state),
});
let _ = writeln!(
text,
" companion: {}{}",
status(palette, &companion.state),
" {line}{}",
companion
.path
.as_ref()
@@ -180,27 +268,24 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
.unwrap_or_default()
);
if let Some(source) = &companion.source {
let _ = writeln!(
text,
" {} bytes · SHA-256 {}",
source.size, source.sha256
);
let line = text.say(Cli::CompanionIdentity {
size: source.size,
sha256: source.sha256.clone(),
});
let _ = writeln!(text, " {line}");
}
if let Some(detail) = &companion.detail {
diagnostic(&mut text, " ", "detail", detail);
finding(&mut text, " ", Finding::Detail, detail);
}
}
if let Some(research) = &input.research {
let _ = writeln!(
text,
" analysis input view: {}",
label(&research.input_view)
);
let line = text.say(Cli::InputView {
view: term(lang, &research.input_view),
});
let _ = writeln!(text, " {line}");
if research.input_view == super::ResearchInputView::SplicedCompanion {
let _ = writeln!(
text,
" file offsets below 0x1000 address the stub; offsets at/above 0x1000 address companion offset (file offset - 0x1000)"
);
let line = text.say(Cli::InputViewSplicedNote);
let _ = writeln!(text, " {line}");
}
render_windows(&mut text, "protected input", &research.input);
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 {
let _ = writeln!(
text,
" IL2CPP metadata version: {} · layout definition {}",
metadata.raw_version,
label(&metadata.layout)
);
let _ = writeln!(
text,
" seeded method tokens: {}",
metadata.capabilities.seeded_method_tokens
);
let _ = writeln!(
text,
" structural method tokens: {}",
metadata.capabilities.structural_method_tokens
);
let _ = writeln!(
text,
" method-index restoration: {} · application context required: {}",
metadata.capabilities.method_index_restore,
metadata.capabilities.method_index_requires_context
);
let identity = text.say(Cli::MetadataIdentity {
version: metadata.raw_version,
layout: term(lang, &metadata.layout),
});
let _ = writeln!(text, " {identity}");
let capabilities = &metadata.capabilities;
for line in [
Cli::SeededTokens {
value: capabilities.seeded_method_tokens,
},
Cli::StructuralTokens {
value: capabilities.structural_method_tokens,
},
Cli::MethodIndexRestore {
value: capabilities.method_index_restore,
context: capabilities.method_index_requires_context,
},
] {
let line = text.say(line);
let _ = writeln!(text, " {line}");
}
}
if let Some(container) = &input.container {
let _ = writeln!(
text,
" container: {} · {} entries · {} manifests",
container.kind,
container.entry_count,
container.manifests.len()
);
let line = text.say(Cli::Container {
kind: container.kind.clone(),
entries: container.entry_count,
manifests: container.manifests.len(),
});
let _ = writeln!(text, " {line}");
for manifest in &container.manifests {
let _ = writeln!(
text,
" manifest {} → {} {}",
manifest.source,
manifest.package.as_deref().unwrap_or("<unnamed>"),
manifest.version.as_deref().unwrap_or("")
);
let line = text.say(Cli::Manifest {
source: manifest.source.clone(),
package: manifest
.package
.clone()
.unwrap_or_else(|| text.say(Cli::Unnamed)),
version: manifest.version.clone().unwrap_or_default(),
});
let _ = writeln!(text, " {line}");
}
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 {
render_android(&mut text, " ", research);
}
if let Some(research) = &input.metadata_research {
let _ = writeln!(
text,
" {}:",
palette.paint(Tone::Heading, "metadata transform evidence")
);
let heading = text.say(Cli::MetadataEvidence);
let _ = writeln!(text, " {}:", palette.paint(Tone::Heading, heading));
render_tree(&mut text, " ", research);
}
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!(
text,
" entry {}: {}{}",
palette.paint(Tone::Label, &entry.name),
status(palette, &entry.status),
" {line}{}",
entry
.output
.as_ref()
@@ -295,90 +382,102 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
.unwrap_or_default()
);
if entry.analysis_incomplete {
let _ = writeln!(
text,
" {}: requested entry analysis could not finish",
palette.paint(Tone::Error, "analysis incomplete")
let line = format!(
" {}: {}",
palette.paint(Tone::Error, text.say(Cli::AnalysisIncomplete)),
text.say(Cli::AnalysisIncompleteEntry)
);
let _ = writeln!(text, "{line}");
}
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 {
let _ = writeln!(text, " metadata version: {version}");
let line = text.say(Cli::EntryMetadataVersion { version });
let _ = writeln!(text, " {line}");
}
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 {
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 {
diagnostic(&mut text, " ", "warning", message);
finding(&mut text, " ", Finding::Warning, message);
}
for message in &entry.errors {
diagnostic(&mut text, " ", "error", message);
finding(&mut text, " ", Finding::Error, message);
}
if let Some(research) = &entry.android_research {
render_android(&mut text, " ", research);
}
if let Some(research) = &entry.metadata_research {
let _ = writeln!(
text,
" {}:",
palette.paint(Tone::Heading, "metadata transform evidence")
);
let heading = text.say(Cli::MetadataEvidence);
let _ = writeln!(text, " {}:", palette.paint(Tone::Heading, heading));
render_tree(&mut text, " ", research);
}
}
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 {
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!(
text,
" stage {}: {}{}",
palette.paint(Tone::Label, label(&stage.stage)),
status(palette, &stage.status),
" {line}{}",
stage
.duration_ms
.map(|elapsed| format!(" · {elapsed} ms"))
.unwrap_or_default()
);
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();
for (kind, messages) in [("warning", &input.warnings), ("error", &input.errors)] {
for message in messages {
if seen.insert((kind, message.as_str())) {
diagnostic(&mut text, " ", kind, message);
}
}
}
let mut findings = vec![
(Finding::Warning, &input.warnings),
(Finding::Error, &input.errors),
];
if let Some(profile) = &input.profile {
for (kind, messages) in [("warning", &profile.warnings), ("error", &profile.errors)] {
for message in messages {
if seen.insert((kind, message.as_str())) {
diagnostic(&mut text, " ", kind, message);
}
findings.push((Finding::Warning, &profile.warnings));
findings.push((Finding::Error, &profile.errors));
}
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 {
let _ = writeln!(
text,
" recovered: {} bytes · SHA-256 {}",
recovered.size, recovered.sha256
);
let line = text.say(Cli::Recovered {
size: recovered.size,
sha256: recovered.sha256.clone(),
});
let _ = writeln!(text, " {line}");
}
let _ = writeln!(
text,
" inspection status: {} · {} ms",
status(palette, &input.status),
input.duration_ms
);
let line = text.say(Cli::InspectionStatus {
status: term_status(&text, &input.status),
ms: input.duration_ms,
});
let _ = writeln!(text, " {line}");
text.contents
}
@@ -921,8 +1020,8 @@ mod tests {
StageReport::new(Stage::Recovery, StageStatus::Failed)
.detail("parameters were unavailable"),
);
let text = render_input(&input, Palette::plain());
let colored = render_input(&input, Palette::colored());
let text = render_input(&input, Palette::plain(), Lang::En);
let colored = render_input(&input, Palette::colored(), Lang::En);
assert!(colored.contains('\x1b'));
assert_eq!(strip_styles(&colored), text);
for fact in [
@@ -991,8 +1090,8 @@ mod tests {
});
input.metadata_research =
Some(serde_json::json!({"tried_seeds": [0x5678], "route": "seeded"}));
let text = render_input(&input, Palette::plain());
let colored = render_input(&input, Palette::colored());
let text = render_input(&input, Palette::plain(), Lang::En);
let colored = render_input(&input, Palette::colored(), Lang::En);
assert!(colored.contains('\x1b'));
assert_eq!(strip_styles(&colored), text);
for fact in [
+135 -9
View File
@@ -1,6 +1,7 @@
use indicatif::{ProgressBar, ProgressStyle};
use owo_colors::Style;
use senbei_engine::{IntegrityReport, Kind};
use senbei_i18n::{Cli, Lang, Localize, Message, Step};
use std::cell::Cell;
use std::fmt::{self, Display};
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)
}
/// 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 {
match mode {
ColorMode::Auto => terminal && !no_color && !dumb,
@@ -220,12 +326,15 @@ pub fn metadata(bar: &ProgressBar, quiet: bool, rel: &Path, remapped: usize, des
return;
}
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!(
"{} metadata {} -> {} ({} method fields remapped)",
"{} {}",
palette.paint(Tone::Success, "✓"),
palette.paint(Tone::Label, rel.display()),
palette.paint(Tone::Value, dest.display()),
palette.paint(Tone::Value, remapped)
line.localize(senbei_i18n::current())
);
bar.suspend(|| println!("{msg}"));
}
@@ -236,11 +345,17 @@ pub fn err(bar: &ProgressBar, quiet: bool, rel: &Path, e: &anyhow::Error) {
return;
}
let palette = Palette::stderr();
let msg = format!(
"{} {} {e:#}",
let lang = senbei_i18n::current();
let message = crate::message::of_error(e);
let mut msg = format!(
"{} {} {}",
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}"));
}
@@ -251,16 +366,27 @@ pub fn suspect(bar: &ProgressBar, quiet: bool, rel: &Path, report: &IntegrityRep
return;
}
let palette = Palette::stderr();
let lang = senbei_i18n::current();
let msg = format!(
"{} {} {}: {}",
palette.paint(Tone::Warning, "!"),
palette.paint(Tone::Label, rel.display()),
palette.paint(Tone::Warning, "integrity check failed"),
report.issues.join("; ")
palette.paint(Tone::Warning, Cli::IntegrityFailed.localize(lang)),
issues(report, lang)
);
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)]
mod tests {
use super::*;
+1 -1
View File
@@ -672,7 +672,7 @@ pub fn unpack_one_v(
}
write_atomic(dest, &out)?;
if verbose {
println!("Write to {}", dest.display());
crate::ui::write_to(dest, false);
}
Ok((kind, report))
}
+9
View File
@@ -453,6 +453,7 @@ dependencies = [
"memmap2",
"senbei-crypto",
"senbei-elf",
"senbei-i18n",
"senbei-pe",
"serde",
"serde_json",
@@ -461,6 +462,13 @@ dependencies = [
"thiserror",
]
[[package]]
name = "senbei-i18n"
version = "1.3.4"
dependencies = [
"serde",
]
[[package]]
name = "senbei-io"
version = "1.3.4"
@@ -473,6 +481,7 @@ dependencies = [
"senbei-crypto",
"senbei-elf",
"senbei-engine",
"senbei-i18n",
"senbei-metadata",
"senbei-pe",
"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
/// reads (`issues[i]` and `severities[i]` describe the same defect).
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 fatal = false;
for finding in &report.findings {
@@ -325,7 +329,7 @@ fn metadata_outcome(data: &[u8]) -> (Option<u32>, ProtectionProfile, MetadataTra
layout: route,
outcome: AttemptOutcome::Failed,
warnings: Vec::new(),
errors: vec![error.to_string()],
errors: vec![error.to_string().into()],
}];
profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_string());