From edd0157069b09e3fceb8036cabbdba96972cb2f7 Mon Sep 17 00:00:00 2001 From: Christian Poveda Date: Wed, 13 Nov 2019 11:57:20 -0500 Subject: [PATCH] Cap `count` twice --- src/shims/fs.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/shims/fs.rs b/src/shims/fs.rs index 5e84cdee5cc..9a819cd9db4 100644 --- a/src/shims/fs.rs +++ b/src/shims/fs.rs @@ -168,10 +168,13 @@ fn read( let ptr_size = this.pointer_size().bits(); + // We cap the number of read bytes to the largest value that we are able to fit in both the + // host's and target's `isize`. let count = this .read_scalar(count_op)? .to_machine_usize(&*this.tcx)? - .min(1 << (ptr_size - 1)); + .min(1 << (ptr_size - 1)) + .min(isize::max_value() as u64); // Reading zero bytes should not change `buf`. if count == 0 { return Ok(0); @@ -180,6 +183,8 @@ fn read( let buf = this.read_scalar(buf_op)?.not_undef()?; if let Some(handle) = this.machine.file_handler.handles.get_mut(&fd) { + // This can never fail because `count` was capped to be smaller than + // `isize::max_value()`. let count = isize::try_from(count).unwrap(); // We want to read at most `count` bytes. We are sure that `count` is not negative // because it was a target's `usize`. Also we are sure that its smaller than @@ -188,6 +193,8 @@ fn read( let result = handle .file .read(&mut bytes) + // `File::read` never returns a value larger than `i64::max_value()`, so this + // unwrap cannot fail. .map(|c| i64::try_from(c).unwrap()); match result { @@ -218,10 +225,13 @@ fn write( let ptr_size = this.pointer_size().bits(); + // We cap the number of read bytes to the largest value that we are able to fit in both the + // host's and target's `isize`. let count = this .read_scalar(count_op)? .to_machine_usize(&*this.tcx)? - .min(1 << (ptr_size - 1)); + .min(1 << (ptr_size - 1)) + .min(isize::max_value() as u64); // Writing zero bytes should not change `buf`. if count == 0 { return Ok(0); -- 2.44.0