sign_extend() potential shift underflow for nbytes > 8

Open Beginner friendly
#832 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
68/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Quiet
Tech stack
rust
Domain
backend

Research direction

Start at src/buf/buf_impl.rs:90 and inspect how sign_extend is called, especially the allowed nbytes range. Verify the behavior for nbytes greater than 8 and add the agreed guard or fix; done when the underflow concern is covered by tests or formal verification.

Written by the indexing model from the issue text.

Description

Hi,

I found a potential shift underflow issue through Kani formal verification.

Location: src/buf/buf_impl.rs:90

Current Code:

fn sign_extend(val: u64, nbytes: usize) -> i64 {
let shift = (8 - nbytes) * 8; // Underflow when nbytes > 8!
(val << shift) as i64 >> shift
}
Problem:

When nbytes > 8, the shift amount becomes incorrect.

Suggested Fix:

fn sign_extend(val: u64, nbytes: usize) -> i64 {
debug_assert!(nbytes >= 1 && nbytes <= 8, “nbytes must be in [1, 8]”);
let shift = (8 - nbytes) * 8;
(val << shift) as i64 >> shift
}
Could you please confirm if this is a valid concern?

Dominant language
Rust
Stars
2.3k
Forks
355
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from tokio-rs/bytes

All issues in tokio-rs/bytes

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.