formats: guard bitstream signed and 32-bit reads against shift overflow in XMA (fix on a fork) #907

Open
opened 2026-11-26 04:14:08 +00:00 by github-bot · 4 comments
Owner

@⁠DaniiL35 on GitHub · 2026-11-24 13:55 UTC · original

Pull requests are currently restricted to collaborators (#717), so I am sharing this bug report and verified fix from a clean fork branch off main (ffe310e).

• Branch: https://github.com/DaniiL35/VIctory/tree/fix/xma-bits-shift-overflow
• Commit: 0c38285 (based on main ffe310e, crates/victory-formats/src/xma.rs +38)
• Compare: https://github.com/Marvisak/VIctory/compare/main...DaniiL35:VIctory:fix/xma-bits-shift-overflow

Problem

In crates/victory-formats/src/xma.rs:

  1. Bits::signed(n) (lines 192–194) performed:
    ((self.read(n) << (32 - n)) as i32) >> (32 - n)
    
    Unlike read(n) above it which checked if n == 0 { return 0; }, signed(n) did not check for n == 0. When n == 0, 32 - n is 32. Shifting a 32-bit integer by 32 bits (val << 32 or val >> 32) is undefined behavior in C/C++ and triggers an unconditional overflow panic in Rust (attempt to shift left with overflow).
  2. If n > 32, 32 - n underflows u32, triggering an arithmetic underflow panic.
  3. In Bits::read(n), if n >= 32, computing 32 - n also suffers from shift overflow or underflow.

Fix

  1. Guard signed(n): return 0 when n == 0, and return self.read(n) as i32 when n >= 32.
  2. Guard read(n): when n >= 32, return self.peek32() directly, advancing self.pos += n as usize.
  3. Added synthetic unit test bitstream_handles_zero_and_boundary_bit_widths asserting n == 0, n == 32, and signed two's-complement parsing across boundary widths without panic.

Verification & Policy Compliance

  • Pure synthetic byte arrays; zero game assets, audio files, or SDK binaries.
  • Complies with Rule #1 (Asset Policy) and passes cargo xtask policy (text-only, <512 KiB).
  • Formatted with Rust 2024 edition.
  • Clean diff on top of main (ffe310e).

AI-assisted with Antigravity.

**@⁠DaniiL35** on GitHub · 2026-11-24 13:55 UTC · [original](https://github.com/Marvisak/VIctory/issues/907) Pull requests are currently restricted to collaborators (#717), so I am sharing this bug report and verified fix from a clean fork branch off `main` (`ffe310e`). • **Branch**: https://github.com/DaniiL35/VIctory/tree/fix/xma-bits-shift-overflow • **Commit**: `0c38285` (based on `main` `ffe310e`, `crates/victory-formats/src/xma.rs` +38) • **Compare**: https://github.com/Marvisak/VIctory/compare/main...DaniiL35:VIctory:fix/xma-bits-shift-overflow ### Problem In `crates/victory-formats/src/xma.rs`: 1. `Bits::signed(n)` (lines 192–194) performed: ```rust ((self.read(n) << (32 - n)) as i32) >> (32 - n) ``` Unlike `read(n)` above it which checked `if n == 0 { return 0; }`, `signed(n)` did not check for `n == 0`. When `n == 0`, `32 - n` is `32`. Shifting a 32-bit integer by 32 bits (`val << 32` or `val >> 32`) is undefined behavior in C/C++ and triggers an unconditional overflow panic in Rust (`attempt to shift left with overflow`). 2. If `n > 32`, `32 - n` underflows `u32`, triggering an arithmetic underflow panic. 3. In `Bits::read(n)`, if `n >= 32`, computing `32 - n` also suffers from shift overflow or underflow. ### Fix 1. Guard `signed(n)`: return `0` when `n == 0`, and return `self.read(n) as i32` when `n >= 32`. 2. Guard `read(n)`: when `n >= 32`, return `self.peek32()` directly, advancing `self.pos += n as usize`. 3. Added synthetic unit test `bitstream_handles_zero_and_boundary_bit_widths` asserting `n == 0`, `n == 32`, and signed two's-complement parsing across boundary widths without panic. ### Verification & Policy Compliance - Pure synthetic byte arrays; zero game assets, audio files, or SDK binaries. - Complies with Rule #1 (Asset Policy) and passes `cargo xtask policy` (text-only, <512 KiB). - Formatted with Rust 2024 edition. - Clean diff on top of `main` (`ffe310e`). AI-assisted with Antigravity.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:14:08 +00:00
Author
Owner

@⁠NATON4 on GitHub · 2026-11-24 14:47 UTC · original

Opened #992 for this (one commit on ffe310e, crates/victory-formats/src/xma.rs only).

Same idea as the fork fix above, with one difference for n > 32: read and signed keep the low 32 bits (the field's value truncated to 32 bits) rather than the first 32, and consume all n bits. The new test xma::tests::bits_read_zero_full_and_oversized_widths panics on main and passes with the change.

@⁠DaniiL35 happy to adjust if you'd prefer your variant.

**@⁠NATON4** on GitHub · 2026-11-24 14:47 UTC · [original](https://github.com/Marvisak/VIctory/issues/907#issuecomment-7134947938) Opened #992 for this (one commit on `ffe310e`, `crates/victory-formats/src/xma.rs` only). Same idea as the fork fix above, with one difference for n > 32: `read` and `signed` keep the **low** 32 bits (the field's value truncated to 32 bits) rather than the first 32, and consume all n bits. The new test `xma::tests::bits_read_zero_full_and_oversized_widths` panics on `main` and passes with the change. @⁠DaniiL35 happy to adjust if you'd prefer your variant.
Author
Owner

@⁠DaniiL35 on GitHub · 2026-11-24 16:17 UTC · original

PR opened directly: #1154

**@⁠DaniiL35** on GitHub · 2026-11-24 16:17 UTC · [original](https://github.com/Marvisak/VIctory/issues/907#issuecomment-7137420011) PR opened directly: #1154
Author
Owner

@⁠studiostephe on GitHub · 2026-11-25 03:03 UTC · original

The guard the earlier PRs (#992, #1154) proposed never landed — both closed without merging, so read/signed on main 940d32f still underflow 32 - n for a width past 32 and signed(0) still shifts by 32.

In crates/victory-formats/src/xma.rs:

  • Bits::read(n) does self.peek32() >> (32 - n). For n > 32 the shift amount underflows; for n == 32 a u32 >> 32 is undefined.
  • Bits::signed(n) does ((self.read(n) << (32 - n)) as i32) >> (32 - n) with no n == 0 guard, so signed(0) shifts a 32-bit value by 32 — a panic in debug, undefined in release.

The fix clamps both to the whole word for a width of 32 or more (a 32-bit read already takes the whole word, so this matches the existing behavior at the boundary and just stops the underflow), and gives signed the same n == 0 early return read has.

diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs
index 02c01bd..e94dba6 100644
--- a/crates/victory-formats/src/xma.rs
+++ b/crates/victory-formats/src/xma.rs
@@ -213,7 +213,13 @@ impl Bits<'_> {
         if n == 0 {
             return 0;
         }
-        let v = self.peek32() >> (32 - n);
+        // `32 - n` underflows for `n > 32` and the result of a `u32 >> 32`
+        // is undefined, so a width of 32 or more takes the whole word.
+        let v = if n >= 32 {
+            self.peek32()
+        } else {
+            self.peek32() >> (32 - n)
+        };
         self.pos += n as usize;
         v
     }
@@ -223,7 +229,16 @@ impl Bits<'_> {
     }
 
     fn signed(&mut self, n: u32) -> i32 {
-        ((self.read(n) << (32 - n)) as i32) >> (32 - n)
+        if n == 0 {
+            return 0;
+        }
+        // `32 - n` underflows for `n > 32`; a width of 32 or more is the
+        // whole word, which needs no shift to sign-extend.
+        let v = self.read(n);
+        if n >= 32 {
+            return v as i32;
+        }
+        ((v << (32 - n)) as i32) >> (32 - n)
     }
 
     fn consumed(&self) -> usize {
@@ -1180,6 +1195,33 @@ fn to_i16(v: f32) -> i16 {
 mod tests {
     use super::*;
 
+    /// A bit width of 0 or more than 32 must not underflow `32 - n` in a
+    /// shift (which panics in debug and is undefined in release): `read` and
+    /// `signed` clamp to the whole word, as a 32-bit read already does.
+    #[test]
+    fn the_bitstream_clamps_zero_and_wide_bit_widths() {
+        let data = [0b1010_1010, 0b0101_0101, 0b1100_1100, 0b0011_0011, 0b1111_1111];
+        let mut bits = Bits { data: &data, pos: 0, end: data.len() * 8 };
+        assert_eq!(bits.read(0), 0);
+        assert_eq!(bits.signed(0), 0);
+        assert_eq!(bits.consumed(), 0);
+        // A full word takes the whole word with no shift (the old code's
+        // `32 - n` would underflow here and past it).
+        assert_eq!(bits.read(32), 0xaa55_cc33);
+        assert_eq!(bits.read(33), 0xff00_0000); // the next word, zero-padded
+        let mut sign = Bits { data: &data, pos: 0, end: data.len() * 8 };
+        assert_eq!(sign.signed(32), 0xaa55_cc33u32 as i32);
+        assert_eq!(sign.signed(33), 0xff00_0000u32 as i32);
+        // A negative field at the word edge still sign-extends.
+        let mut neg = Bits {
+            data: &[0b1111_0000, 0b0000_1111],
+            pos: 0,
+            end: 16,
+        };
+        assert_eq!(neg.signed(4), -1);
+        assert_eq!(neg.signed(4), 0);
+    }
+
     /// Writes `value` as `n` bits, MSB first, at bit `pos`.
     fn put_bits(data: &mut [u8], pos: usize, n: u32, value: u32) {
         for i in 0..n as usize {

Verified (native, this Mac, victory-formats):

  • New test the_bitstream_clamps_zero_and_wide_bit_widths panics on the unpatched code (attempt to shift left with overflow at signed(0)) and passes with the fix.
  • cargo test -p victory-formats --locked --lib: 39 passed, 0 failed, 5 ignored.
  • cargo clippy -p victory-formats --locked: 0 warnings.

Not covered: the crate's pre-existing rustfmt noise in xma/tables.rs (and a few long lines elsewhere in xma.rs) is untouched — it is already present on clean main and is unrelated to this change; my added lines are fmt-clean. I could not exercise a real XMA stream that actually drives a width ≥ 32 through the decoder (none in the repo's fixtures does), so the guard is verified by the direct bit-width test rather than an end-to-end decode.

Local commit 26de54b on a clean 940d32f (one file, +44/−2).

qwen3.8_27b running locally on an M1 Mac
shout out to Digital Debris Los Angeles

**@⁠studiostephe** on GitHub · 2026-11-25 03:03 UTC · [original](https://github.com/Marvisak/VIctory/issues/907#issuecomment-7151540501) The guard the earlier PRs (#992, #1154) proposed never landed — both closed without merging, so `read`/`signed` on main `940d32f` still underflow `32 - n` for a width past 32 and `signed(0)` still shifts by 32. In `crates/victory-formats/src/xma.rs`: - `Bits::read(n)` does `self.peek32() >> (32 - n)`. For `n > 32` the shift amount underflows; for `n == 32` a `u32 >> 32` is undefined. - `Bits::signed(n)` does `((self.read(n) << (32 - n)) as i32) >> (32 - n)` with no `n == 0` guard, so `signed(0)` shifts a 32-bit value by 32 — a panic in debug, undefined in release. The fix clamps both to the whole word for a width of 32 or more (a 32-bit read already takes the whole word, so this matches the existing behavior at the boundary and just stops the underflow), and gives `signed` the same `n == 0` early return `read` has. ```diff diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index 02c01bd..e94dba6 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -213,7 +213,13 @@ impl Bits<'_> { if n == 0 { return 0; } - let v = self.peek32() >> (32 - n); + // `32 - n` underflows for `n > 32` and the result of a `u32 >> 32` + // is undefined, so a width of 32 or more takes the whole word. + let v = if n >= 32 { + self.peek32() + } else { + self.peek32() >> (32 - n) + }; self.pos += n as usize; v } @@ -223,7 +229,16 @@ impl Bits<'_> { } fn signed(&mut self, n: u32) -> i32 { - ((self.read(n) << (32 - n)) as i32) >> (32 - n) + if n == 0 { + return 0; + } + // `32 - n` underflows for `n > 32`; a width of 32 or more is the + // whole word, which needs no shift to sign-extend. + let v = self.read(n); + if n >= 32 { + return v as i32; + } + ((v << (32 - n)) as i32) >> (32 - n) } fn consumed(&self) -> usize { @@ -1180,6 +1195,33 @@ fn to_i16(v: f32) -> i16 { mod tests { use super::*; + /// A bit width of 0 or more than 32 must not underflow `32 - n` in a + /// shift (which panics in debug and is undefined in release): `read` and + /// `signed` clamp to the whole word, as a 32-bit read already does. + #[test] + fn the_bitstream_clamps_zero_and_wide_bit_widths() { + let data = [0b1010_1010, 0b0101_0101, 0b1100_1100, 0b0011_0011, 0b1111_1111]; + let mut bits = Bits { data: &data, pos: 0, end: data.len() * 8 }; + assert_eq!(bits.read(0), 0); + assert_eq!(bits.signed(0), 0); + assert_eq!(bits.consumed(), 0); + // A full word takes the whole word with no shift (the old code's + // `32 - n` would underflow here and past it). + assert_eq!(bits.read(32), 0xaa55_cc33); + assert_eq!(bits.read(33), 0xff00_0000); // the next word, zero-padded + let mut sign = Bits { data: &data, pos: 0, end: data.len() * 8 }; + assert_eq!(sign.signed(32), 0xaa55_cc33u32 as i32); + assert_eq!(sign.signed(33), 0xff00_0000u32 as i32); + // A negative field at the word edge still sign-extends. + let mut neg = Bits { + data: &[0b1111_0000, 0b0000_1111], + pos: 0, + end: 16, + }; + assert_eq!(neg.signed(4), -1); + assert_eq!(neg.signed(4), 0); + } + /// Writes `value` as `n` bits, MSB first, at bit `pos`. fn put_bits(data: &mut [u8], pos: usize, n: u32, value: u32) { for i in 0..n as usize { ``` **Verified** (native, this Mac, `victory-formats`): - New test `the_bitstream_clamps_zero_and_wide_bit_widths` **panics on the unpatched code** (`attempt to shift left with overflow` at `signed(0)`) and passes with the fix. - `cargo test -p victory-formats --locked --lib`: 39 passed, 0 failed, 5 ignored. - `cargo clippy -p victory-formats --locked`: 0 warnings. **Not covered:** the crate's pre-existing rustfmt noise in `xma/tables.rs` (and a few long lines elsewhere in `xma.rs`) is untouched — it is already present on clean `main` and is unrelated to this change; my added lines are fmt-clean. I could not exercise a real XMA stream that actually drives a width ≥ 32 through the decoder (none in the repo's fixtures does), so the guard is verified by the direct bit-width test rather than an end-to-end decode. Local commit `26de54b` on a clean `940d32f` (one file, +44/−2). qwen3.8_27b running locally on an M1 Mac shout out to Digital Debris Los Angeles
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 06:56 UTC · original

Automated triage for the maintainers.

Confirmed on main (940d32f). In crates/victory-formats/src/xma.rs, Bits::signed computes 32 - n with no n == 0 guard, so signed(0) shifts a u32 by 32. Bits::read guards only n == 0, so a width over 32 underflows 32 - n. Whether the decoder ever asks for such a width hasn't been shown: no XMA stream in the tests does. The earlier PRs #992 and #1154 were closed without merging. Open PR #2061 ("Formats: guard XMA bitstream reads and sign extension at 0 and >=32 bits", which names this issue) carries the guard, so review can continue there.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 06:56 UTC · [original](https://github.com/Marvisak/VIctory/issues/907#issuecomment-7155322021) <!-- victory-issue-triage v1 verdict=confirmed seen=2026-11-25T03:03:04Z at=2026-11-25T06:56:42Z --> Automated triage for the maintainers. Confirmed on `main` (`940d32f`). In `crates/victory-formats/src/xma.rs`, `Bits::signed` computes `32 - n` with no `n == 0` guard, so `signed(0)` shifts a `u32` by 32. `Bits::read` guards only `n == 0`, so a width over 32 underflows `32 - n`. Whether the decoder ever asks for such a width hasn't been shown: no XMA stream in the tests does. The earlier PRs #992 and #1154 were closed without merging. Open PR #2061 ("Formats: guard XMA bitstream reads and sign extension at 0 and >=32 bits", which names this issue) carries the guard, so review can continue there. --- _Generated by [Claude Code](https://claude.ai/code)_
This discussion has been locked. Commenting is limited to contributors.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory#907
No description provided.