Skip to content

Commit 46cd465

Browse files
committed
fix(sdmmc): check if max block id exceeds device capacity
1 parent b68db57 commit 46cd465

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

axdriver_block/src/sdmmc.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,18 @@ impl BlockDriverOps for SdMmcDriver {
4242

4343
fn read_block(&mut self, block_id: u64, buf: &mut [u8]) -> DevResult {
4444
let (blocks, remainder) = buf.as_chunks_mut::<{ SdMmc::BLOCK_SIZE }>();
45-
let block_id: u32 = block_id.try_into().map_err(|_| DevError::InvalidParam)?;
4645

46+
// the buf length must be a multiple of block size
4747
if !remainder.is_empty() {
4848
return Err(DevError::InvalidParam);
4949
}
5050

51-
// check that block_id + blocks.len() does not overflow u32
52-
if block_id.checked_add(blocks.len() as u32).is_none() {
51+
// check if block id exceeds device capacity
52+
if block_id.saturating_add(blocks.len() as u64) > self.0.num_blocks(){
5353
return Err(DevError::InvalidParam);
5454
}
5555

56+
let block_id: u32 = block_id.try_into().map_err(|_| DevError::InvalidParam)?;
5657
for (i, block) in blocks.iter_mut().enumerate() {
5758
self.0.read_block(block_id + i as u32, block);
5859
}
@@ -62,17 +63,18 @@ impl BlockDriverOps for SdMmcDriver {
6263

6364
fn write_block(&mut self, block_id: u64, buf: &[u8]) -> DevResult {
6465
let (blocks, remainder) = buf.as_chunks::<{ SdMmc::BLOCK_SIZE }>();
65-
let block_id: u32 = block_id.try_into().map_err(|_| DevError::InvalidParam)?;
6666

67+
// the buf length must be a multiple of block size
6768
if !remainder.is_empty() {
6869
return Err(DevError::InvalidParam);
6970
}
7071

71-
// check that block_id + blocks.len() does not overflow u32
72-
if block_id.checked_add(blocks.len() as u32).is_none() {
72+
// check if block id exceeds device capacity
73+
if block_id.saturating_add(blocks.len() as u64) > self.0.num_blocks(){
7374
return Err(DevError::InvalidParam);
7475
}
7576

77+
let block_id: u32 = block_id.try_into().map_err(|_| DevError::InvalidParam)?;
7678
for (i, block) in blocks.iter().enumerate() {
7779
self.0.write_block(block_id + i as u32, block);
7880
}

0 commit comments

Comments
 (0)