Skip to content

fix(vm): use checked_mul and checked_add to avoid pre-check overflow#545

Open
MozirDmitriy wants to merge 1 commit intonexus-xyz:mainfrom
MozirDmitriy:fix/paged-memory-checked-size-calc
Open

fix(vm): use checked_mul and checked_add to avoid pre-check overflow#545
MozirDmitriy wants to merge 1 commit intonexus-xyz:mainfrom
MozirDmitriy:fix/paged-memory-checked-size-calc

Conversation

@MozirDmitriy
Copy link
Contributor

The previous overflow guard in vm/src/memory/paged_memory.rs::set_words() computed values.len() as u32 * WORD_SIZE as u32 prior to calling checked_add, allowing multiplication to overflow before the check and later recomputing end_address with unchecked addition. This change converts the word count to u32 with u32::try_from, then uses checked_mul to obtain the byte length and checked_add to compute end_address. The checked end_address is reused throughout the function, eliminating the unchecked recomputation. This ensures that any overflow during size or address calculations is caught and reported as MemoryError::AddressCalculationOverflow without relying on debug panics or release-mode wrapping.

Copy link
Contributor

@sjudson sjudson left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use of more checking is nice, but some minor stylistic quibbles.

}

let end_address = address + values.len() as u32 * WORD_SIZE as u32;
let words_len_u32 =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We freely swap between u32 and usize throughout the codebase, due to the fact that it is a RISC-V32 processor this is essentially always safe. So that's much cleaner and I'd recommend just doing the cast here.

let end_address = address + values.len() as u32 * WORD_SIZE as u32;
let words_len_u32 =
u32::try_from(values.len()).map_err(|_| MemoryError::AddressCalculationOverflow)?;
let bytes_len = words_len_u32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should be able to chain these cleanly using map_or_else.

SashaMalysehko pushed a commit to SashaMalysehko/nexus-zkvm that referenced this pull request Dec 9, 2025
* Replace Reg1Accessed

* Replace Reg2Accessed
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