Skip to content

Avoid allocating in ReadExact when insufficient data#659

Open
fbergero wants to merge 1 commit into
sharksforarms:masterfrom
fbergero:fix/read-exact-prealloc-check
Open

Avoid allocating in ReadExact when insufficient data#659
fbergero wants to merge 1 commit into
sharksforarms:masterfrom
fbergero:fix/read-exact-prealloc-check

Conversation

@fbergero

@fbergero fbergero commented May 6, 2026

Copy link
Copy Markdown

Summary

  • Adds a seek-based bounds check in DekuReader<ReadExact> for Vec<u8> to verify the underlying reader has enough bytes before allocating the output buffer
  • Uses reader.as_mut() to seek on the inner reader directly, avoiding side effects on Reader's bits_read and leftover state
  • Returns DekuError::Incomplete early when data is insufficient

Problem

The current implementation unconditionally allocates and zero-fills a buffer of exact.0 bytes:

let mut bytes = alloc::vec![0x00; exact.0];
let _ = reader.read_bytes(exact.0, &mut bytes, Order::Lsb0)?;

If exact.0 comes from untrusted input (e.g., a length-prefixed protocol), a malformed value can cause a huge allocation that gets immediately discarded when read_bytes fails. This is a DoS vector for any binary parser handling network data.

Fix

Three cheap seeks (get position, seek to end, restore) to compute remaining bytes, then early-return Incomplete if insufficient. Zero overhead for the happy path beyond those seeks.

Tests

  • Unit tests for happy path, partial reads, empty input, zero-length, and error cases
  • Allocation-counting test using alloc_counter (existing dev-dependency) that proves (0, 0, 0) allocations on the error path with ReadExact(1_000_000) on a 3-byte buffer

Test plan

  • All existing vec tests pass (32/32)
  • New unit tests pass (6/6)
  • Allocation counting test confirms zero allocations on error path

🤖 Generated with Claude Code

@fbergero

fbergero commented May 7, 2026

Copy link
Copy Markdown
Author

@sharksforarms Hey idk what's your AI policy for contributions, but feel free to drop this PR if it's against the policy

@fbergero fbergero force-pushed the fix/read-exact-prealloc-check branch from 086c9ab to b782745 Compare June 16, 2026 15:46
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

AI-Attribution: AI:0,Human:140,Tool:none
@fbergero fbergero force-pushed the fix/read-exact-prealloc-check branch from b782745 to 502538e Compare June 16, 2026 15:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants