Skip to content
Merged
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
28 changes: 27 additions & 1 deletion HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,8 @@ The EXE (+ EOSSDK) imports 31 functions from console libraries: MFPlat `MFResetD
name @0x40), RetrieveErrorRecord 0x290, Query 0x1C. A worker thread per queue runs the submitted requests in order:
file reads through the VFS (as the title's own CreateFileW), memory copies, zlib (miniz_oxide); a status entry gets
the first failure since the previous one, a signal sets the D3D12 fence from the CPU; a half-full queue submits by
itself. BCPack (and other console formats) are refused; the unlisted interface slots are logged E_NOTIMPL. The test
itself. BCPack is unpacked where `hle/bcpack` rebuilds the mode's blocks: BC1 and BC5 (2026-11-23); BC3,
BC4, BC6H and BC7 are refused (see "BCPack blocks" below). The unlisted interface slots are logged E_NOTIMPL. The test
title reads the start of its own exe through it and waits on the fence. Not yet: cancelling submitted requests,
multi-stage (intermediate-size) decompression, destinations that are not plain memory.
- **Texture layout library (`xg_xs.dll`, `hle/xg.rs`)** – Fortnite imports `XGCreateTextureComputer`. XCL's own GFX10
Expand Down Expand Up @@ -1924,6 +1925,31 @@ three `graphics PSO rejected (0x8007000e)` just before are the driver's E_OUTOFM
are on the adapter's device and the per-draw queues were not given back – the draw-heavy tests ended in
E_OUTOFMEMORY at CreateCommandQueue with several test threads.

## BCPack blocks: BC1 and BC5 (2026-11-23)

- **What decodes:** `hle/bcpack` has the entropy stage for every mode and block rebuilds for BC1 and
BC5. A BC5 stream is two symbols per lane per 16-byte block: lane 0 the distance (BC3's
bit-interleaved form), lanes 2/3 the endpoint residues of the two BC4 channels, lanes 4–7 and
8–11 the 3-bit index pairs (64 possible pairs). Each channel is a plain BC4 block.
- **Tables:** neither mode's stream carries its constants. BC5 needs the 64-entry index-pair table
and a 255-slot endpoint history; XCL takes the estimates of the clean-room decoder
leonida-asset-pipeline (MIT, `bc5_tables.rs`), which fits 214 slots; the 42 it does not fit
(and slots 1–2) end a stream with `Error::History` instead of a guess. Only 3 slots (182, 183,
222) are reported as confirmed. Its fits agree with SixNG's within a step on the shared slots.
So BC5 output is an approximation wherever one of those constants is off, as BC1's is.
- **BC7 is not done:** its block layout is documented (lanes, mode/partition/rotation/index
selection from lane 15, endpoint and index states), but the rebuild needs two 256-slot history
tables and 10 of the 285 lane-15 signature ranks that no stream carries. The only sources with
fitted values are GPL-3.0 (SixNG, rage-texture), which a GPL-2.0-only crate cannot take; the
MIT decoder ships them empty. A BC7 decoder without them would refuse nearly every chunk, so
it is left out rather than guessed. Same for BC3, BC4 and BC6H (their fitted selector/history
tables have the same problem).
- **Tests** (synthetic, no game files): `bc5_block_rebuild` (hand-built symbols for an in-stream
reference and a history slot), `bc5_blocks_round_trip_through_a_stream` (blocks → symbols →
fragment encoder → entropy decoder → blocks, 1–300 blocks), `bc5_fixture_decodes_to_blocks`,
`fitted_bc5_tables_are_well_formed` (pair table is a permutation, 214 slots fitted, unknown slot
ends the rebuild).

## Next steps (priority)
Little is left to do without the exe – the rest needs an actual run of the game.
1. Once the user has a legal game exe: `xcl inspect`, `xcl run`, analysis of `report.json`
Expand Down
2 changes: 2 additions & 0 deletions THIRD_PARTY.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ carry a note in their header about its origin and the date of changes (GPL-2.0
| [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation |
| [silicon-rans](https://github.com/microsoft/silicon-rans) (Microsoft) | MIT | BCPack entropy stage: the rANS lane in `crates/xcl/src/hle/bcpack/lanes.rs` (after the `decoder` module of `mdu_minirans.v`) and its model tables in `hle/bcpack/rans_tables.rs` (generated by `scripts/gen_bcpack_tables.py` from the same file) | port to Rust with annotation; tables |
| [bcpack-decoder](https://github.com/Tim0219800/bcpack-decoder) (Tim0219800), [bcpack-rs](https://github.com/Ahmet-Dedeler/bcpack-rs) (Ahmet Dedeler) | MIT | no code; the BCPack stream layout, lane widths, byte feeder rule and BC1 block rule in `hle/bcpack/` follow their format notes (`docs/SPEC.md`, `docs/BCPACK_SPEC.md`) | specification |
| [leonida-asset-pipeline](https://github.com/wxrrry/leonida-asset-pipeline) (wxrrry) | MIT | no code; the BC5 block rule in `hle/bcpack/bc5.rs` follows its clean-room decoder (`tools/bcpack.py`) | specification |
| bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler/bcpack-rs) | MIT (notice in the file) | `crates/xcl/src/hle/bcpack/bc1_fitted.rs` (generated by `scripts/gen_bcpack_bc1_tables.py` from `data/bc1_window.json` and `data/bc1_quad_table.json`): the two tables of BC1 constants BCPack streams do not carry, as bcpack-rs estimated them from retail data | data tables (estimates; codec constants, not game content) |
| leonida-asset-pipeline by wxrrry (https://github.com/wxrrry/leonida-asset-pipeline) | MIT (notice in the file) | `crates/xcl/src/hle/bcpack/bc5_tables.rs` (generated by `scripts/gen_bcpack_bc5_tables.py` from `tools/bcpack_tables.py`): the two tables of BC5 constants BCPack streams do not carry, as leonida-asset-pipeline estimated them from retail data | data tables (estimates; codec constants, not game content) |
| [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts |
| [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only |
| [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification |
Expand Down
67 changes: 66 additions & 1 deletion crates/xcl/src/eh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,25 @@ fn cmp_eflags(eflags: u32, lhs: u64, rhs: u64) -> u32 {
f
}

/// Overwrites the `len` code bytes at `rip` with `head` followed by NOPs, and flushes the
/// instruction cache; left as it is when the page cannot be made writable.
unsafe fn patch_code(rip: usize, len: usize, head: &[u8]) {
use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
if head.len() > len {
return;
}
let mut old = 0u32;
if VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 {
let code = std::slice::from_raw_parts_mut(rip as *mut u8, len);
code.fill(0x90);
code[..head.len()].copy_from_slice(head);
VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old);
FlushInstructionCache(GetCurrentProcess(), rip as *const std::ffi::c_void, len);
}
}

/// A title's STATUS_ILLEGAL_INSTRUCTION: an instruction the console's Zen 2 has and this CPU
/// lacks (`insn`) is emulated and stepped over (EXCEPTION_CONTINUE_EXECUTION); anything else is
/// logged with its code bytes and goes on to the title's handlers.
Expand Down Expand Up @@ -341,8 +360,13 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics
unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) };
}
}
ConsoleOnly::Monitorx => {}
// MONITORX / MWAITX sit in the title's spin-waits: emulating them costs an exception per
// loop iteration, a core's worth of exception dispatch on a CPU without them (any Intel).
// Rewritten in place on first use, as CLWB is: MONITORX becomes NOPs (it only arms the
// monitor) and MWAITX becomes PAUSE (F3 90) and NOPs, the spin hint the loop waits with.
ConsoleOnly::Monitorx => patch_code(rip, len, &[]),
ConsoleOnly::Mwaitx => {
patch_code(rip, len, &[0xF3, 0x90]);
std::hint::spin_loop();
}
ConsoleOnly::Clzero => {
Expand Down Expand Up @@ -1182,6 +1206,47 @@ mod tests {
}
}

/// MONITORX / MWAITX in a title image: on a CPU without them (any Intel) the first run
/// raises STATUS_ILLEGAL_INSTRUCTION, is emulated and rewritten in place (NOPs; PAUSE and a
/// NOP), so later runs raise nothing; on an AMD CPU they run natively and stay as they are.
#[test]
fn monitorx_and_mwaitx_are_rewritten_after_their_first_emulation() {
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE};
// f(): xor eax, eax; xor ecx, ecx; xor edx, edx; monitorx; mwaitx; ret
let f_code: &[u8] = &[0x31, 0xC0, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x0F, 0x01, 0xFB, 0xC3];
unsafe {
let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as *mut u8;
assert!(!page.is_null());
std::ptr::write_bytes(page, 0xCC, 4096);
std::ptr::copy_nonoverlapping(f_code.as_ptr(), page, f_code.len());
modules::register_mapped(std::sync::Arc::new(modules::MappedModule {
name: "mwaitx_test.exe".into(),
path: "mwaitx_test.exe".into(),
base: page as usize,
size: 4096,
entry_rva: 0,
is_dll: false,
exports: Default::default(),
tls_callbacks: Default::default(),
no_thread_calls: Default::default(),
initialized: Default::default(),
stack_reserve: 0,
}));
let veh = windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(cpp_exception_logger));
let f: extern "system" fn() = std::mem::transmute(page);
f();
f();
let code = std::slice::from_raw_parts(page.add(6), 6);
assert!(
code == [0x0F, 0x01, 0xFA, 0x0F, 0x01, 0xFB] || code == [0x90, 0x90, 0x90, 0xF3, 0x90, 0x90],
"left as it was (native) or rewritten (emulated): {code:02x?}"
);
windows_sys::Win32::System::Diagnostics::Debug::RemoveVectoredExceptionHandler(veh);
modules::unregister_mapped(page as usize);
VirtualFree(page as _, 0, MEM_RELEASE);
}
}

static TITLE_FILTER_TEST_LOCK: Mutex<()> = Mutex::new(());

#[test]
Expand Down
122 changes: 122 additions & 0 deletions crates/xcl/src/hle/bcpack/bc5.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
//! BC5 blocks from the 12 lanes of a BCPack BC5 stream (two symbols per 16-byte block).
//!
//! Block `i` reads the symbol `2i` (E) and `2i + 1` (O) of every lane:
//! * lane 0 is a distance `d` back to the block whose endpoints predict this one's, bit
//! interleaved over E and O: `x` takes O's bits at positions 0, 2, 4, 6 and `E >> 1`'s at
//! 1, 3, 5, and `d` is `255 - x` when E's lowest bit is set, `x` otherwise. Symbol 0 is
//! "none" (predict 128 for every endpoint); `d <= i` names block `i - d`; a larger `d` names
//! slot `256 + i - d` of the built-in history ([`Tables::preset`]),
//! * lane 1 is unused; the format notes report it as 0 in every stream, and its symbols are
//! ignored here (the fixture generator fills it with noise),
//! * lanes 2 and 3 hold the residues of the endpoint pairs of channel 0 and channel 1, E for
//! the first endpoint and O for the second, 0, -1, 1, -2, 2 … for the symbols 0, 1, 2, 3,
//! 4 …, modulo 256,
//! * lanes 4–7 hold the index pairs of channel 0 and lanes 8–11 those of channel 1: lane
//! `4 + 4c + k` has E = the indices of pixels `4k` and `4k + 1`, O = pixels `4k + 2` and
//! `4k + 3`, each symbol the index of one of the 64 possible pairs in a fixed order
//! ([`Tables::pairs`]).
//!
//! Each channel is a BC4 block: endpoint 0, endpoint 1, then the 16 3-bit indices of the
//! 4 x 4 texels, low texels first, little-endian. The blocks are in the order of the
//! surface's memory, tiled as the console stores it.
//!
//! After the BC5 sections of the public format notes of the SixNG project and the clean-room
//! decoder of leonida-asset-pipeline (wxrrry, MIT), which agree on every symbol; written for
//! XCL on 2026-11-23.
use super::{lane_widths, lanes, Error};

/// The constants of the BC5 rebuild that are not in a stream.
pub struct Tables {
/// The two 3-bit indices each index symbol codes, the first pixel then the second.
pub pairs: [(u8, u8); 64],
/// The endpoint pairs `[channel 0 e0, channel 0 e1, channel 1 e0, channel 1 e1]` of the
/// blocks before a stream's first: `preset[256 + i - d]` is the block `d - i` before block
/// 0 when `d > i` (slot 0 is never read). `None`: not known.
pub preset: [Option<[u8; 4]>; 256],
}

/// The distance back to the block whose endpoints predict block `i`, from lane 0's symbols.
pub fn distance(e: u8, o: u8) -> usize {
let mut x = 0usize;
for k in 0..4 {
x |= ((o as usize >> k) & 1) << (2 * k);
}
for k in 0..3 {
x |= ((e as usize >> (k + 1)) & 1) << (2 * k + 1);
}
if e & 1 != 0 {
255 - x
} else {
x
}
}

/// The residue a symbol stands for: 0, -1, 1, -2, 2 … for 0, 1, 2, 3, 4 …
fn zigzag(v: u8) -> i32 {
if v & 1 == 0 {
(v >> 1) as i32
} else {
-(((v >> 1) + 1) as i32)
}
}

/// An endpoint from its prediction and residue, modulo 256.
fn endpoint(predicted: u8, symbol: u8) -> u8 {
(predicted as i32 + zigzag(symbol)) as u8
}

/// Unpack a BC5 stream to its `out_len` bytes of blocks.
pub fn decode(src: &[u8], out_len: usize, tables: &Tables) -> Result<Vec<u8>, Error> {
if out_len % 16 != 0 {
return Err(Error::OutputSize);
}
let widths = lane_widths(5).unwrap();
let (symbols, consumed) = lanes::decode(src, widths, out_len / 8)?;
if src[consumed..].iter().any(|&b| b != 0) {
return Err(Error::Trailing { consumed });
}
assemble(&symbols, tables)
}

/// The blocks of `symbols` (24 per block, two units of 12, in [`super::decode_lanes`]'s order).
pub fn assemble(symbols: &[u8], tables: &Tables) -> Result<Vec<u8>, Error> {
let blocks = symbols.len() / 24;
let mut out = Vec::new();
out.try_reserve_exact(blocks * 16).map_err(|_| Error::OutputSize)?;
out.resize(blocks * 16, 0u8);
for i in 0..blocks {
let s = &symbols[i * 24..i * 24 + 24];
let d = distance(s[0], s[12]);
let base = if d == 0 {
[128; 4]
} else if d <= i {
let p = &out[(i - d) * 16..];
[p[0], p[1], p[8], p[9]]
} else {
let slot = 256 + i - d;
tables.preset[slot].ok_or(Error::History { block: i, slot })?
};
let e = [
endpoint(base[0], s[2]),
endpoint(base[1], s[14]),
endpoint(base[2], s[3]),
endpoint(base[3], s[15]),
];
for ch in 0..2 {
let mut bits = 0u64;
for r in 0..4 {
let lane = 4 + 4 * ch + r;
let (a0, a1) = tables.pairs[s[lane] as usize];
let (b0, b1) = tables.pairs[s[12 + lane] as usize];
bits |= ((a0 as u64) | (a1 as u64) << 3 | (b0 as u64) << 6 | (b1 as u64) << 9) << (12 * r);
}
let b = &mut out[i * 16 + 8 * ch..i * 16 + 8 * ch + 8];
b[0] = e[2 * ch];
b[1] = e[2 * ch + 1];
// the 16 indices, 3 bits each, low texels first
b[2..8].copy_from_slice(&bits.to_le_bytes()[..6]);
}
}
Ok(out)
}
Loading
Loading