From 3cd9f3f6ab7d906e23d0ddc4bb0604b09966961f Mon Sep 17 00:00:00 2001 From: Marcin Mielniczuk Date: Tue, 6 Aug 2019 19:34:10 +0200 Subject: [PATCH 1/2] Add an overflow check in truncate implementation for Unix. --- src/libstd/fs.rs | 2 ++ src/libstd/sys/unix/fs.rs | 12 +++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs index f7c32a5c20d3d..5f76875bd66c4 100644 --- a/src/libstd/fs.rs +++ b/src/libstd/fs.rs @@ -468,6 +468,8 @@ impl File { /// # Errors /// /// This function will return an error if the file is not opened for writing. + /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired + /// length would cause an overflow due to the implementation specifics. /// /// # Examples /// diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index cc1f0790d4334..48e449d9c377c 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -1,5 +1,6 @@ use crate::os::unix::prelude::*; +use crate::convert::TryInto; use crate::ffi::{CString, CStr, OsString, OsStr}; use crate::fmt; use crate::io::{self, Error, ErrorKind, SeekFrom, IoSlice, IoSliceMut}; @@ -554,9 +555,14 @@ impl File { return crate::sys::android::ftruncate64(self.0.raw(), size); #[cfg(not(target_os = "android"))] - return cvt_r(|| unsafe { - ftruncate64(self.0.raw(), size as off64_t) - }).map(|_| ()); + { + let size: off64_t = size + .try_into() + .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + cvt_r(|| unsafe { + ftruncate64(self.0.raw(), size) + }).map(|_| ()) + } } pub fn read(&self, buf: &mut [u8]) -> io::Result { From 3adbf63b119d26edf1997e974d0727791d6f4060 Mon Sep 17 00:00:00 2001 From: Marcin Mielniczuk Date: Thu, 8 Aug 2019 11:44:59 +0200 Subject: [PATCH 2/2] Move the TryInto import into the inner scope --- src/libstd/sys/unix/fs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index 48e449d9c377c..0223957e611fb 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -1,6 +1,5 @@ use crate::os::unix::prelude::*; -use crate::convert::TryInto; use crate::ffi::{CString, CStr, OsString, OsStr}; use crate::fmt; use crate::io::{self, Error, ErrorKind, SeekFrom, IoSlice, IoSliceMut}; @@ -556,6 +555,7 @@ impl File { #[cfg(not(target_os = "android"))] { + use crate::convert::TryInto; let size: off64_t = size .try_into() .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;