mirror of
https://github.com/Momoko-Ayase/Senbei.git
synced 2026-11-24 18:52:47 +08:00
fix(inspect): collect full static recovery research by default
Inspect the protected input and actual recovered image, with bounded structural evidence, source identities and scoped recovery traces. Keep ordinary unpack lightweight and retain no research output files or logs. Preserve Android extraction, restoration and metadata evidence, distinguish incomplete analyses from rejected candidates, and render detailed text and JSON reports with explicit address provenance.
This commit is contained in:
1 parent
05a4337a5e
commit
1ee4344c1e
22 files changed
+7776
-758
No files matched your search
@@ -7,7 +7,7 @@ use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use senbei_engine::android::ResourceLimits;
|
||||
use senbei_engine::android::{LimitExceeded, ResourceLimits};
|
||||
use zip::ZipArchive;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
@@ -180,14 +180,25 @@ impl ArchiveBudget {
|
||||
label: &str,
|
||||
) -> Result<Vec<u8>> {
|
||||
if size > self.max_entry_bytes {
|
||||
bail!(
|
||||
return Err(anyhow::Error::new(LimitExceeded::Entry {
|
||||
requested: size,
|
||||
limit: self.max_entry_bytes,
|
||||
})
|
||||
.context(format!(
|
||||
"entry `{label}` exceeds extraction limit {}",
|
||||
self.max_entry_bytes
|
||||
);
|
||||
)));
|
||||
}
|
||||
let length = size.min(maximum as u64);
|
||||
if length > self.max_total_bytes.saturating_sub(self.bytes) {
|
||||
bail!("manifest `{label}` exceeds the remaining extraction byte limit");
|
||||
return Err(anyhow::Error::new(LimitExceeded::Total {
|
||||
requested: self.bytes.saturating_add(length),
|
||||
adding: length,
|
||||
limit: self.max_total_bytes,
|
||||
})
|
||||
.context(format!(
|
||||
"manifest `{label}` exceeds the remaining extraction byte limit"
|
||||
)));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
bytes
|
||||
@@ -203,10 +214,14 @@ impl ArchiveBudget {
|
||||
.checked_add(entries)
|
||||
.context("archive entry count overflow")?;
|
||||
if total > self.max_entries {
|
||||
bail!(
|
||||
return Err(anyhow::Error::new(LimitExceeded::Entries {
|
||||
requested: total,
|
||||
limit: self.max_entries,
|
||||
})
|
||||
.context(format!(
|
||||
"archive entry limit exceeded: {total} > {}",
|
||||
self.max_entries
|
||||
);
|
||||
)));
|
||||
}
|
||||
self.entries = total;
|
||||
Ok(())
|
||||
@@ -222,9 +237,21 @@ impl ArchiveBudget {
|
||||
let remaining = self.max_total_bytes.saturating_sub(self.bytes);
|
||||
let allowance = self.max_entry_bytes.min(remaining);
|
||||
if declared_size > allowance {
|
||||
bail!(
|
||||
let exceeded = if declared_size > self.max_entry_bytes {
|
||||
LimitExceeded::Entry {
|
||||
requested: declared_size,
|
||||
limit: self.max_entry_bytes,
|
||||
}
|
||||
} else {
|
||||
LimitExceeded::Total {
|
||||
requested: self.bytes.saturating_add(declared_size),
|
||||
adding: declared_size,
|
||||
limit: self.max_total_bytes,
|
||||
}
|
||||
};
|
||||
return Err(anyhow::Error::new(exceeded).context(format!(
|
||||
"entry `{label}` declares {declared_size} bytes, exceeding extraction limit {allowance}"
|
||||
);
|
||||
)));
|
||||
}
|
||||
// The advertised size is a stricter ceiling when it is smaller than
|
||||
// the budget. A dishonest header must not buy extra decompression work.
|
||||
@@ -243,7 +270,13 @@ impl ArchiveBudget {
|
||||
.checked_add(read as u64)
|
||||
.context("decompressed entry size overflow")?;
|
||||
if next > limit {
|
||||
bail!("entry `{label}` exceeds extraction limit {limit} while decompressing");
|
||||
return Err(anyhow::Error::new(LimitExceeded::Entry {
|
||||
requested: next,
|
||||
limit,
|
||||
})
|
||||
.context(format!(
|
||||
"entry `{label}` exceeds extraction limit {limit} while decompressing"
|
||||
)));
|
||||
}
|
||||
self.bytes = self
|
||||
.bytes
|
||||
@@ -346,7 +379,11 @@ fn inspect_archive(
|
||||
bail!("invalid ZIP64 end record");
|
||||
}
|
||||
if qword(&record, 4) > max_directory_bytes {
|
||||
bail!("ZIP64 metadata exceeds the directory memory limit");
|
||||
return Err(anyhow::Error::new(LimitExceeded::Entry {
|
||||
requested: qword(&record, 4),
|
||||
limit: max_directory_bytes,
|
||||
})
|
||||
.context("ZIP64 metadata exceeds the directory memory limit"));
|
||||
}
|
||||
zip64_record = Some(record_offset);
|
||||
directory_start = qword(&record, 48);
|
||||
@@ -356,10 +393,22 @@ fn inspect_archive(
|
||||
bail!("inconsistent ZIP entry counts");
|
||||
}
|
||||
if entries > max_entries as u64 {
|
||||
bail!("archive entry limit exceeded: {entries} > {max_entries}");
|
||||
return Err(anyhow::Error::new(LimitExceeded::Entries {
|
||||
requested: usize::try_from(entries).unwrap_or(usize::MAX),
|
||||
limit: max_entries,
|
||||
})
|
||||
.context(format!(
|
||||
"archive entry limit exceeded: {entries} > {max_entries}"
|
||||
)));
|
||||
}
|
||||
if directory_bytes > max_directory_bytes {
|
||||
bail!("ZIP directory size {directory_bytes} exceeds memory limit {max_directory_bytes}");
|
||||
return Err(anyhow::Error::new(LimitExceeded::Entry {
|
||||
requested: directory_bytes,
|
||||
limit: max_directory_bytes,
|
||||
})
|
||||
.context(format!(
|
||||
"ZIP directory size {directory_bytes} exceeds memory limit {max_directory_bytes}"
|
||||
)));
|
||||
}
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
Ok(ArchiveInfo {
|
||||
@@ -420,6 +469,51 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_ceilings_keep_typed_causes_and_context() {
|
||||
let mut budget = ArchiveBudget::new(4, 6, 1);
|
||||
budget.register_entries(1).unwrap();
|
||||
let error = budget.register_entries(1).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<LimitExceeded>(),
|
||||
Some(LimitExceeded::Entries { .. })
|
||||
));
|
||||
assert!(format!("{error:#}").contains("entry limit"));
|
||||
|
||||
let error = budget
|
||||
.read_probe(&mut Cursor::new(b"abcde"), 5, 5, "manifest")
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<LimitExceeded>(),
|
||||
Some(LimitExceeded::Entry { .. })
|
||||
));
|
||||
let error = budget
|
||||
.copy_entry(&mut Cursor::new(b"abcde"), &mut Vec::new(), 5, "large")
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<LimitExceeded>(),
|
||||
Some(LimitExceeded::Entry { .. })
|
||||
));
|
||||
assert!(format!("{error:#}").contains("extraction limit"));
|
||||
budget
|
||||
.copy_entry(&mut Cursor::new(b"abcd"), &mut Vec::new(), 4, "first")
|
||||
.unwrap();
|
||||
let error = budget
|
||||
.copy_entry(&mut Cursor::new(b"abc"), &mut Vec::new(), 3, "second")
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<LimitExceeded>(),
|
||||
Some(LimitExceeded::Total { .. })
|
||||
));
|
||||
let error = budget
|
||||
.read_probe(&mut Cursor::new(b"abc"), 3, 3, "manifest")
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<LimitExceeded>(),
|
||||
Some(LimitExceeded::Total { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_writes_still_consume_the_read_budget() {
|
||||
struct FailingWriter;
|
||||
@@ -457,8 +551,16 @@ mod tests {
|
||||
fn preflight_rejects_large_counts_and_directory_before_indexing() {
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
file.write_all(&end_record(50, 1000)).unwrap();
|
||||
assert!(preflight_archive(&mut file, 49, 1000).is_err());
|
||||
assert!(preflight_archive(&mut file, 50, 999).is_err());
|
||||
let count_error = preflight_archive(&mut file, 49, 1000).unwrap_err();
|
||||
assert!(matches!(
|
||||
count_error.downcast_ref::<LimitExceeded>(),
|
||||
Some(LimitExceeded::Entries { .. })
|
||||
));
|
||||
let size_error = preflight_archive(&mut file, 50, 999).unwrap_err();
|
||||
assert!(matches!(
|
||||
size_error.downcast_ref::<LimitExceeded>(),
|
||||
Some(LimitExceeded::Entry { .. })
|
||||
));
|
||||
assert_eq!(preflight_archive(&mut file, 50, 1000).unwrap(), 50);
|
||||
}
|
||||
|
||||
|
||||
@@ -78,6 +78,10 @@ pub(crate) enum ContextAmbiguity {
|
||||
pub(crate) struct AndroidRunCache {
|
||||
pub(super) limits: senbei_engine::android::ResourceLimits,
|
||||
pub(super) archive: super::archive_limits::ArchiveBudget,
|
||||
/// Capture the engine's own extraction/restoration reports for research
|
||||
/// inspection. Off for every ordinary run: the reports are large and are
|
||||
/// discarded after each restore.
|
||||
pub(super) research: bool,
|
||||
apps: HashMap<AppKey, ApplicationModules>,
|
||||
/// Successfully restored protected libraries, keyed by encrypted content.
|
||||
libraries: HashMap<String, CachedLibrary>,
|
||||
@@ -121,6 +125,11 @@ impl AndroidRunCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this run keeps the engines' own reports for research output.
|
||||
pub(crate) fn research(&self) -> bool {
|
||||
self.research
|
||||
}
|
||||
|
||||
pub(crate) fn modules_mut(&mut self, key: &AppKey) -> &mut ApplicationModules {
|
||||
self.apps.entry(key.clone()).or_default()
|
||||
}
|
||||
@@ -495,6 +504,9 @@ pub(crate) struct RestoredLibrary {
|
||||
/// test double, or an engine without a validation pass) — never that the
|
||||
/// output validated. `Some(empty)` is a completed, clean validation.
|
||||
pub validation: Option<super::ValidationDiagnostics>,
|
||||
/// The extraction and restoration reports this restore actually produced,
|
||||
/// kept only when the run asked for research output. `None` otherwise.
|
||||
pub research: Option<crate::report::AndroidResearchReport>,
|
||||
}
|
||||
|
||||
/// Injectable library restore. Tests supply a fake so application-context
|
||||
@@ -513,10 +525,27 @@ pub(crate) trait LibraryRestorer {
|
||||
|
||||
/// Production restorer: stage-2 extract, ELF rebuild, embedded metadata unwrap.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct EngineRestorer(pub(super) senbei_engine::android::ResourceLimits);
|
||||
pub(crate) struct EngineRestorer {
|
||||
pub(super) limits: senbei_engine::android::ResourceLimits,
|
||||
/// Keep the engines' reports instead of dropping them after each restore.
|
||||
pub(super) research: bool,
|
||||
}
|
||||
|
||||
impl EngineRestorer {
|
||||
/// A restorer for `limits`, keeping the engines' reports only for research.
|
||||
pub(crate) fn new(limits: senbei_engine::android::ResourceLimits, research: bool) -> Self {
|
||||
Self { limits, research }
|
||||
}
|
||||
}
|
||||
|
||||
impl LibraryRestorer for EngineRestorer {
|
||||
fn restore(&mut self, input: &Path, dest: &Path, verbose: bool) -> Result<RestoredLibrary> {
|
||||
crate::android::restore_so_with_engine_limits(input, dest, verbose, &self.0)
|
||||
crate::android::restore_so_with_engine_limits(
|
||||
input,
|
||||
dest,
|
||||
verbose,
|
||||
&self.limits,
|
||||
self.research,
|
||||
)
|
||||
}
|
||||
}
|
||||
+480
-94
@@ -254,27 +254,6 @@ pub fn is_protected_so_file(path: &Path) -> bool {
|
||||
is_elf64_aarch64(&bytes) && is_protected_libil2cpp(&bytes)
|
||||
}
|
||||
|
||||
/// [`probe_so_file_with_limits`] with the recognition profile it produced.
|
||||
///
|
||||
/// A resource-limit failure is reported as `Blocked` with the error retained,
|
||||
/// never as "not protected".
|
||||
pub(crate) fn probe_so_profiled(
|
||||
path: &Path,
|
||||
limits: &ResourceLimits,
|
||||
) -> Result<(senbei_engine::ProtectionProfile, Result<bool, String>)> {
|
||||
let file = File::open(path).with_context(|| format!("open `{}`", path.display()))?;
|
||||
let bytes = map_read_only(&file, path)?;
|
||||
if !is_elf64_aarch64(&bytes) {
|
||||
return Ok((
|
||||
senbei_engine::ProtectionProfile::new(senbei_engine::ObservedTarget::android(None)),
|
||||
Ok(false),
|
||||
));
|
||||
}
|
||||
let (profile, result) =
|
||||
senbei_engine::android::probe_libil2cpp_profiled_with_limits(&bytes, limits);
|
||||
Ok((profile, result.map_err(|error| error.to_string())))
|
||||
}
|
||||
|
||||
pub(crate) fn probe_so_file_with_limits(
|
||||
path: &Path,
|
||||
limits: &senbei_engine::android::ResourceLimits,
|
||||
@@ -311,6 +290,7 @@ pub(crate) fn restore_so_with_engine_limits(
|
||||
dest: &Path,
|
||||
verbose: bool,
|
||||
limits: &ResourceLimits,
|
||||
research: bool,
|
||||
) -> Result<context::RestoredLibrary> {
|
||||
let temporary = tempfile::tempdir().context("create stage-2 workspace")?;
|
||||
let stage2_dir = temporary.path().join("stage2");
|
||||
@@ -319,6 +299,14 @@ pub(crate) fn restore_so_with_engine_limits(
|
||||
limits,
|
||||
)
|
||||
.context("extract stage-1/stage-2 payload")?;
|
||||
// The report the extraction just produced. Serialized once, only for
|
||||
// research runs; an ordinary run drops it with the rest of the workspace.
|
||||
let extraction_report = research.then(|| {
|
||||
report_value(
|
||||
&extraction,
|
||||
&[(input, "<input>"), (temporary.path(), "<workspace>")],
|
||||
)
|
||||
});
|
||||
// Every module 0x0C is collected. Two distinct images in one library are a
|
||||
// conflict for that library's application, not a last-writer-wins update.
|
||||
let mut modules = Vec::new();
|
||||
@@ -357,8 +345,37 @@ pub(crate) fn restore_so_with_engine_limits(
|
||||
verbose,
|
||||
},
|
||||
limits,
|
||||
)
|
||||
.context("restore protected library")?;
|
||||
);
|
||||
// A restore that failed after extraction is still a research finding: the
|
||||
// extraction's seeds, records and modules are already known, and the
|
||||
// original failure travels with them so nothing is lost.
|
||||
let report = match report {
|
||||
Ok(report) => report,
|
||||
Err(error) => {
|
||||
let restored = extraction_report
|
||||
.map(|extraction| crate::report::AndroidResearchReport {
|
||||
extraction,
|
||||
restoration: None,
|
||||
})
|
||||
.map(ResearchCapture::Library);
|
||||
return Err(capture(
|
||||
anyhow::Error::new(error).context("restore protected library"),
|
||||
restored,
|
||||
));
|
||||
}
|
||||
};
|
||||
// The same restore's own report, serialized once for research output
|
||||
// before the validation diagnostics are taken out of it below.
|
||||
let restoration = research.then(|| {
|
||||
report_value(
|
||||
&report,
|
||||
&[
|
||||
(input, "<input>"),
|
||||
(dest, "<output>"),
|
||||
(temporary.path(), "<workspace>"),
|
||||
],
|
||||
)
|
||||
});
|
||||
// Keep only the validation verdict this call already produced. Nothing is
|
||||
// re-read or re-validated: the diagnostics describe the bytes just written.
|
||||
let validation = Some(ValidationDiagnostics {
|
||||
@@ -372,6 +389,13 @@ pub(crate) fn restore_so_with_engine_limits(
|
||||
method_index_module,
|
||||
module_image,
|
||||
validation,
|
||||
research: match (extraction_report, restoration) {
|
||||
(Some(extraction), restoration) => Some(crate::report::AndroidResearchReport {
|
||||
extraction,
|
||||
restoration,
|
||||
}),
|
||||
_ => None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -400,10 +424,36 @@ pub fn restore_so_file_with_diagnostics(
|
||||
verbose: bool,
|
||||
limits: &ResourceLimits,
|
||||
) -> Result<(Option<Vec<u8>>, Option<ValidationDiagnostics>)> {
|
||||
let restored = context::EngineRestorer(*limits).restore(input, dest, verbose)?;
|
||||
let restored = context::EngineRestorer::new(*limits, false).restore(input, dest, verbose)?;
|
||||
Ok((restored.embedded_metadata, restored.validation))
|
||||
}
|
||||
|
||||
/// One single-file Android library restore.
|
||||
pub(crate) struct ResearchedLibrary {
|
||||
pub embedded_metadata: Option<Vec<u8>>,
|
||||
/// Structural diagnostics for the image this restore wrote.
|
||||
pub validation: Option<ValidationDiagnostics>,
|
||||
/// The engines' own reports, kept only when research was requested.
|
||||
pub research: Option<crate::report::AndroidResearchReport>,
|
||||
}
|
||||
|
||||
/// [`restore_so_file_with_diagnostics`], also keeping the engines' own reports
|
||||
/// for research output. Nothing else changes: the same single restore runs.
|
||||
pub(crate) fn restore_so_file_researched(
|
||||
input: &Path,
|
||||
dest: &Path,
|
||||
verbose: bool,
|
||||
limits: &ResourceLimits,
|
||||
research: bool,
|
||||
) -> Result<ResearchedLibrary> {
|
||||
let restored = context::EngineRestorer::new(*limits, research).restore(input, dest, verbose)?;
|
||||
Ok(ResearchedLibrary {
|
||||
embedded_metadata: restored.embedded_metadata,
|
||||
validation: restored.validation,
|
||||
research: restored.research,
|
||||
})
|
||||
}
|
||||
|
||||
/// Fresh run-scoped cache. Library hits reuse their module context; metadata hits
|
||||
/// are keyed by encrypted bytes and the module that recovered them.
|
||||
#[cfg(test)]
|
||||
@@ -415,6 +465,13 @@ pub(crate) fn run_cache_with_limits(limits: &ResourceLimits) -> context::Android
|
||||
context::AndroidRunCache::with_limits(limits)
|
||||
}
|
||||
|
||||
/// The same cache, keeping the engines' reports for research output.
|
||||
pub(crate) fn run_cache_for_research(limits: &ResourceLimits) -> context::AndroidRunCache {
|
||||
let mut cache = context::AndroidRunCache::with_limits(limits);
|
||||
cache.research = true;
|
||||
cache
|
||||
}
|
||||
|
||||
/// Assign loose libraries and metadata to application contexts.
|
||||
pub(crate) fn loose_scopes(
|
||||
libraries: &[PathBuf],
|
||||
@@ -434,6 +491,9 @@ pub(crate) struct LooseLibraryOutcome {
|
||||
/// Structural diagnostics from the restore that produced this output.
|
||||
/// `None` for duplicates, failures, and restorers without a report.
|
||||
pub validation: Option<ValidationDiagnostics>,
|
||||
/// The engines' own extraction and restoration reports, kept only for
|
||||
/// research inspection. `None` for every ordinary run.
|
||||
pub research: Option<crate::report::AndroidResearchReport>,
|
||||
}
|
||||
|
||||
pub(crate) fn restore_loose_library(
|
||||
@@ -452,7 +512,7 @@ pub(crate) fn restore_loose_library(
|
||||
app,
|
||||
verbose,
|
||||
cache,
|
||||
&mut context::EngineRestorer(limits),
|
||||
&mut context::EngineRestorer::new(limits, cache.research()),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -474,6 +534,7 @@ fn restore_loose_library_with<R: context::LibraryRestorer>(
|
||||
status: EntryStatus::Duplicate,
|
||||
embedded: None,
|
||||
validation: None,
|
||||
research: None,
|
||||
});
|
||||
}
|
||||
// A prior content-only success still needs context extraction. Restore it
|
||||
@@ -499,6 +560,7 @@ fn restore_loose_library_with<R: context::LibraryRestorer>(
|
||||
status: EntryStatus::Failed(error),
|
||||
embedded: None,
|
||||
validation: None,
|
||||
research: None,
|
||||
});
|
||||
}
|
||||
embedded = Some(meta_dest);
|
||||
@@ -517,15 +579,30 @@ fn restore_loose_library_with<R: context::LibraryRestorer>(
|
||||
},
|
||||
embedded,
|
||||
// A duplicate restored only for its module context has no
|
||||
// output of its own, so it reports no diagnostics.
|
||||
validation: if prior { None } else { restored.validation },
|
||||
// output of its own, so it reports no diagnostics, and the
|
||||
// engine reports belong to the run that actually produced it.
|
||||
validation: if prior {
|
||||
None
|
||||
} else {
|
||||
restored.validation.clone()
|
||||
},
|
||||
research: if prior { None } else { restored.research },
|
||||
})
|
||||
}
|
||||
Err(error) => {
|
||||
// A restore that failed after extraction keeps the extraction's
|
||||
// own report; the error itself is unchanged.
|
||||
let research = match error_research(&error) {
|
||||
Some(ResearchCapture::Library(report)) => Some(report.clone()),
|
||||
_ => None,
|
||||
};
|
||||
Ok(LooseLibraryOutcome {
|
||||
status: EntryStatus::Failed(error),
|
||||
embedded: None,
|
||||
validation: None,
|
||||
research,
|
||||
})
|
||||
}
|
||||
Err(error) => Ok(LooseLibraryOutcome {
|
||||
status: EntryStatus::Failed(error),
|
||||
embedded: None,
|
||||
validation: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -538,6 +615,9 @@ pub(crate) struct LooseMetadataOutcome {
|
||||
pub provenance: Vec<String>,
|
||||
/// Route the transform actually took (seeded, structural, or method-index).
|
||||
pub layout: senbei_engine::LayoutKind,
|
||||
/// Seeds tried, discovery, and the transform's own report. Only a research
|
||||
/// run keeps this.
|
||||
pub research: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
pub(crate) fn restore_loose_metadata(
|
||||
@@ -571,8 +651,9 @@ pub(crate) fn restore_loose_metadata(
|
||||
let module = module.as_deref();
|
||||
// Loose metadata retains one output per path, as before. Do not keep all
|
||||
// restored blobs in the folder cache just to avoid a repeated permutation.
|
||||
let (out, report, layout) =
|
||||
restore_metadata_bytes_with_module(&data, module).with_context(|| label.to_owned())?;
|
||||
let (out, report, layout, research) =
|
||||
restore_metadata_with_module(&data, module, cache.research())
|
||||
.with_context(|| label.to_owned())?;
|
||||
if report.remapped > 0 {
|
||||
write_metadata_blob(dest, &out)?;
|
||||
if verbose {
|
||||
@@ -584,6 +665,7 @@ pub(crate) fn restore_loose_metadata(
|
||||
remapped: report.remapped,
|
||||
provenance,
|
||||
layout,
|
||||
research,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -665,43 +747,47 @@ pub(crate) fn restore_package_cached(
|
||||
out_root,
|
||||
cache,
|
||||
verbose,
|
||||
&mut context::EngineRestorer(limits),
|
||||
&mut context::EngineRestorer::new(limits, cache.research()),
|
||||
)
|
||||
}
|
||||
|
||||
/// One folder split-set: every library in the group, then every metadata blob.
|
||||
/// A library-only pass records modules without writing metadata, so a metadata
|
||||
/// blob in an earlier sibling cannot run before a library in a later one.
|
||||
/// `members` pairs each package with the relative path its outputs live under.
|
||||
///
|
||||
/// The relative path is computed by the caller (see `job::rel_in_tree`) and is
|
||||
/// always relative. This function never derives it: `Path::join` with an
|
||||
/// absolute path discards the output root, so a fallback here could write
|
||||
/// outside the caller's directory — unacceptable for a dry run or inspection,
|
||||
/// whose whole contract is that it keeps nothing outside its own workspace.
|
||||
pub(crate) fn restore_apk_group(
|
||||
packages: &[PathBuf],
|
||||
root: &Path,
|
||||
members: &[(&Path, &Path)],
|
||||
out_root: &Path,
|
||||
cache: &mut context::AndroidRunCache,
|
||||
verbose: bool,
|
||||
) -> Result<Vec<EntryOutcome>> {
|
||||
let limits = cache.limits;
|
||||
let mut outcomes = Vec::new();
|
||||
for package in packages {
|
||||
let rel = package.strip_prefix(root).unwrap_or(package);
|
||||
for (package, rel) in members {
|
||||
outcomes.extend(restore_package_pass(
|
||||
package,
|
||||
rel,
|
||||
out_root,
|
||||
cache,
|
||||
verbose,
|
||||
&mut context::EngineRestorer(limits),
|
||||
&mut context::EngineRestorer::new(limits, cache.research()),
|
||||
PackagePass::Libraries,
|
||||
)?);
|
||||
}
|
||||
for package in packages {
|
||||
let rel = package.strip_prefix(root).unwrap_or(package);
|
||||
for (package, rel) in members {
|
||||
outcomes.extend(restore_package_pass(
|
||||
package,
|
||||
rel,
|
||||
out_root,
|
||||
cache,
|
||||
verbose,
|
||||
&mut context::EngineRestorer(limits),
|
||||
&mut context::EngineRestorer::new(limits, cache.research()),
|
||||
PackagePass::Metadata,
|
||||
)?);
|
||||
}
|
||||
@@ -724,6 +810,124 @@ pub fn content_identity(data: &[u8]) -> String {
|
||||
hex_digest(&digest.finalize())
|
||||
}
|
||||
|
||||
/// A failure that still carries what the attempt had already observed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum ResearchCapture {
|
||||
/// Extraction ran and produced a report; the restoration after it failed.
|
||||
Library(crate::report::AndroidResearchReport),
|
||||
/// A metadata transform's seeds, discovery, and failure reason.
|
||||
Metadata(serde_json::Value),
|
||||
}
|
||||
|
||||
/// A transform error that still carries what the attempt observed.
|
||||
///
|
||||
/// Research inspection wants the seeds it tried and the reason each failed even
|
||||
/// when no output was produced. The error keeps its ordinary `anyhow` chain —
|
||||
/// callers that do not care about research see exactly the same message.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct LossyError {
|
||||
inner: anyhow::Error,
|
||||
capture: ResearchCapture,
|
||||
}
|
||||
|
||||
impl LossyError {
|
||||
pub(crate) fn new(inner: anyhow::Error, capture: ResearchCapture) -> Self {
|
||||
Self { inner, capture }
|
||||
}
|
||||
|
||||
fn capture(&self) -> &ResearchCapture {
|
||||
&self.capture
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for LossyError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.inner.fmt(formatter)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for LossyError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
// Keep the whole wrapped chain reachable: callers classify the original
|
||||
// error (an unsupported version, a malformed blob) by walking it.
|
||||
Some(self.inner.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// The research captured for a failure, if the error (or anything it wraps)
|
||||
/// carries one.
|
||||
pub(crate) fn error_research(error: &anyhow::Error) -> Option<&ResearchCapture> {
|
||||
error
|
||||
.chain()
|
||||
.find_map(|cause| cause.downcast_ref::<LossyError>())
|
||||
.map(LossyError::capture)
|
||||
}
|
||||
|
||||
/// [`capture`] with the same rule, exposed to the module's tests so a failed
|
||||
/// restore can be exercised without a protected fixture.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn capture_for_tests(
|
||||
error: anyhow::Error,
|
||||
research: Option<ResearchCapture>,
|
||||
) -> anyhow::Error {
|
||||
capture(error, research)
|
||||
}
|
||||
|
||||
/// Wrap `error` with the capture, when there is one.
|
||||
fn capture(error: anyhow::Error, capture: Option<ResearchCapture>) -> anyhow::Error {
|
||||
match capture {
|
||||
Some(capture) => LossyError::new(error, capture).into(),
|
||||
None => error,
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize one engine report for research output.
|
||||
///
|
||||
/// The report is the engine's own, unchanged; only filesystem locations are
|
||||
/// rewritten to logical labels. A research report outlives the run, and a
|
||||
/// scratch path that no longer exists is noise — or worse, a misleading hint
|
||||
/// about where an output was "kept".
|
||||
fn report_value<T: serde::Serialize>(report: &T, labels: &[(&Path, &str)]) -> serde_json::Value {
|
||||
let mut value = serde_json::to_value(report).unwrap_or(serde_json::Value::Null);
|
||||
scrub_paths(&mut value, labels);
|
||||
value
|
||||
}
|
||||
|
||||
fn scrub_paths(value: &mut serde_json::Value, labels: &[(&Path, &str)]) {
|
||||
// Longest location first: a nested path starts with its parent, and the
|
||||
// more specific label is the one that describes it.
|
||||
let mut rules: Vec<(String, &str)> = labels
|
||||
.iter()
|
||||
.map(|(path, label)| (path.display().to_string(), *label))
|
||||
.filter(|(rendered, _)| !rendered.is_empty())
|
||||
.collect();
|
||||
rules.sort_by_key(|(rendered, _)| std::cmp::Reverse(rendered.len()));
|
||||
scrub_value(value, &rules);
|
||||
}
|
||||
|
||||
fn scrub_value(value: &mut serde_json::Value, rules: &[(String, &str)]) {
|
||||
match value {
|
||||
serde_json::Value::String(text) => {
|
||||
for (rendered, label) in rules {
|
||||
if text.contains(rendered.as_str()) {
|
||||
*text = text.replace(rendered.as_str(), label);
|
||||
}
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(items) => {
|
||||
for item in items {
|
||||
scrub_value(item, rules);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Object(fields) => {
|
||||
for field in fields.values_mut() {
|
||||
scrub_value(field, rules);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore an il2cpp metadata blob. Paired v24.1 Android packages use the
|
||||
/// method-index profile recovered from module 0x0C; later Android layouts use
|
||||
/// the seeded MethodDef RID permutation before falling back to the structural
|
||||
@@ -745,20 +949,67 @@ pub(crate) fn restore_metadata_bytes_with_module(
|
||||
data: &[u8],
|
||||
method_index_module: Option<&[u8]>,
|
||||
) -> anyhow::Result<(Vec<u8>, senbei_metadata::Report, senbei_engine::LayoutKind)> {
|
||||
let (out, report, layout, _) = restore_metadata_with_module(data, method_index_module, false)?;
|
||||
Ok((out, report, layout))
|
||||
}
|
||||
|
||||
/// [`restore_metadata_bytes_with_module`], optionally keeping the facts the
|
||||
/// transform observed on the way.
|
||||
///
|
||||
/// The research value is produced by the same pass that does the work: the
|
||||
/// seed candidates discovery found (or why it found none), the seeds actually
|
||||
/// tried, and the transform's own report. Nothing is re-run for it, and it
|
||||
/// survives a transform that fails — a failing trial is exactly what the
|
||||
/// caller wants to see.
|
||||
pub(crate) fn restore_metadata_with_module(
|
||||
data: &[u8],
|
||||
method_index_module: Option<&[u8]>,
|
||||
research: bool,
|
||||
) -> anyhow::Result<(
|
||||
Vec<u8>,
|
||||
senbei_metadata::Report,
|
||||
senbei_engine::LayoutKind,
|
||||
Option<serde_json::Value>,
|
||||
)> {
|
||||
use senbei_engine::LayoutKind;
|
||||
let version = data
|
||||
.get(4..8)
|
||||
.and_then(|bytes| <[u8; 4]>::try_from(bytes).ok())
|
||||
.map(u32::from_le_bytes);
|
||||
let mut facts = MetadataFacts {
|
||||
version,
|
||||
route: "method_indices",
|
||||
module_0c_sha256: method_index_module.map(content_identity),
|
||||
..MetadataFacts::default()
|
||||
};
|
||||
// Keep what the attempt has seen so far, then wrap the failure with it.
|
||||
let fail = |facts: &mut MetadataFacts, error: anyhow::Error| -> anyhow::Error {
|
||||
facts.error = Some(format!("{error:#}"));
|
||||
let kept = research.then(|| facts.clone().into_value());
|
||||
capture(error, kept.map(ResearchCapture::Metadata))
|
||||
};
|
||||
|
||||
if version == Some(24) {
|
||||
// v24.1 method indices come only from this application's module 0x0C.
|
||||
// Falling through to the structural remap would report "unsupported
|
||||
// version" and could be mistaken for a clean skip. No module is a
|
||||
// failed binding, not an unsupported layout.
|
||||
let module = method_index_module
|
||||
.ok_or_else(|| anyhow::anyhow!("no module 0x0C for v24.1 metadata"))?;
|
||||
let Some(module) = method_index_module else {
|
||||
let error = anyhow::anyhow!("no module 0x0C for v24.1 metadata");
|
||||
return Err(fail(&mut facts, error));
|
||||
};
|
||||
let (out, report) = senbei_metadata::android::restore_method_indices_v24_1(data, module)
|
||||
.map_err(anyhow::Error::new)?;
|
||||
.map_err(anyhow::Error::new)
|
||||
.map_err(|error| fail(&mut facts, error))?;
|
||||
facts.version = Some(report.version);
|
||||
facts.report = Some(serde_json::json!({
|
||||
"version": report.version,
|
||||
"methods": report.methods,
|
||||
"active_methods": report.active_methods,
|
||||
"changed_indices": report.changed_indices,
|
||||
"exception_count": report.exception_count,
|
||||
"seed": report.seed,
|
||||
}));
|
||||
return Ok((
|
||||
out,
|
||||
senbei_metadata::Report {
|
||||
@@ -768,12 +1019,31 @@ pub(crate) fn restore_metadata_bytes_with_module(
|
||||
modules: 0,
|
||||
},
|
||||
LayoutKind::MetadataMethodIndices,
|
||||
research.then(|| facts.into_value()),
|
||||
));
|
||||
}
|
||||
if let Ok(discovery) = senbei_metadata::android::discover_method_token_seeds(data)
|
||||
&& matches!(discovery.version, 29 | 31 | 39)
|
||||
{
|
||||
let mut seeds = discovery.seed_candidates.clone();
|
||||
|
||||
// Seed discovery is the only step that can say why a seeded restore was
|
||||
// never tried, so its own outcome is recorded for research. Whether the
|
||||
// seeded route runs at all is decided exactly as before.
|
||||
let mut seeded_layout = false;
|
||||
match senbei_metadata::android::discover_method_token_seeds(data) {
|
||||
Ok(found) if matches!(found.version, 29 | 31 | 39) => {
|
||||
seeded_layout = true;
|
||||
facts.seed_candidates = found.seed_candidates.clone();
|
||||
if research {
|
||||
facts.discovery = serde_json::to_value(&found).ok();
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
if research {
|
||||
facts.discovery_error = Some(format!("{error}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if seeded_layout {
|
||||
let mut seeds = facts.seed_candidates.clone();
|
||||
if seeds.is_empty() {
|
||||
seeds.push(senbei_metadata::android::DEFAULT_METHOD_TOKEN_SEED);
|
||||
}
|
||||
@@ -782,7 +1052,24 @@ pub(crate) fn restore_metadata_bytes_with_module(
|
||||
// build with an unseeded permutation falls through to the structural
|
||||
// remap rather than producing a silently wrong file.
|
||||
for seed in seeds {
|
||||
facts.tried_seeds.push(seed);
|
||||
if let Ok((out, report)) = senbei_metadata::android::restore_method_tokens(data, seed) {
|
||||
facts.route = "seeded";
|
||||
facts.version = Some(report.version);
|
||||
facts.report = Some(serde_json::json!({
|
||||
"version": report.version,
|
||||
"seed": report.seed,
|
||||
"encryption_status": report.encryption_status,
|
||||
"images": report.images,
|
||||
"images_with_methods": report.images_with_methods,
|
||||
"types": report.types,
|
||||
"methods": report.methods,
|
||||
"visited_methods": report.visited_methods,
|
||||
"already_correct_before": report.already_correct_before,
|
||||
"correct_after": report.correct_after,
|
||||
"changed_tokens": report.changed_tokens,
|
||||
"transformed_images": report.transformed_images,
|
||||
}));
|
||||
return Ok((
|
||||
out,
|
||||
senbei_metadata::Report {
|
||||
@@ -792,12 +1079,66 @@ pub(crate) fn restore_metadata_bytes_with_module(
|
||||
modules: report.images_with_methods,
|
||||
},
|
||||
LayoutKind::MetadataSeeded,
|
||||
research.then(|| facts.into_value()),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (out, report) = senbei_metadata::deobfuscate(data).map_err(anyhow::Error::new)?;
|
||||
Ok((out, report, LayoutKind::MetadataStructural))
|
||||
|
||||
facts.route = "structural";
|
||||
let (out, report) = senbei_metadata::deobfuscate(data)
|
||||
.map_err(anyhow::Error::new)
|
||||
.map_err(|error| fail(&mut facts, error))?;
|
||||
facts.version = Some(report.version);
|
||||
facts.report = Some(serde_json::json!({
|
||||
"version": report.version,
|
||||
"methods": report.methods,
|
||||
"remapped": report.remapped,
|
||||
"modules": report.modules,
|
||||
}));
|
||||
Ok((
|
||||
out,
|
||||
report,
|
||||
LayoutKind::MetadataStructural,
|
||||
research.then(|| facts.into_value()),
|
||||
))
|
||||
}
|
||||
|
||||
/// What one metadata transform observed, independent of whether it succeeded.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct MetadataFacts {
|
||||
route: &'static str,
|
||||
version: Option<u32>,
|
||||
/// Seeds the transform actually tried, in order.
|
||||
tried_seeds: Vec<u32>,
|
||||
/// Candidates seed discovery reported.
|
||||
seed_candidates: Vec<u32>,
|
||||
/// The discovery report, when it found a supported layout.
|
||||
discovery: Option<serde_json::Value>,
|
||||
/// Why seed discovery declined, when it did.
|
||||
discovery_error: Option<String>,
|
||||
/// The transform's own report.
|
||||
report: Option<serde_json::Value>,
|
||||
/// Identity of the module `0x0C` this transform bound to, when it had one.
|
||||
module_0c_sha256: Option<String>,
|
||||
/// Why the transform stopped, when it did.
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl MetadataFacts {
|
||||
fn into_value(self) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"route": self.route,
|
||||
"version": self.version,
|
||||
"tried_seeds": self.tried_seeds,
|
||||
"seed_candidates": self.seed_candidates,
|
||||
"discovery": self.discovery,
|
||||
"discovery_error": self.discovery_error,
|
||||
"report": self.report,
|
||||
"module_0c_sha256": self.module_0c_sha256,
|
||||
"error": self.error,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened to one archive entry (or one loose Android target).
|
||||
@@ -820,6 +1161,12 @@ pub struct EntryOutcome {
|
||||
/// Structural diagnostics from the restore of this entry. `None` for
|
||||
/// metadata entries, duplicates, and restorers without a report.
|
||||
pub validation: Option<ValidationDiagnostics>,
|
||||
/// The engines' own reports for a library entry. Only a research run keeps
|
||||
/// them, and only for an entry that actually restored.
|
||||
pub research: Option<crate::report::AndroidResearchReport>,
|
||||
/// Seeds tried, discovery, and the transform report for a metadata entry.
|
||||
/// Only a research run keeps them, and they survive a failed transform.
|
||||
pub metadata_research: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -897,17 +1244,34 @@ pub fn restore_package_with_limits(
|
||||
// package still skips those bytes; module context for metadata is rebuilt
|
||||
// inside this package (one package, or one manifest-scoped bundle, is one
|
||||
// application boundary).
|
||||
restore_package_with_limits_and_research(package, rel, out_root, seen, verbose, &limits, false)
|
||||
}
|
||||
|
||||
/// [`restore_package_with_limits`], optionally keeping the engines' reports for
|
||||
/// research output. One package is one application boundary either way.
|
||||
pub(crate) fn restore_package_with_limits_and_research(
|
||||
package: &Path,
|
||||
rel: &Path,
|
||||
out_root: &Path,
|
||||
seen: &mut HashSet<String>,
|
||||
verbose: bool,
|
||||
limits: &ResourceLimits,
|
||||
research: bool,
|
||||
) -> Result<Vec<EntryOutcome>> {
|
||||
let limits = *limits;
|
||||
let mut cache = context::AndroidRunCache::with_limits(&limits);
|
||||
cache.research = research;
|
||||
for identity in seen.iter().cloned() {
|
||||
cache.insert_prior_success(identity);
|
||||
}
|
||||
let research = cache.research();
|
||||
let outcomes = restore_package_with_restorer(
|
||||
package,
|
||||
rel,
|
||||
out_root,
|
||||
&mut cache,
|
||||
verbose,
|
||||
&mut context::EngineRestorer(limits),
|
||||
&mut context::EngineRestorer::new(limits, research),
|
||||
);
|
||||
// Publish successes even when the package returns `Err`. The caller's set
|
||||
// is only replaced after that, so a panic still leaves the old successes.
|
||||
@@ -1188,6 +1552,8 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
layout: None,
|
||||
metadata_version: None,
|
||||
validation: None,
|
||||
research: None,
|
||||
metadata_research: None,
|
||||
};
|
||||
if !is_so && !is_meta {
|
||||
return Ok(vec![outcome(
|
||||
@@ -1238,6 +1604,7 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
let mut restored_outcome =
|
||||
outcome(EntryKind::So, EntryStatus::Restored, Vec::new());
|
||||
restored_outcome.validation = restored.validation.clone();
|
||||
restored_outcome.research = restored.research.clone();
|
||||
outcomes.push(restored_outcome);
|
||||
}
|
||||
if !prior && let Some(blob) = &restored.embedded_metadata {
|
||||
@@ -1252,6 +1619,8 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
layout: None,
|
||||
metadata_version: None,
|
||||
validation: None,
|
||||
research: None,
|
||||
metadata_research: None,
|
||||
}),
|
||||
Err(error) => embedded_failed = Some(error),
|
||||
}
|
||||
@@ -1276,11 +1645,17 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => vec![outcome(
|
||||
EntryKind::So,
|
||||
EntryStatus::Failed(error),
|
||||
Vec::new(),
|
||||
)],
|
||||
Err(error) => {
|
||||
// A restore that failed after extraction keeps what the
|
||||
// extraction already reported, alongside the error.
|
||||
let research = match error_research(&error) {
|
||||
Some(ResearchCapture::Library(report)) => Some(report.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let mut failed = outcome(EntryKind::So, EntryStatus::Failed(error), Vec::new());
|
||||
failed.research = research;
|
||||
vec![failed]
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1328,47 +1703,58 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
// Metadata entry: write only when the restore actually changed protected
|
||||
// method fields — a clean blob needs no copy (same contract as loose files).
|
||||
// The binding was resolved before this write.
|
||||
let (kind, status, layout) = match restore_metadata_bytes_with_module(&entry_data, module) {
|
||||
Ok((out, report, layout)) if report.remapped > 0 => {
|
||||
let kind = EntryKind::Metadata {
|
||||
remapped: report.remapped,
|
||||
};
|
||||
match write_metadata_blob(dest, &out) {
|
||||
Ok(()) => {
|
||||
state.cache.insert_metadata(
|
||||
identity,
|
||||
context_identity,
|
||||
context::CachedMetadata::Restored {
|
||||
remapped: report.remapped,
|
||||
},
|
||||
);
|
||||
(kind, EntryStatus::Restored, Some(layout))
|
||||
let (kind, status, layout, metadata_research) =
|
||||
match restore_metadata_with_module(&entry_data, module, state.cache.research()) {
|
||||
Ok((out, report, layout, research)) if report.remapped > 0 => {
|
||||
let kind = EntryKind::Metadata {
|
||||
remapped: report.remapped,
|
||||
};
|
||||
match write_metadata_blob(dest, &out) {
|
||||
Ok(()) => {
|
||||
state.cache.insert_metadata(
|
||||
identity,
|
||||
context_identity,
|
||||
context::CachedMetadata::Restored {
|
||||
remapped: report.remapped,
|
||||
},
|
||||
);
|
||||
(kind, EntryStatus::Restored, Some(layout), research)
|
||||
}
|
||||
Err(error) => (kind, EntryStatus::Failed(error), Some(layout), research),
|
||||
}
|
||||
Err(error) => (kind, EntryStatus::Failed(error), Some(layout)),
|
||||
}
|
||||
}
|
||||
// A blob that needed no change still reports the route that ran.
|
||||
Ok((_, _report, layout)) => {
|
||||
state.cache.insert_metadata(
|
||||
identity,
|
||||
context_identity,
|
||||
context::CachedMetadata::Unchanged,
|
||||
);
|
||||
(
|
||||
EntryKind::Metadata { remapped: 0 },
|
||||
EntryStatus::Unchanged,
|
||||
Some(layout),
|
||||
)
|
||||
}
|
||||
Err(error) => (
|
||||
EntryKind::Metadata { remapped: 0 },
|
||||
EntryStatus::Failed(error),
|
||||
None,
|
||||
),
|
||||
};
|
||||
// A blob that needed no change still reports the route that ran.
|
||||
Ok((_, _report, layout, research)) => {
|
||||
state.cache.insert_metadata(
|
||||
identity,
|
||||
context_identity,
|
||||
context::CachedMetadata::Unchanged,
|
||||
);
|
||||
(
|
||||
EntryKind::Metadata { remapped: 0 },
|
||||
EntryStatus::Unchanged,
|
||||
Some(layout),
|
||||
research,
|
||||
)
|
||||
}
|
||||
Err(error) => {
|
||||
// The seeds it tried and the reason it stopped survive the failure.
|
||||
let research = error_research(&error).and_then(|capture| match capture {
|
||||
ResearchCapture::Metadata(value) => Some(value.clone()),
|
||||
ResearchCapture::Library(_) => None,
|
||||
});
|
||||
(
|
||||
EntryKind::Metadata { remapped: 0 },
|
||||
EntryStatus::Failed(error),
|
||||
None,
|
||||
research,
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut entry_outcome = outcome(kind, status, provenance_labels(&provenance));
|
||||
entry_outcome.layout = layout;
|
||||
entry_outcome.metadata_version = version;
|
||||
entry_outcome.metadata_research = metadata_research;
|
||||
Ok(vec![entry_outcome])
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ impl LibraryRestorer for ScriptedRestorer {
|
||||
// A scripted restore has no engine report behind it, so it claims
|
||||
// no validation verdict at all.
|
||||
validation: None,
|
||||
research: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1349,3 +1350,242 @@ fn scripted_restore_claims_no_validation_verdict() {
|
||||
"a restorer without a report must not claim a clean verdict"
|
||||
);
|
||||
}
|
||||
|
||||
/// Research keeps what the transform actually did: the route, the seeds tried,
|
||||
/// and the engine's own counters. Ordinary runs keep none of it.
|
||||
#[test]
|
||||
fn metadata_research_reports_the_route_that_ran() {
|
||||
let data = metadata_fixture();
|
||||
|
||||
let (_, _, layout, research) = restore_metadata_with_module(&data, None, true).unwrap();
|
||||
let research = research.expect("research mode keeps the transform's facts");
|
||||
assert_eq!(research["version"], 31);
|
||||
// The fixture has no seeded permutation to find, so the measured route is
|
||||
// the structural remap — and the research names the route that actually ran.
|
||||
assert_eq!(research["route"], "structural");
|
||||
assert!(research["tried_seeds"].as_array().is_some());
|
||||
assert!(research["report"].is_object(), "{research}");
|
||||
assert!(research["error"].is_null());
|
||||
assert_eq!(
|
||||
research["module_0c_sha256"],
|
||||
serde_json::Value::Null,
|
||||
"no module was offered for this blob"
|
||||
);
|
||||
// The layout the transform reported is the one the research names.
|
||||
let (_, _, quiet_layout, quiet) = restore_metadata_with_module(&data, None, false).unwrap();
|
||||
assert!(quiet.is_none(), "an ordinary run keeps no research value");
|
||||
assert_eq!(quiet_layout, layout);
|
||||
}
|
||||
|
||||
/// A failed transform still reports the seeds it tried and why it stopped.
|
||||
#[test]
|
||||
fn metadata_research_survives_a_failed_transform() {
|
||||
// A v24.1 header with no module 0x0C: the binding itself fails, before any
|
||||
// transform could run.
|
||||
let mut data = metadata_fixture();
|
||||
data[4..8].copy_from_slice(&24u32.to_le_bytes());
|
||||
|
||||
let error = restore_metadata_with_module(&data, None, true).unwrap_err();
|
||||
let capture = error_research(&error).expect("the failure carries its research");
|
||||
let ResearchCapture::Metadata(value) = capture else {
|
||||
panic!("a metadata failure carries metadata research");
|
||||
};
|
||||
assert_eq!(value["route"], "method_indices");
|
||||
assert_eq!(value["version"], 24);
|
||||
assert!(
|
||||
value["error"]
|
||||
.as_str()
|
||||
.is_some_and(|text| text.contains("0x0C")),
|
||||
"the reason is kept: {value}"
|
||||
);
|
||||
// An ordinary run fails the same way, just without the research value.
|
||||
let quiet = restore_metadata_with_module(&data, None, false).unwrap_err();
|
||||
assert!(error_research(&quiet).is_none());
|
||||
}
|
||||
|
||||
/// A library restore that fails after extraction keeps the extraction's own
|
||||
/// report, so the research output says how far it got.
|
||||
#[test]
|
||||
fn a_failed_library_restore_keeps_what_extraction_reported() {
|
||||
let report = crate::report::AndroidResearchReport {
|
||||
extraction: serde_json::json!({"stage1": {"payload_key": 0x1234}, "streams": []}),
|
||||
restoration: None,
|
||||
};
|
||||
let error = crate::android::capture_for_tests(
|
||||
anyhow::anyhow!("baseline restore failed"),
|
||||
Some(ResearchCapture::Library(report.clone())),
|
||||
);
|
||||
let capture = error_research(&error).expect("the failure carries its research");
|
||||
let ResearchCapture::Library(kept) = capture else {
|
||||
panic!("a library failure carries library research");
|
||||
};
|
||||
assert_eq!(kept.extraction, report.extraction);
|
||||
assert!(
|
||||
kept.restoration.is_none(),
|
||||
"no restoration report exists for a restore that failed"
|
||||
);
|
||||
// The original failure is still the error's message.
|
||||
assert!(format!("{error:#}").contains("baseline restore failed"));
|
||||
}
|
||||
|
||||
/// A split set is restored with output paths computed by the caller. An
|
||||
/// absolute relative path would make `Path::join` discard the output root and
|
||||
/// escape it — precisely what a dry run/inspection must never do.
|
||||
#[test]
|
||||
fn a_split_set_never_writes_outside_the_output_root() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("tree");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let config = root.join("config.arm64_v8a.apk");
|
||||
let base = root.join("base.apk");
|
||||
let module_data = pair(3).1;
|
||||
write_package(
|
||||
&config,
|
||||
&[
|
||||
(
|
||||
"AndroidManifest.xml",
|
||||
manifest("com.example.split", "7").as_bytes(),
|
||||
),
|
||||
("lib/arm64-v8a/libil2cpp.so", &library_bytes(b"split-so")),
|
||||
],
|
||||
);
|
||||
write_package(
|
||||
&base,
|
||||
&[
|
||||
(
|
||||
"AndroidManifest.xml",
|
||||
manifest("com.example.split", "7").as_bytes(),
|
||||
),
|
||||
("assets/global-metadata.dat", &pair(3).0),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
loose_apk_groups(&[base.clone(), config.clone()]).len(),
|
||||
1,
|
||||
"same package and version form one split set"
|
||||
);
|
||||
|
||||
let out = temp.path().join("workspace");
|
||||
let rels: Vec<PathBuf> = [&base, &config]
|
||||
.iter()
|
||||
.map(|package| package.strip_prefix(&root).unwrap().to_path_buf())
|
||||
.collect();
|
||||
let members: Vec<(&Path, &Path)> = [&base, &config]
|
||||
.iter()
|
||||
.map(|package| package.as_path())
|
||||
.zip(rels.iter().map(|rel| rel.as_path()))
|
||||
.collect();
|
||||
let mut cache = run_cache_for_research(&senbei_engine::android::ResourceLimits::default());
|
||||
let results = restore_apk_group(&members, &out, &mut cache, false);
|
||||
assert!(results.is_ok(), "synthetic split set restores: {results:?}");
|
||||
|
||||
for rel in &rels {
|
||||
assert!(!rel.is_absolute(), "relative paths stay relative: {rel:?}");
|
||||
assert!(
|
||||
out.join(rel).starts_with(&out),
|
||||
"every output stays under the workspace"
|
||||
);
|
||||
}
|
||||
let written: Vec<PathBuf> = std::fs::read_dir(temp.path())
|
||||
.unwrap()
|
||||
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
|
||||
.filter(|path| path != &root && path != &out)
|
||||
.collect();
|
||||
assert!(
|
||||
written.is_empty(),
|
||||
"nothing appears beside the workspace: {written:?}"
|
||||
);
|
||||
let _ = module_data;
|
||||
}
|
||||
|
||||
/// A caller cannot hand the group restore an absolute "relative" path by
|
||||
/// accident through this API: it takes explicit pairs, and the folder driver
|
||||
/// builds them with the same helper the rest of the run uses. This pins the
|
||||
/// shape so a future refactor cannot reintroduce the `strip_prefix(..).unwrap_or`
|
||||
/// fallback that made `Path::join` discard the output root.
|
||||
#[test]
|
||||
fn the_group_restore_never_derives_its_own_relative_path() {
|
||||
let source = include_str!("mod.rs");
|
||||
let signature = source
|
||||
.split("pub(crate) fn restore_apk_group(")
|
||||
.nth(1)
|
||||
.unwrap();
|
||||
let head = signature
|
||||
.split(") -> Result<Vec<EntryOutcome>>")
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(
|
||||
head.contains("members: &[(&Path, &Path)]"),
|
||||
"the group restore receives caller-computed relative paths: {head}"
|
||||
);
|
||||
assert!(
|
||||
!source.contains("strip_prefix(root).unwrap_or(package)"),
|
||||
"the absolute-path fallback must not come back"
|
||||
);
|
||||
}
|
||||
|
||||
/// A restorer that fails with a resource ceiling, as the production one does
|
||||
/// when an entry exceeds `--max-entry-mib`.
|
||||
struct LimitedRestorer;
|
||||
|
||||
impl LibraryRestorer for LimitedRestorer {
|
||||
fn restore(
|
||||
&mut self,
|
||||
_input: &Path,
|
||||
_dest: &Path,
|
||||
_verbose: bool,
|
||||
) -> anyhow::Result<RestoredLibrary> {
|
||||
Err(anyhow::Error::new(
|
||||
senbei_engine::android::LimitExceeded::Entry {
|
||||
requested: 4 * 1024 * 1024,
|
||||
limit: 1024 * 1024,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn protected_override(&mut self, input: &Path) -> Option<Vec<u8>> {
|
||||
std::fs::read(input).ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// A known target whose restore stopped on a resource ceiling is an error the
|
||||
/// report can name — it is not "recognized, therefore complete". The status and
|
||||
/// the cause come from the typed error, never from its message text.
|
||||
#[test]
|
||||
fn a_known_library_that_hits_a_ceiling_is_reported_incomplete() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let app = root.join("app");
|
||||
std::fs::create_dir_all(app.join("lib/arm64-v8a")).unwrap();
|
||||
let so = app.join("lib/arm64-v8a/libil2cpp.so");
|
||||
std::fs::write(&so, library_bytes(b"over-limit")).unwrap();
|
||||
|
||||
let mut cache = run_cache();
|
||||
let scoped = loose_scopes(std::slice::from_ref(&so), &[]);
|
||||
let mut restorer = LimitedRestorer;
|
||||
let outcome = restore_loose_library_with(
|
||||
&so,
|
||||
&root.join("out.so"),
|
||||
"libil2cpp.so",
|
||||
&scoped[0].key,
|
||||
false,
|
||||
&mut cache,
|
||||
&mut restorer,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let EntryStatus::Failed(error) = &outcome.status else {
|
||||
panic!("the ceiling must fail the restore: {:?}", outcome.status);
|
||||
};
|
||||
assert!(
|
||||
crate::job::analysis_incomplete(error),
|
||||
"a LimitExceeded failure is infrastructure, not a rejected layout"
|
||||
);
|
||||
let report = crate::job::android_library_input(
|
||||
&so,
|
||||
crate::report::InputStatus::Error,
|
||||
&root.join("out.so"),
|
||||
std::time::Instant::now(),
|
||||
);
|
||||
assert_eq!(report.status, crate::report::InputStatus::Error);
|
||||
}
|
||||
Reference in new issue
Block a user