Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions crates/xcl/src/hle/bcpack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub enum Error {
OutputSize,
/// the stream is truncated, malformed, or ends in a bad lane state
Decode(&'static str),
OutOfMemory,
}

impl Error {
Expand All @@ -26,6 +27,7 @@ impl Error {
Error::Unsupported => "unsupported",
Error::OutputSize => "output size",
Error::Decode(_) => "decode",
Error::OutOfMemory => "out of memory",
}
}
}
Expand All @@ -36,6 +38,7 @@ impl std::fmt::Display for Error {
Error::Unsupported => write!(f, "no decoder for this mode"),
Error::OutputSize => write!(f, "the output size is not a whole number of blocks"),
Error::Decode(why) => write!(f, "{why}"),
Error::OutOfMemory => write!(f, "BCPack output allocation failed"),
}
}
}
Expand All @@ -60,9 +63,14 @@ pub fn decode(mode: u8, src: &[u8], out_len: usize) -> Result<Vec<u8>, Error> {
if out_len == 0 || out_len % block != 0 {
return Err(Error::OutputSize);
}
let mut out = vec![0u8; out_len];
let mut out = Vec::new();
out.try_reserve_exact(out_len).map_err(|_| Error::OutOfMemory)?;
out.resize(out_len, 0);
victory::decode(mode, src, &mut out, victory::Tables::builtin())
.map_err(|e| Error::Decode(e.0))?;
.map_err(|e| match e {
victory::Error::OutOfMemory => Error::OutOfMemory,
victory::Error::Decode(message) => Error::Decode(message),
})?;
Ok(out)
}

Expand Down
25 changes: 17 additions & 8 deletions crates/xcl/src/hle/bcpack/victory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,17 @@
use std::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Error(pub &'static str);
pub enum Error {
Decode(&'static str),
OutOfMemory,
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "BCPack: {}", self.0)
match self {
Self::Decode(message) => write!(f, "BCPack: {message}"),
Self::OutOfMemory => write!(f, "BCPack: output allocation failed"),
}
}
}

Expand Down Expand Up @@ -101,15 +107,18 @@ pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(),
let block = match bc {
1 | 4 => 8,
3 | 5 | 6 | 7 => 16,
_ => return Err(Error("unsupported BC format")),
_ => return Err(Error::Decode("unsupported BC format")),
};
if dst.is_empty() || !dst.len().is_multiple_of(block) {
return Err(Error("destination is not a whole number of blocks"));
return Err(Error::Decode("destination is not a whole number of blocks"));
}
let blocks = dst.len() / block;
let (widths, per) = lane_layout(bc);
let stride = widths.len() * per;
let mut records = vec![0u8; blocks * stride];
let record_len = blocks.checked_mul(stride).ok_or(Error::OutOfMemory)?;
let mut records = Vec::new();
records.try_reserve_exact(record_len).map_err(|_| Error::OutOfMemory)?;
records.resize(record_len, 0);
let mut next = src.iter().copied();
lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?;
let records = records.chunks_exact(stride);
Expand Down Expand Up @@ -312,7 +321,7 @@ fn lanes(
// Nothing read and nothing delivered for a few rounds: no lane can go on.
idle = if taken > 0 || moved { 0 } else { idle + 1 };
if idle > 3 {
return Err(Error("the stream ends early or is corrupt"));
return Err(Error::Decode("the stream ends early or is corrupt"));
}
}
Ok(())
Expand Down Expand Up @@ -617,7 +626,7 @@ fn bc7<'a>(
let (ep_ref, ix_ref) = references(s, true);
let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)];
if ctrl == 0 {
return Err(Error("unused BC7 control code"));
return Err(Error::Decode("unused BC7 control code"));
}
let mode = usize::from(ctrl & 7);
let subsets = usize::from((ctrl & 0xff) >> 6);
Expand Down Expand Up @@ -929,7 +938,7 @@ fn bc6<'a>(
let (ep_ref, ix_ref) = references(s, true);
let mode = s[30].wrapping_add(1);
if !(1..=14).contains(&mode) {
return Err(Error("BC6H mode out of range"));
return Err(Error::Decode("BC6H mode out of range"));
}
let two = mode < 11;
let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b));
Expand Down
62 changes: 54 additions & 8 deletions crates/xcl/src/hle/dstorage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use windows_sys::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAM
use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};
use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent};

use crate::util::{HRESULT, S_OK};
use crate::util::{HRESULT, S_OK, E_OUTOFMEMORY};

const DLL: &str = "xcrdapi.dll";

Expand Down Expand Up @@ -261,16 +261,21 @@ fn bcpack_unpack(r: &Request, packed: &[u8], n: usize) -> Result<Vec<u8>, HRESUL
Ok(blocks)
}
Err(e) => {
let hr = if matches!(&e, &super::bcpack::Error::OutOfMemory) {
E_OUTOFMEMORY
} else {
E_DECOMPRESSION
};
let k = UNPACKED.failed[i].fetch_add(1, Ordering::Relaxed) + 1;
// one warning per mode and kind of failure, then a running count
warn_once(
&format!("BCPack {} stream ({})", bcpack_name(bc), e.kind()),
format_args!("{e} (packed={}, dst={n}); the request fails with E_DECOMPRESSION", packed.len()),
format_args!("{e} (packed={}, dst={n}); the request fails with {hr:#010x}", packed.len()),
);
if k <= 16 || k.is_power_of_two() {
crate::xlog_info!("DirectStorage: BCPack {} streams not unpacked so far: {k}", bcpack_name(bc));
}
Err(E_DECOMPRESSION)
Err(hr)
}
}
}
Expand Down Expand Up @@ -720,6 +725,14 @@ impl Request {
if self.destination == 0 || (self.memory_source() && self.source == 0) {
return Err(E_ACCESS_VIOLATION);
}
// Keep guest-controlled DirectStorage allocations within the existing 256 MiB limit.
const MAX_REQUEST_SIZE: u32 = 256 * 1024 * 1024;
if self.source_size > MAX_REQUEST_SIZE
|| self.destination_size > MAX_REQUEST_SIZE
|| self.intermediate_size > MAX_REQUEST_SIZE
{
return Err(E_OUTOFMEMORY);
}
if self.options & !KNOWN_OPTIONS_MASK != 0 {
warn_once("DSTORAGE_REQUEST_OPTIONS", format_args!("unknown high option bits {:#x}", self.options & !KNOWN_OPTIONS_MASK));
}
Expand Down Expand Up @@ -835,6 +848,13 @@ fn read_exact_at(f: &std::fs::File, offset: u64, buf: &mut [u8]) -> Result<(), H
Ok(())
}

fn zeroed_buffer(len: usize) -> Result<Vec<u8>, HRESULT> {
let mut buffer = Vec::new();
buffer.try_reserve_exact(len).map_err(|_| E_OUTOFMEMORY)?;
buffer.resize(len, 0);
Ok(buffer)
}

static REQUESTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
Expand Down Expand Up @@ -871,24 +891,37 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us
return Err(E_ACCESS_VIOLATION);
}
let src: Vec<u8> = if r.memory_source() {
let mut b = vec![0u8; r.source_size as usize];
if r.source_physical_pages() {
let pages = src_pages.ok_or(E_ACCESS_VIOLATION)?;
if !crate::hle::kernelx::read_physical_pages(pages, r.source_page_offset as usize, &mut b) {
let mut b = zeroed_buffer(r.source_size as usize)?;
if !crate::hle::kernelx::read_physical_pages(
pages,
r.source_page_offset as usize,
&mut b,
) {
return Err(E_ACCESS_VIOLATION);
}
b
} else {
if !crate::gpu::shader::readable(r.source as usize, r.source_size as usize) {
return Err(E_ACCESS_VIOLATION);
}
let mut b = zeroed_buffer(r.source_size as usize)?;
if !b.is_empty() {
std::ptr::copy_nonoverlapping(r.source as *const u8, b.as_mut_ptr(), b.len());
}
b
}
b
} else {
let f = file.and_then(|f| f.handle()).ok_or(E_FILE_HANDLE)?;
let mut b = vec![0u8; r.source_size as usize];
let end = r.offset.checked_add(r.source_size as u64).ok_or(E_END_OF_FILE)?;
let file_len = f.metadata()
.map_err(|e| e.raw_os_error().map_or(E_ABORT, |c| (0x8007_0000u32 | (c as u32 & 0xFFFF)) as i32))?
.len();
if end > file_len {
return Err(E_END_OF_FILE);
}
let mut b = zeroed_buffer(r.source_size as usize)?;
read_exact_at(&f, r.offset, &mut b)?;
b
};
Expand All @@ -901,7 +934,15 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us
// the stages in the console's order: zlib, then BCPack
let stage1: Vec<u8> = if r.zlib() {
let stage1_len = if r.intermediate_size != 0 { r.intermediate_size as usize } else { n };
let mut d = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&src, stage1_len).map_err(|_| E_ZLIB_DATA)?;
let mut d = zeroed_buffer(stage1_len)?;
let written = miniz_oxide::inflate::decompress_slice_iter_to_slice(
&mut d,
std::iter::once(src.as_slice()),
true,
false,
)
.map_err(|_| E_ZLIB_DATA)?;
d.truncate(written);
// zlib yields `intermediate_size` bytes; when the title names none, the destination's
// size, or before BCPack a stream of any size up to it. That last case is XCL's
// leniency, as is a BCPack stream no smaller than its blocks: the GDK documents
Expand Down Expand Up @@ -2637,4 +2678,9 @@ mod tests {
status_release(s);
}
}

#[test]
fn zeroed_buffer_rejects_impossible_allocation() {
assert!(matches!(zeroed_buffer(usize::MAX), Err(E_OUTOFMEMORY)));
}
}
Loading