
Detecting Silent Overflow in Cranelift Bit-Packing Code
Bit-packing code can silently turn an out-of-range value into a different, valid-looking value when it truncates bits, overflows an intermediate calculation, or shifts by an invalid amount. Prevent this by validating field widths and values before packing, using checked arithmetic for offsets and sizes, and testing boundaries as well as round trips. The Wasmtime advisory RUSTSEC-2026-0380 (CVE-2026-115889, GHSA-897f-g5gm-fmxm) makes this a security-relevant review area: use a patched Wasmtime release and verify the exact affected code path rather than assuming a local helper is equivalent.
Environment and baseline specifications
The examples below target Rust 1.82+ (Edition 2021) and use only the standard library. They illustrate a production-safe bit-packing pattern; they are not a reconstruction of Wasmtime’s internal patch. The advisory excerpt identifies the issue as a vulnerability involving Wasmtime and Cranelift bit-packing, but does not include the vulnerable function, affected Cranelift component, or a detailed exploit description. Do not infer those details from the advisory ID alone.
For applications embedding Wasmtime, check the resolved dependency and upgrade to a release in the advisory’s patched ranges: 36.0.19 or later in the 36.x line, or 43.0.0 or later. The advisory lists the affected version ranges as patched at >=36.0.19, <37.0.0 and >=43.0.0. Confirm the full range and applicable release branches in the advisory before deciding whether a particular version is safe. Keep Cargo.lock committed for deployable applications and inspect the actual resolved graph:
cargo tree -i wasmtime
cargo update -p wasmtime
cargo audit
cargo update alone is not proof of remediation: it may select a version constrained by the manifest, lockfile, or dependency graph. Review the selected version and run the project’s regression tests.
Why bit-packing overflow is easy to miss
A packer commonly combines fields using shifts and bitwise OR:
fn pack_bad(a: u32, b: u32) -> u32 {
(a << 12) | b
}
This code silently accepts values wider than their assigned fields. If a exceeds 20 bits, its high bits are shifted out of the u32; if b exceeds 12 bits, its high bits overlap the portion reserved for a. The result may still be a plausible integer, so the error can survive ordinary tests.
Other failure points are less obvious:
- Calculating the total width or byte count with unchecked addition or multiplication.
- Computing a shift or mask for a width equal to the integer type’s bit count.
- Narrowing a wider value with
as, which truncates rather than reporting an error. - Accepting a field width from untrusted or malformed input without validating it.
- Testing only values that fit, leaving overflow and boundary behavior unexamined.
In compiler and JIT code, packed values can encode metadata used later for decoding, indexing, or code generation. A corrupted field may therefore affect a later operation, not just the packer’s immediate return value. The exact impact depends on the code path. Treat any assumption that input values fit as an invariant that must be enforced at the boundary.
Production pattern: validate before packing
A safe packer should make the layout explicit, reject invalid widths, and reject values that do not fit. The following example packs two fields into a 32-bit word. The upper field has a configurable width; the lower field occupies the remaining bits.
#[derive(Debug, PartialEq, Eq)]
enum PackError {
InvalidWidth,
ValueOutOfRange,
}
fn low_mask(width: u32) -> Result<u32, PackError> {
if width > u32::BITS {
return Err(PackError::InvalidWidth);
}
// Shifting by 32 is invalid. Handle the full-width case separately.
if width == u32::BITS {
Ok(u32::MAX)
} else if width == 0 {
Ok(0)
} else {
Ok((1_u32 << width) - 1)
}
}
fn pack_fields(high: u32, high_width: u32, low: u32) -> Result<u32, PackError> {
if high_width > u32::BITS {
return Err(PackError::InvalidWidth);
}
let low_width = u32::BITS
.checked_sub(high_width)
.ok_or(PackError::InvalidWidth)?;
let high_mask = low_mask(high_width)?;
let low_mask = low_mask(low_width)?;
if high & !high_mask != 0 || low & !low_mask != 0 {
return Err(PackError::ValueOutOfRange);
}
// high_width == 32 implies low_width == 0, so low must be zero.
// The checked shift also makes the precondition explicit.
let shifted_high = high
.checked_shl(low_width)
.ok_or(PackError::InvalidWidth)?;
Ok(shifted_high | low)
}
fn unpack_fields(word: u32, high_width: u32) -> Result<(u32, u32), PackError> {
if high_width > u32::BITS {
return Err(PackError::InvalidWidth);
}
let low_width = u32::BITS
.checked_sub(high_width)
.ok_or(PackError::InvalidWidth)?;
let low = word & low_mask(low_width)?;
let high = if low_width == u32::BITS {
0
} else {
word >> low_width
};
Ok((high, low))
}
There is a subtle Rust detail here: checked_shl checks whether the shift amount is less than the integer width; it does not report bits shifted out of the value. That is why the code first checks that high fits its field. Checked shifting cannot replace range validation.
For high_width == 0, the upper field must be zero and the lower field uses all 32 bits. For high_width == 32, the lower field must be zero and the upper field uses all 32 bits. Those cases are handled without evaluating 1 << 32. If the packed format instead requires both fields to have nonzero widths, reject zero and full-width configurations explicitly.
Test boundaries and layout invariants
Test both valid boundaries and invalid values. Round-trip tests alone are insufficient: a packer and unpacker can share the same incorrect layout and still round-trip successfully.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn packs_and_unpacks_maximum_12_bit_fields() {
let high = 0x000f_ffff; // 20 bits
let low = 0x0000_0fff; // 12 bits
let word = pack_fields(high, 20, low).unwrap();
assert_eq!(unpack_fields(word, 20).unwrap(), (high, low));
assert_eq!(word, u32::MAX);
}
#[test]
fn rejects_values_that_overlap_their_fields() {
assert_eq!(
pack_fields(1 << 20, 20, 0),
Err(PackError::ValueOutOfRange)
);
assert_eq!(
pack_fields(0, 20, 1 << 12),
Err(PackError::ValueOutOfRange)
);
}
#[test]
fn handles_zero_and_full_width_without_invalid_shifts() {
assert_eq!(pack_fields(0, 0, u32::MAX), Ok(u32::MAX));
assert_eq!(pack_fields(u32::MAX, 32, 0), Ok(u32::MAX));
assert_eq!(pack_fields(1, 32, 0), Err(PackError::ValueOutOfRange));
assert_eq!(pack_fields(0, 0, 1), Err(PackError::ValueOutOfRange));
}
#[test]
fn rejects_widths_above_the_word_size() {
assert_eq!(pack_fields(0, 33, 0), Err(PackError::InvalidWidth));
assert_eq!(unpack_fields(0, 33), Err(PackError::InvalidWidth));
}
}
For variable-length formats, also test total-size arithmetic separately. For example, use checked_add and checked_mul when calculating a bit offset, byte length, or allocation capacity. Validate conversions with TryFrom rather than as when moving from usize to a smaller integer type. This is especially important when a decoded length controls indexing or allocation; related integer-boundary risks are covered in Preventing Unsafe Integer Conversions in Rust: Avoiding Truncation, Overflow, and Signedness Bugs.
Differential verification and advisory response
Run the focused tests in both debug and release profiles. Debug builds commonly panic on ordinary integer overflow, whereas release builds generally wrap unless overflow checks are enabled. Neither profile catches truncation caused by a cast or an explicit mask, so assertions about field ranges remain essential.
cargo test pack_fields
cargo test --release pack_fields
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-targets --all-features
For code with unsafe pointer arithmetic or uninitialized memory around the packing path, run Miri on the targeted tests as well:
cargo +nightly miri test pack_fields
Miri can detect some classes of undefined behavior; it does not prove that a bit layout is correct or that a value was not silently truncated. Keep explicit boundary and expected-encoding tests. For broader input-space checks, add properties such as “every accepted pair unpacks to the original pair” and “any value with bits outside its assigned mask is rejected.” Property-based testing complements, but does not replace, fixed regression cases; see Effective Property-Based Testing in Rust.
For RUSTSEC-2026-0380, also verify the dependency version and the application-level behavior that reaches the affected Wasmtime functionality. A passing test against a local copy of a packing helper does not establish that the dependency is patched. Add a regression test at the narrowest public boundary your application uses, then run the full suite against the resolved patched Wasmtime release. Existing strategies for organizing focused regressions are discussed in Advanced Unit Testing and Debugging in Rust.
| Approach | Overflow or truncation behavior | Useful verification | Production assessment |
|---|---|---|---|
| Unchecked shift and OR | Out-of-range field bits can be lost or overlap | Ordinary examples may pass | Unsafe for variable or untrusted values |
| Mask then pack without validation | Silently discards high bits | Test expected encoded constants | Only appropriate when truncation is explicitly part of the format |
| Checked layout plus field validation | Rejects invalid widths and values | Boundary, rejection, and decode tests | Recommended for fallible input |
| Patched Wasmtime dependency plus regression tests | Incorporates upstream remediation for the advisory | cargo tree, cargo audit, profile-specific tests | Required when affected Wasmtime versions are in use |
Production pitfalls
Do not “fix” overflow by masking first. Applying value & mask makes the output fit but changes invalid input into a different value. That is correct only if the wire format explicitly defines truncation.
Keep the layout contract in one place. If encoder and decoder each calculate widths independently, a future change can make them disagree. Prefer a shared layout definition or a small, reviewed abstraction with tests for exact encoded words.
Be careful with dynamic widths. Validate widths before subtraction, shifts, or allocation calculations. For a multi-field format, calculate cumulative offsets with checked arithmetic and reject layouts whose total exceeds the container width.
Distinguish format errors from internal invariant failures. Untrusted input should usually produce a structured error rather than a panic. An impossible state in a private, validated compiler invariant may warrant an assertion, but that assertion must not be the only defense at a trust boundary.
Pinpoint the affected path. The supplied advisory record gives identifiers, severity, and patched release ranges, but not a function name or detailed root cause. Consult the upstream advisory and fix for the exact component and version assessment; do not claim that the illustrative pack_fields code is the vulnerable Wasmtime implementation.
Frequently Asked Questions (FAQ)
Which Wasmtime versions are patched for RUSTSEC-2026-0380?
The advisory record lists >=36.0.19, <37.0.0 and >=43.0.0 as patched ranges. Check the upstream advisory for the complete version assessment and use cargo tree -i wasmtime to confirm the version actually resolved by your application.
Does Rust’s checked_shl detect bits shifted out of a value?
No. checked_shl returns None when the shift amount is greater than or equal to the integer type’s width; it does not report significant value bits shifted out. Validate that the value fits the assigned field before shifting.
Will cargo test catch silent overflow in release builds?
Not reliably. Debug and release profiles can behave differently for ordinary arithmetic overflow, while truncating casts and masking can silently lose bits in either profile. Test exact encoded outputs, maximum valid values, and out-of-range inputs in both profiles.