Skip to content

Commit

Permalink
Fix integer overflow during file length calculation on 32bit targets.
Browse files Browse the repository at this point in the history
  • Loading branch information
RazrFalcon committed Aug 15, 2021
1 parent 2406f2f commit 9aa838a
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 9 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]
### Fixed
- Integer overflow during file length calculation on 32bit targets.

## [0.3.0] - 2021-06-10
### Changed
Expand Down
18 changes: 15 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,25 @@ impl MmapOptions {
self.len.map(Ok).unwrap_or_else(|| {
let desc = file.as_raw_desc();
let file_len = file_len(desc.0)?;
let len = file_len as u64 - self.offset;
if len > (usize::MAX as u64) {

if file_len < self.offset {
return Err(Error::new(
ErrorKind::InvalidData,
"memory map length overflows usize",
"memory map offset is larger than length",
));
}
let len = file_len - self.offset;

#[cfg(not(target_pointer_width = "64"))]
{
if len > (usize::MAX as u64) {
return Err(Error::new(
ErrorKind::InvalidData,
"memory map length overflows usize",
));
}
}

Ok(len as usize)
})
}
Expand Down
4 changes: 2 additions & 2 deletions src/stub.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,6 @@ impl MmapInner {
}
}

pub fn file_len(file: &File) -> io::Result<usize> {
Ok(file.metadata()?.len() as usize)
pub fn file_len(file: &File) -> io::Result<u64> {
Ok(file.metadata()?.len())
}
4 changes: 2 additions & 2 deletions src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,13 +233,13 @@ fn page_size() -> usize {
unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
}

pub fn file_len(file: RawFd) -> io::Result<usize> {
pub fn file_len(file: RawFd) -> io::Result<u64> {
unsafe {
let mut stat: libc::stat = std::mem::zeroed();

let result = libc::fstat(file, &mut stat);
if result == 0 {
Ok(stat.st_size as usize)
Ok(stat.st_size as u64)
} else {
Err(io::Error::last_os_error())
}
Expand Down
4 changes: 2 additions & 2 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,6 @@ fn allocation_granularity() -> usize {
}
}

pub fn file_len(file: &File) -> io::Result<usize> {
Ok(file.metadata()?.len() as usize)
pub fn file_len(file: &File) -> io::Result<u64> {
Ok(file.metadata()?.len())
}

0 comments on commit 9aa838a

Please sign in to comment.