diff --git a/crates/xcl/src/gpu/pack.rs b/crates/xcl/src/gpu/pack.rs index 3486c16..4460178 100644 --- a/crates/xcl/src/gpu/pack.rs +++ b/crates/xcl/src/gpu/pack.rs @@ -36,26 +36,37 @@ fn rd32(b: &[u8], o: usize) -> u32 { pub fn scan(d: &[u8], from: usize) -> Vec { let mut out = Vec::new(); let mut i = from; - while i + 32 < d.len() { + while i < d.len().saturating_sub(32) { let len = d[i] as usize; - let p = i + len; + let Some(p) = i.checked_add(len) else { break }; + let Some(header_end) = p.checked_add(18) else { break }; if len >= 4 - && p + 18 <= d.len() + && header_end <= d.len() && d[p] == 0 && (d[i + 1].is_ascii_alphabetic() || d[i + 1] == b'_') && d[i + 2..p].iter().all(|&c| ident(c)) { let (c1, c2, u) = (rd32(d, p + 2) as usize, rd32(d, p + 10) as usize, rd32(d, p + 14) as usize); - if c1 == c2 && c1 > 0 && c1 < 16 << 20 && u > 0 && u < 64 << 20 && p + 18 + c1 <= d.len() { + let Some(data_end) = header_end.checked_add(c1) else { + i += 1; + continue; + }; + if c1 == c2 + && c1 > 0 + && c1 < 16 << 20 + && u > 0 + && u < 64 << 20 + && data_end <= d.len() + { out.push(Record { name: String::from_utf8_lossy(&d[i + 1..p]).into_owned(), offset: i, flag: d[p + 1], - data: p + 18, + data: header_end, csize: c1, usize: u, }); - i = p + 18 + c1; + i = data_end; continue; } } @@ -66,7 +77,10 @@ pub fn scan(d: &[u8], from: usize) -> Vec { /// Inflate a record. `None` when the stream is not valid deflate. pub fn inflate(d: &[u8], r: &Record) -> Option> { - miniz_oxide::inflate::decompress_to_vec_with_limit(&d[r.data..r.data + r.csize], r.usize).ok() + let end = r.data.checked_add(r.csize)?; + let compressed = d.get(r.data..end)?; + let unpacked = miniz_oxide::inflate::decompress_to_vec_with_limit(compressed, r.usize).ok()?; + (unpacked.len() == r.usize).then_some(unpacked) } /// Stage prefix of a shader name (`PS_Foo` → `PS`). @@ -108,4 +122,69 @@ mod tests { assert_eq!(name_stage(&recs[0].name), Some("PS")); assert_eq!(name_stage("ptfx_x"), None); } + + #[test] + fn inflate_rejects_hostile_ranges_and_size_mismatches() { + let payload = b"synthetic payload"; + let compressed = miniz_oxide::deflate::compress_to_vec(payload, 6); + let base = Record { + name: "PS_Synthetic".into(), + offset: 0, + flag: 0, + data: 0, + csize: compressed.len(), + usize: payload.len(), + }; + assert_eq!(inflate(&compressed, &base).as_deref(), Some(payload.as_slice())); + + let mut record = base.clone(); + record.data = usize::MAX; + record.csize = 2; + assert_eq!(inflate(&compressed, &record), None); + + record = base.clone(); + record.data = compressed.len() + 1; + assert_eq!(inflate(&compressed, &record), None); + + record = base; + record.usize += 1; + assert_eq!(inflate(&compressed, &record), None); + } + + #[test] + fn scan_is_bounded_for_hostile_offsets_and_arbitrary_bytes() { + assert!(scan(&[0; 64], usize::MAX).is_empty()); + + let mut state = 0x6f6c_796d_7075_7355u64; + for len in 0..512usize { + let mut bytes = vec![0u8; len]; + for byte in &mut bytes { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + *byte = state as u8; + } + for from in [0, len / 2, len, len.saturating_add(1), usize::MAX] { + let records = scan(&bytes, from); + let mut previous_end = from; + for record in records { + let end = record.data.checked_add(record.csize).expect("record range"); + assert!(record.offset >= previous_end); + assert!(end <= bytes.len()); + assert!(record.csize < 16 << 20); + assert!(record.usize < 64 << 20); + previous_end = end; + } + } + } + + let payload: Vec = (0..128).map(|value| value as u8).collect(); + let complete = record("PS_TruncationProbe", &payload); + for end in 0..=complete.len() { + for record in scan(&complete[..end], 0) { + assert!(record.data.checked_add(record.csize).is_some_and(|record_end| record_end <= end)); + } + } + assert_eq!(scan(&complete, 0).len(), 1); + } } diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 52b5de7..effb182 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -6,9 +6,10 @@ //! the compiler can sign the DXIL (unsigned DXIL is rejected by D3D12). use std::cell::RefCell; +use std::collections::HashMap; use std::ffi::c_void; use std::path::{Path, PathBuf}; -use std::sync::OnceLock; +use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::core::{Interface, GUID, HRESULT, PCWSTR}; use windows::Win32::Graphics::Direct3D::Dxc::{DxcBuffer, IDxcBlob, IDxcCompiler3, IDxcResult, CLSID_DxcCompiler, DXC_CP_UTF8}; @@ -198,17 +199,142 @@ pub fn cache_dir() -> PathBuf { /// `compile` through a disk cache in `dir` (big translated programs take seconds in DXC; /// the same console shader comes back every run). Returns (DXIL, from cache). pub fn compile_cached_in(dir: &Path, src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { - let file = dir.join(format!("{:016x}.dxil", cache_key(src, entry, profile))); - if let Ok(b) = std::fs::read(&file) { - if !b.is_empty() { - return Ok((b, true)); + compile_cached_in_with(dir, src, entry, profile, || compile(src, entry, profile, &[])) +} + +type CacheFlight = (PathBuf, u64); + +fn cache_flight(key: CacheFlight) -> Arc> { + static FLIGHTS: OnceLock>>>> = OnceLock::new(); + let mut flights = FLIGHTS.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); + flights.retain(|_, v| v.strong_count() != 0); + if let Some(flight) = flights.get(&key).and_then(Weak::upgrade) { + return flight; + } + let flight = Arc::new(Mutex::new(())); + flights.insert(key, Arc::downgrade(&flight)); + flight +} + +struct ProcessCacheLock { + handle: windows_sys::Win32::Foundation::HANDLE, +} + +impl Drop for ProcessCacheLock { + fn drop(&mut self) { + unsafe { + windows_sys::Win32::System::Threading::ReleaseMutex(self.handle); + windows_sys::Win32::Foundation::CloseHandle(self.handle); } } +} + +fn cache_mutex_name(file: &Path) -> String { + let absolute = if file.is_absolute() { + file.to_path_buf() + } else { + std::env::current_dir().unwrap_or_default().join(file) + }; + let mut h = 0xcbf2_9ce4_8422_2325u64; + for b in absolute.to_string_lossy().to_lowercase().bytes() { + h ^= b as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + format!(r"Local\OlympusDxilCache-{h:016x}") +} + +fn process_cache_lock(file: &Path) -> Result { + use windows_sys::Win32::Foundation::{CloseHandle, WAIT_ABANDONED, WAIT_OBJECT_0}; + use windows_sys::Win32::System::Threading::{CreateMutexW, WaitForSingleObject, INFINITE}; + let name = crate::util::wide(&cache_mutex_name(file)); + let handle = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) }; + if handle.is_null() { + return Err("DXIL cache: cannot create the cross-process mutex".into()); + } + let wait = unsafe { WaitForSingleObject(handle, INFINITE) }; + if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED { + unsafe { CloseHandle(handle) }; + return Err(format!("DXIL cache: waiting for the cross-process mutex failed ({wait:#x})")); + } + Ok(ProcessCacheLock { handle }) +} + +fn cached_file(file: &Path) -> Option> { + if let Ok(b) = std::fs::read(&file) { + if valid_dxil_container(&b) { + return Some(b); + } + } + None +} + +/// Cheap validation before handing a cached blob to D3D12. DXIL uses the DXBC +/// container header: magic, hash, version, total size, chunk count and offsets. +fn valid_dxil_container(blob: &[u8]) -> bool { + let rd = |at: usize| { + blob.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize) + }; + if blob.len() < 36 || blob.get(..4) != Some(b"DXBC") || rd(20) != Some(1) || rd(24) != Some(blob.len()) { + return false; + } + let Some(count) = rd(28) else { return false }; + if count == 0 || count > 64 { + return false; + } + let Some(table_end) = 32usize.checked_add(count * 4) else { return false }; + if table_end > blob.len() { + return false; + } + let mut ranges = Vec::with_capacity(count); + let mut has_dxil = false; + for i in 0..count { + let Some(off) = rd(32 + i * 4) else { return false }; + if off < table_end || off & 3 != 0 { + return false; + } + let Some(size) = rd(off + 4) else { return false }; + let Some(end) = off.checked_add(8).and_then(|v| v.checked_add(size)) else { return false }; + if end > blob.len() || ranges.iter().any(|&(a, b)| off < b && a < end) { + return false; + } + if blob.get(off..off + 4) == Some(b"DXIL") { + // DxilProgramHeader is six dwords before the bitcode payload. + if size < 24 || blob.get(off + 16..off + 20) != Some(b"DXIL") { + return false; + } + has_dxil = true; + } + ranges.push((off, end)); + } + has_dxil +} + +fn compile_cached_in_with(dir: &Path, src: &str, entry: &str, profile: &str, compile_one: F) -> Result<(Vec, bool), String> +where + F: FnOnce() -> Result, String>, +{ + let key = cache_key(src, entry, profile); + let file = dir.join(format!("{key:016x}.dxil")); + if let Some(b) = cached_file(&file) { + return Ok((b, true)); + } + let flight = cache_flight((dir.to_path_buf(), key)); + let _guard = flight.lock().unwrap_or_else(|e| e.into_inner()); + let _process_guard = process_cache_lock(&file)?; + // Another caller may have populated the cache while this one waited. + if let Some(b) = cached_file(&file) { + return Ok((b, true)); + } if CACHED_ONLY.with(|c| c.get()) { MISSED.with(|m| m.set(true)); return Err("DXIL not compiled yet".into()); } - let b = compile(src, entry, profile, &[])?; + // A corrupt target must be removed before the atomic rename on Windows; + // rename does not replace an existing file there. + if file.is_file() { + let _ = std::fs::remove_file(&file); + } + let b = compile_one()?; if std::fs::create_dir_all(dir).is_ok() { // write to a temporary name first: another thread / process may be reading let tmp = file.with_extension(format!("tmp{}", std::process::id())); @@ -246,6 +372,22 @@ pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, #[cfg(test)] mod cache_tests { use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + fn synthetic_dxil(marker: u8) -> Vec { + let mut b = vec![0u8; 68]; + b[..4].copy_from_slice(b"DXBC"); + b[20..24].copy_from_slice(&1u32.to_le_bytes()); + b[24..28].copy_from_slice(&68u32.to_le_bytes()); + b[28..32].copy_from_slice(&1u32.to_le_bytes()); + b[32..36].copy_from_slice(&36u32.to_le_bytes()); + b[36..40].copy_from_slice(b"DXIL"); + b[40..44].copy_from_slice(&24u32.to_le_bytes()); + b[52..56].copy_from_slice(b"DXIL"); // inner DxilBitcodeHeader magic + b[67] = marker; + b + } #[test] fn dxil_cache_round_trip() { @@ -261,4 +403,137 @@ mod cache_tests { assert_ne!(cache_key(src, "main", "cs_6_6"), cache_key(src, "main", "cs_6_7")); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn validates_dxil_cache_structure_and_rebuilds_corruption() { + let valid = synthetic_dxil(7); + assert!(valid_dxil_container(&valid)); + assert!(!valid_dxil_container(&valid[..valid.len() - 1])); + let mut bad = valid.clone(); + bad[0] = b'X'; + assert!(!valid_dxil_container(&bad)); + let mut bad = valid.clone(); + bad[24..28].copy_from_slice(&999u32.to_le_bytes()); + assert!(!valid_dxil_container(&bad)); + let mut bad = valid.clone(); + bad[32..36].copy_from_slice(&35u32.to_le_bytes()); + assert!(!valid_dxil_container(&bad)); + let mut bad = valid.clone(); + bad[36..40].copy_from_slice(b"STAT"); + assert!(!valid_dxil_container(&bad)); + let mut bad = valid.clone(); + bad[52..56].fill(0); + assert!(!valid_dxil_container(&bad)); + + let mut overlap = vec![0u8; 80]; + overlap[..4].copy_from_slice(b"DXBC"); + overlap[20..24].copy_from_slice(&1u32.to_le_bytes()); + overlap[24..28].copy_from_slice(&80u32.to_le_bytes()); + overlap[28..32].copy_from_slice(&2u32.to_le_bytes()); + overlap[32..36].copy_from_slice(&40u32.to_le_bytes()); + overlap[36..40].copy_from_slice(&40u32.to_le_bytes()); + overlap[40..44].copy_from_slice(b"DXIL"); + overlap[44..48].copy_from_slice(&24u32.to_le_bytes()); + overlap[56..60].copy_from_slice(b"DXIL"); + assert!(!valid_dxil_container(&overlap)); + + let dir = std::env::temp_dir().join(format!("olympus-dxil-corrupt-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let key = cache_key("corrupt", "main", "cs_6_6"); + let file = dir.join(format!("{key:016x}.dxil")); + std::fs::write(&file, b"truncated cache entry").unwrap(); + let calls = AtomicUsize::new(0); + let (rebuilt, hit) = compile_cached_in_with(&dir, "corrupt", "main", "cs_6_6", || { + calls.fetch_add(1, Ordering::SeqCst); + Ok(synthetic_dxil(8)) + }) + .unwrap(); + assert!(!hit); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(rebuilt, synthetic_dxil(8)); + let (_, hit) = compile_cached_in_with(&dir, "corrupt", "main", "cs_6_6", || panic!("valid rebuilt entry was not reused")).unwrap(); + assert!(hit); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn concurrent_cache_misses_compile_once() { + let dir = std::env::temp_dir().join(format!("olympus-dxil-flight-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let calls = AtomicUsize::new(0); + let hits = AtomicUsize::new(0); + std::thread::scope(|s| { + let mut threads = Vec::new(); + for _ in 0..8 { + threads.push(s.spawn(|| { + let (dxil, hit) = compile_cached_in_with(&dir, "same source", "main", "cs_6_6", || { + calls.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(25)); + Ok(synthetic_dxil(4)) + }) + .unwrap(); + assert_eq!(dxil, synthetic_dxil(4)); + hits.fetch_add(hit as usize, Ordering::SeqCst); + })); + } + for thread in threads { + thread.join().unwrap(); + } + }); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(hits.load(Ordering::SeqCst), 7); + + // A failed leader releases the flight; the next caller can retry. + let failed = compile_cached_in_with(&dir, "retry", "main", "cs_6_6", || Err("synthetic failure".into())); + assert!(failed.is_err()); + let (dxil, hit) = compile_cached_in_with(&dir, "retry", "main", "cs_6_6", || Ok(synthetic_dxil(9))).unwrap(); + assert!(!hit); + assert_eq!(dxil, synthetic_dxil(9)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn different_cache_keys_do_not_block_each_other() { + let dir = std::env::temp_dir().join(format!("olympus-dxil-parallel-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let barrier = std::sync::Barrier::new(2); + std::thread::scope(|s| { + let a = s.spawn(|| compile_cached_in_with(&dir, "source a", "main", "cs_6_6", || { + barrier.wait(); + Ok(synthetic_dxil(1)) + })); + let b = s.spawn(|| compile_cached_in_with(&dir, "source b", "main", "cs_6_6", || { + barrier.wait(); + Ok(synthetic_dxil(2)) + })); + assert_eq!(a.join().unwrap().unwrap().0, synthetic_dxil(1)); + assert_eq!(b.join().unwrap().unwrap().0, synthetic_dxil(2)); + }); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn process_cache_mutex_serializes_the_same_file() { + let file = std::env::temp_dir().join(format!("olympus-dxil-mutex-{}-{}.dxil", std::process::id(), cache_key("mutex", "main", "cs_6_6"))); + let (held_tx, held_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let (second_tx, second_rx) = std::sync::mpsc::channel(); + std::thread::scope(|s| { + let first_file = file.clone(); + s.spawn(move || { + let _guard = process_cache_lock(&first_file).unwrap(); + held_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }); + held_rx.recv().unwrap(); + s.spawn(move || { + let _guard = process_cache_lock(&file).unwrap(); + second_tx.send(()).unwrap(); + }); + assert!(second_rx.recv_timeout(Duration::from_millis(30)).is_err()); + release_tx.send(()).unwrap(); + second_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + }); + } } diff --git a/crates/xcl/src/rpf.rs b/crates/xcl/src/rpf.rs index 5b01bc7..bc92baa 100644 --- a/crates/xcl/src/rpf.rs +++ b/crates/xcl/src/rpf.rs @@ -2,8 +2,13 @@ //! lists the records of an RPF9 package (name, sizes, signature of the unpacked data) and //! extracts the matching ones. Same record scan as the shader pack (`gpu::pack`). -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{self, Write}; +use std::os::windows::ffi::OsStrExt; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_WRITE_THROUGH}; use crate::gpu::pack; @@ -17,6 +22,78 @@ fn magic(b: &[u8]) -> String { } } +/// Choose a deterministic output path without overwriting another record or an +/// existing file. Duplicate inline names are legal because the scanner does not +/// rely on a table of contents; retain both by suffixing later records with their +/// archive offset. +fn extraction_path(out: &Path, name: &str, offset: usize, used: &mut BTreeSet) -> PathBuf { + let safe = name.replace(['/', '\\', ':'], "_"); + let first = out.join(&safe); + if !first.exists() && used.insert(first.clone()) { + return first; + } + + let mut n = 0usize; + loop { + let suffix = if n == 0 { + format!("{safe}.{offset:08x}") + } else { + format!("{safe}.{offset:08x}.{n}") + }; + let path = out.join(suffix); + if !path.exists() && used.insert(path.clone()) { + return path; + } + n += 1; + } +} + +static TEMP_ID: AtomicU64 = AtomicU64::new(0); + +struct TempPath(PathBuf); + +impl Drop for TempPath { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +fn atomic_write_with( + path: &Path, + data: &[u8], + before_commit: impl FnOnce(&Path) -> io::Result<()>, +) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "output has no parent"))?; + let name = path.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "output has no file name"))?; + let (temporary, mut file) = loop { + let id = TEMP_ID.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!(".{}.tmp.{}.{id}", name.to_string_lossy(), std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&candidate) { + Ok(file) => break (TempPath(candidate), file), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + }; + + file.write_all(data)?; + file.sync_all()?; + drop(file); + if path.exists() { + return Err(io::Error::new(io::ErrorKind::AlreadyExists, "output appeared during extraction")); + } + before_commit(&temporary.0)?; + let from: Vec = temporary.0.as_os_str().encode_wide().chain([0]).collect(); + let to: Vec = path.as_os_str().encode_wide().chain([0]).collect(); + if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), MOVEFILE_WRITE_THROUGH) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +fn atomic_write(path: &Path, data: &[u8]) -> io::Result<()> { + atomic_write_with(path, data, |_| Ok(())) +} + pub fn run(path: &Path, args: &[String]) -> i32 { let opt = |n: &str| args.iter().position(|a| a == n).and_then(|i| args.get(i + 1)).cloned(); let top: usize = opt("--top").and_then(|v| v.parse().ok()).unwrap_or(30); @@ -43,8 +120,13 @@ pub fn run(path: &Path, args: &[String]) -> i32 { println!("{}: {:.1} MB, no records with plain names", path.display(), data.len() as f64 / 1048576.0); println!("RPF9 archives (headers every 2 KB): {}", heads.len()); for &h in heads.iter().take(top) { - let w = |o: usize| u32::from_le_bytes(data[h + o..h + o + 4].try_into().unwrap()); - println!(" {h:#010x}: fields {:#x} {:#x} {:#x}", w(4), w(8), w(12)); + let fields = h.checked_add(4).and_then(|start| h.checked_add(16).and_then(|end| data.get(start..end))); + if let Some(fields) = fields { + let w = |o: usize| u32::from_le_bytes(fields[o..o + 4].try_into().unwrap()); + println!(" {h:#010x}: fields {:#x} {:#x} {:#x}", w(0), w(4), w(8)); + } else { + println!(" {h:#010x}: truncated header"); + } } if same { println!("TOC encrypted: every archive starts its table of contents with the same bytes (a fixed key from the game) – unreadable without the exe"); @@ -65,6 +147,9 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let mut by_magic: BTreeMap = BTreeMap::new(); let mut shown = 0; let mut extracted = 0; + let mut extraction_errors = 0; + let mut output_ready = false; + let mut extraction_paths = BTreeSet::new(); for r in &recs { let ext = r.name.rsplit_once('.').map(|x| x.1.to_ascii_lowercase()).unwrap_or_else(|| "(no extension)".into()); let e = by_ext.entry(ext).or_default(); @@ -75,17 +160,33 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if !(hit && shown < top) && !want && by_magic.len() > 64 { continue; } - let Some(blob) = pack::inflate(&data, r) else { continue }; + let Some(blob) = pack::inflate(&data, r) else { + if want { + extraction_errors += 1; + eprintln!("xcl rpf: cannot unpack {} at {:#x}", r.name, r.offset); + } + continue; + }; *by_magic.entry(magic(&blob)).or_default() += 1; if hit && shown < top { println!(" {:#010x} {:>9} → {:>9} B [{}] {}", r.offset, r.csize, r.usize, magic(&blob), r.name); shown += 1; } if want { - let _ = std::fs::create_dir_all(&out); - let file = out.join(r.name.replace(['/', '\\', ':'], "_")); - if std::fs::write(&file, &blob).is_ok() { - extracted += 1; + if !output_ready { + if let Err(error) = std::fs::create_dir_all(&out) { + eprintln!("xcl rpf: cannot create {}: {error}", out.display()); + return 2; + } + output_ready = true; + } + let file = extraction_path(&out, &r.name, r.offset, &mut extraction_paths); + match atomic_write(&file, &blob) { + Ok(()) => extracted += 1, + Err(error) => { + extraction_errors += 1; + eprintln!("xcl rpf: cannot extract {} to {}: {error}", r.name, file.display()); + } } } } @@ -99,5 +200,156 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if extract.is_some() { println!("extracted {extracted} to {}", out.display()); } - 0 + if extraction_errors == 0 { 0 } else { 2 } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn record(name: &str, payload: &[u8]) -> Vec { + let compressed = miniz_oxide::deflate::compress_to_vec(payload, 6); + let mut bytes = vec![(name.len() + 1) as u8]; + bytes.extend_from_slice(name.as_bytes()); + bytes.push(0); + bytes.push(50); + for value in [ + compressed.len() as u32, + 0, + compressed.len() as u32, + payload.len() as u32, + ] { + bytes.extend_from_slice(&value.to_le_bytes()); + } + bytes.extend_from_slice(&compressed); + bytes + } + + #[test] + fn extraction_preserves_duplicate_record_names() { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let root = std::env::temp_dir().join(format!("olympus-rpf-{}-{nonce}", std::process::id())); + let archive = root.join("synthetic.rpf"); + let out = root.join("out"); + std::fs::create_dir_all(&root).unwrap(); + + let mut data = b"9FPR".to_vec(); + data.resize(0x40, 0); + data.extend(record("PS_Duplicate", b"first")); + data.extend(record("PS_Duplicate", b"second")); + let records = pack::scan(&data, 0x40); + assert_eq!(records.len(), 2); + std::fs::write(&archive, data).unwrap(); + + let args = vec![ + "--extract".into(), + "PS_Duplicate".into(), + "--out".into(), + out.to_string_lossy().into_owned(), + ]; + assert_eq!(run(&archive, &args), 0); + assert_eq!(std::fs::read(out.join("PS_Duplicate")).unwrap(), b"first"); + assert_eq!( + std::fs::read(out.join(format!("PS_Duplicate.{:08x}", records[1].offset))).unwrap(), + b"second" + ); + + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn atomic_extraction_cleans_up_an_interrupted_write() { + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("olympus-rpf-atomic-{}-{nonce}", std::process::id())); + let output = root.join("record.bin"); + std::fs::create_dir_all(&root).unwrap(); + + let error = atomic_write_with(&output, b"complete payload", |_| { + Err(io::Error::new(io::ErrorKind::Other, "injected before commit")) + }) + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::Other); + assert!(!output.exists()); + assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0); + + let error = atomic_write_with(&output, b"replacement", |_| std::fs::write(&output, b"appeared concurrently")).unwrap_err(); + assert!(matches!(error.kind(), io::ErrorKind::AlreadyExists | io::ErrorKind::PermissionDenied)); + assert_eq!(std::fs::read(&output).unwrap(), b"appeared concurrently"); + assert_eq!(std::fs::read_dir(&root).unwrap().count(), 1); + + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn extraction_reports_an_unusable_output_directory() { + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("olympus-rpf-error-{}-{nonce}", std::process::id())); + let archive = root.join("synthetic.rpf"); + let output_file = root.join("not-a-directory"); + std::fs::create_dir_all(&root).unwrap(); + + let mut data = b"9FPR".to_vec(); + data.resize(0x40, 0); + data.extend(record("PS_OutputProbe", b"payload")); + std::fs::write(&archive, data).unwrap(); + std::fs::write(&output_file, b"preserve me").unwrap(); + + let args = vec![ + "--extract".into(), + "PS_OutputProbe".into(), + "--out".into(), + output_file.to_string_lossy().into_owned(), + ]; + assert_eq!(run(&archive, &args), 2); + assert_eq!(std::fs::read(&output_file).unwrap(), b"preserve me"); + + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn extraction_reports_a_corrupt_matching_record() { + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("olympus-rpf-corrupt-{}-{nonce}", std::process::id())); + let archive = root.join("synthetic.rpf"); + let out = root.join("out"); + std::fs::create_dir_all(&root).unwrap(); + + let name = "PS_CorruptProbe"; + let mut bad_record = record(name, b"payload"); + let data_offset = name.len() + 19; + bad_record[data_offset..].fill(0xff); + let mut data = b"9FPR".to_vec(); + data.resize(0x40, 0); + data.extend(bad_record); + std::fs::write(&archive, data).unwrap(); + + let args = vec!["--extract".into(), name.into(), "--out".into(), out.to_string_lossy().into_owned()]; + assert_eq!(run(&archive, &args), 2); + assert!(!out.exists()); + + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn truncated_rpf_headers_are_reported_without_panicking() { + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("olympus-rpf-header-{}-{nonce}", std::process::id())); + let archive = root.join("truncated.rpf"); + std::fs::create_dir_all(&root).unwrap(); + + std::fs::write(&archive, b"9FPR").unwrap(); + assert_eq!(run(&archive, &[]), 0); + + let mut nested = vec![0u8; 0x800]; + nested[..4].copy_from_slice(b"9FPR"); + nested.extend_from_slice(b"9FPR"); + std::fs::write(&archive, nested).unwrap(); + assert_eq!(run(&archive, &[]), 0); + + std::fs::remove_dir_all(root).unwrap(); + } }