Skip to content

Use wrapping arithmetic in ProbeSeq::move_next to avoid overflow#736

Open
amitmishra11 wants to merge 1 commit into
rust-lang:mainfrom
amitmishra11:fix-probe-seq-overflow
Open

Use wrapping arithmetic in ProbeSeq::move_next to avoid overflow#736
amitmishra11 wants to merge 1 commit into
rust-lang:mainfrom
amitmishra11:fix-probe-seq-overflow

Conversation

@amitmishra11

Copy link
Copy Markdown

Bug

In ProbeSeq::move_next (src/raw.rs), stride and pos are updated with plain +=:

self.stride += Group::WIDTH;
self.pos += self.stride;
self.pos &= bucket_mask;

In a debug build this panics; in a release build it produces undefined behavior (integer overflow). Although the existing debug_assert! verifies that stride <= bucket_mask before the addition, it fires before the increment, so the assert itself does not rule out overflow once Group::WIDTH is added.

This was identified via Kani formal verification and confirmed as a bug by @Amanieu in #735.

Fix

Replace the plain additions with wrapping_add, which is what the subsequent & bucket_mask mask assumes:

self.stride = self.stride.wrapping_add(Group::WIDTH);
self.pos = self.pos.wrapping_add(self.stride) & bucket_mask;

The logic is otherwise identical; wrapping_add only differs from + when overflow would occur, and the final mask ensures pos stays in range regardless.

Verification

cargo check passes cleanly. cargo test cannot run on this machine due to an absent MSVC linker, but the type-level correctness of the change is confirmed by cargo check.

Closes #735

In long probe sequences with a nearly-full table, the stride and pos
fields can overflow using plain += before being masked back. Replacing
the additions with wrapping_add makes the arithmetic well-defined under
all inputs and matches the intent of the subsequent mask (& bucket_mask).

Fixes rust-lang#735

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@clarfonthey

Copy link
Copy Markdown
Contributor

It appears that the test failures are due to some unrelated lint changes; I can work on those in a separate PR, or someone else can get to that first. Otherwise, this PR looks fine and can be merged after that is fixed.

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.

ProbeSeq::move_next() potential arithmetic overflow

2 participants