Skip to content

Commit 06ef77b

Browse files
committed
Check for usize to i64 overflows
1 parent 122549f commit 06ef77b

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

src/shims/fs.rs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -176,12 +176,18 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
176176
if let Some(handle) = this.machine.file_handler.handles.get_mut(&fd) {
177177
// We want to read at most `count` bytes
178178
let mut bytes = vec![0; count as usize];
179-
let result = handle.file.read(&mut bytes).map(|c| c as i64);
180-
// If reading to `bytes` did not fail, we write those bytes to the buffer.
181-
if result.is_ok() {
182-
this.memory.write_bytes(buf, bytes)?;
179+
let result = handle.file.read(&mut bytes);
180+
181+
if let Ok(c) = result {
182+
// Check that we read less than `i64::MAX` bytes.
183+
if c > (i64::max_value() as usize) {
184+
throw_unsup_format!("Number of read bytes {} is larger than the maximum value", c);
185+
}
186+
// If reading to `bytes` did not fail, we write those bytes to the buffer.
187+
this.memory.write_bytes(buf, bytes)?
183188
}
184-
this.try_unwrap_io_result(result)
189+
190+
this.try_unwrap_io_result(result.map(|c| c as i64))
185191
} else {
186192
this.handle_not_found()
187193
}
@@ -207,8 +213,16 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
207213

208214
if let Some(handle) = this.machine.file_handler.handles.get_mut(&fd) {
209215
let bytes = this.memory.read_bytes(buf, Size::from_bytes(count))?;
210-
let result = handle.file.write(&bytes).map(|c| c as i64);
211-
this.try_unwrap_io_result(result)
216+
let result = handle.file.write(&bytes);
217+
218+
if let Ok(c) = result {
219+
// Check that we wrote less than `i64::MAX` bytes.
220+
if c > (i64::max_value() as usize) {
221+
throw_unsup_format!("Number of written bytes {} is larger than the maximum value", c);
222+
}
223+
}
224+
225+
this.try_unwrap_io_result(result.map(|c| c as i64))
212226
} else {
213227
this.handle_not_found()
214228
}

0 commit comments

Comments
 (0)