Skip to content

Commit 9cfea38

Browse files
Improve overflow handling in get_or_insert_blocks
When calculating num_bytes overflows, return a new BlockCacheReadTooLarge error instead of silently capping to the block size.
1 parent 49144ea commit 9cfea38

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/block_cache.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
use crate::block_index::FsBlockIndex;
1010
use crate::block_size::BlockSize;
11+
use crate::error::CorruptKind;
1112
use crate::error::Ext4Error;
1213
use crate::util::usize_from_u32;
1314
use alloc::boxed::Box;
@@ -182,13 +183,14 @@ impl BlockCache {
182183
return Ok(&*self.entries[0].data);
183184
}
184185

185-
let block_size = self.block_size.to_usize();
186-
187186
// Get the number of blocks/bytes to read.
188187
let num_blocks = self.num_blocks_to_read(block_index);
189188
let num_bytes = usize_from_u32(num_blocks)
190-
.checked_mul(block_size)
191-
.unwrap_or(block_size);
189+
.checked_mul(self.block_size.to_usize())
190+
.ok_or(CorruptKind::BlockCacheReadTooLarge {
191+
num_blocks,
192+
block_size: self.block_size,
193+
})?;
192194

193195
// Read blocks into the read buffer.
194196
f(&mut self.read_buf[..num_bytes])?;

src/error.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,12 @@ pub(crate) enum CorruptKind {
345345
/// Length in bytes of the read.
346346
read_len: usize,
347347
},
348+
349+
/// Attempting to read too much data in the block cache.
350+
BlockCacheReadTooLarge {
351+
num_blocks: u32,
352+
block_size: BlockSize,
353+
},
348354
}
349355

350356
impl Display for CorruptKind {
@@ -494,6 +500,13 @@ impl Display for CorruptKind {
494500
"invalid read of length {read_len} from block {block_index} (originally {original_block_index}) at offset {offset_within_block}"
495501
)
496502
}
503+
Self::BlockCacheReadTooLarge {
504+
num_blocks,
505+
block_size,
506+
} => write!(
507+
f,
508+
"attempted to read {num_blocks} blocks with block_size {block_size}"
509+
),
497510
}
498511
}
499512
}

0 commit comments

Comments
 (0)