use super::launch::{
discover_ppc_cfm_library_fragments_with_locations, load_game_from_path, new_runner,
ppc_cfrg_is_runtime_library_installer, ppc_diagnostic_vfs, vfs_path_sort_key,
};
use crate::loader::cfrg::{parse_cfrg_resource, ARCH_POWERPC, USAGE_APP, USAGE_DROP_IN, USAGE_LIB};
use crate::loader::pef::{data_fork_is_pef, parse_pef_header};
use crate::loader::ppc::import_audit::{
audit_pef_imports, PpcBundledLibraryExports, PpcImportAuditEntry,
};
use crate::managers::resource::ResourceFork;
use serde::Serialize;
pub const PPC_IMPORT_AUDIT_FORMAT: &str = "systemless_ppc_import_audit_v1";
#[derive(Debug, Clone, Serialize)]
pub struct PpcImportAuditReport {
pub format: &'static str,
pub load_error: Option<String>,
pub fragments: Vec<PpcFragmentImportAudit>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PpcFragmentImportAudit {
pub path: String,
pub name: Option<String>,
pub usage: &'static str,
pub parsed: bool,
pub imports: Vec<PpcImportAuditEntry>,
}
impl PpcImportAuditReport {
pub fn gaps(&self) -> Vec<&PpcImportAuditEntry> {
let mut gaps: Vec<_> = self
.fragments
.iter()
.flat_map(|fragment| fragment.imports.iter())
.filter(|entry| entry.status.is_gap())
.collect();
gaps.sort_by(|left, right| {
(left.status, &left.library, &left.symbol).cmp(&(
right.status,
&right.library,
&right.symbol,
))
});
gaps.dedup_by(|left, right| {
left.status == right.status
&& left.library == right.library
&& left.symbol == right.symbol
});
gaps
}
}
pub fn audit_ppc_imports_from_path(path: &std::path::Path) -> PpcImportAuditReport {
let mut runner = new_runner();
let load_error = load_game_from_path(&mut runner, path).err();
let application = runner.dispatcher().launched_app_path().map(str::to_string);
let vfs = ppc_diagnostic_vfs(&mut runner, None);
let mut bundled = PpcBundledLibraryExports::default();
for library in discover_ppc_cfm_library_fragments_with_locations(&vfs, application.as_deref()).0
{
if !is_native_replacement_library(&library.name) {
bundled.insert(&library.name, &library.bytes);
}
}
let mut fragments = Vec::new();
let mut registered = std::collections::HashSet::new();
let mut installers = std::collections::HashSet::new();
let mut resource_files: Vec<_> = vfs.resource_files.iter().collect();
resource_files.sort_by_key(|file| vfs_path_sort_key(&file.path));
for resource_file in resource_files {
let Some(resource_data) = resource_file.raw_data.as_deref() else {
continue;
};
let Some(cfrg) = ResourceFork::parse(resource_data)
.and_then(|fork| parse_cfrg_resource(&fork.get(*b"cfrg", 0)?.data))
else {
continue;
};
let uses_runtime_library =
ppc_cfrg_is_runtime_library_installer(&cfrg, &resource_file.path, application.as_deref());
if uses_runtime_library {
installers.insert(resource_file.path.to_ascii_lowercase());
}
let Some(data_file) = vfs
.files
.iter()
.find(|file| file.path.eq_ignore_ascii_case(&resource_file.path))
else {
continue;
};
for fragment in cfrg.fragments {
if fragment.architecture != ARCH_POWERPC {
continue;
}
let Some(range) = fragment.data_fork_range(data_file.data.len()) else {
continue;
};
let start = range.start;
let Some(bytes) = data_file.data.get(range) else {
continue;
};
if !is_powerpc_pef(bytes) {
continue;
}
registered.insert((resource_file.path.to_ascii_lowercase(), start));
if fragment.usage == USAGE_LIB
&& (is_native_replacement_library(&fragment.name)
|| (uses_runtime_library
&& crate::loader::ppc::ppc_runtime_provides_cfm_library(&fragment.name)))
{
continue;
}
let usage = match fragment.usage {
USAGE_APP => "application",
USAGE_LIB => "library",
USAGE_DROP_IN => "drop_in",
_ => "unregistered",
};
fragments.push(fragment_audit(
&resource_file.path,
Some(fragment.name),
usage,
bytes,
&bundled,
));
}
}
let mut files: Vec<_> = vfs.files.iter().collect();
files.sort_by_key(|file| vfs_path_sort_key(&file.path));
for file in files {
let path = file.path.to_ascii_lowercase();
if installers.contains(&path) {
continue;
}
for start in pef_container_offsets(&file.data) {
if registered.contains(&(path.clone(), start)) {
continue;
}
let bytes = &file.data[start..];
if !is_powerpc_pef(bytes) {
continue;
}
let location = if start == 0 {
file.path.clone()
} else {
format!("{}@{start}", file.path)
};
fragments.push(fragment_audit(
&location,
None,
"unregistered",
bytes,
&bundled,
));
}
}
PpcImportAuditReport {
format: PPC_IMPORT_AUDIT_FORMAT,
load_error,
fragments,
}
}
fn is_native_replacement_library(name: &str) -> bool {
name.eq_ignore_ascii_case("DrawSprocketLib") || name.eq_ignore_ascii_case("InputSprocketLib")
}
fn pef_container_offsets(data: &[u8]) -> Vec<usize> {
const MAGIC: &[u8; 8] = b"Joy!peff";
data.windows(MAGIC.len())
.enumerate()
.filter(|(_, window)| *window == MAGIC)
.map(|(offset, _)| offset)
.collect()
}
fn is_powerpc_pef(bytes: &[u8]) -> bool {
data_fork_is_pef(bytes)
&& parse_pef_header(bytes).is_some_and(|header| header.architecture == ARCH_POWERPC)
}
fn fragment_audit(
path: &str,
name: Option<String>,
usage: &'static str,
bytes: &[u8],
bundled: &PpcBundledLibraryExports,
) -> PpcFragmentImportAudit {
let imports = audit_pef_imports(bytes, bundled);
PpcFragmentImportAudit {
path: path.to_string(),
name,
usage,
parsed: imports.is_some(),
imports: imports.unwrap_or_default(),
}
}