From d7f37f6455a08ac164efbddf381fac2b08d6c16c Mon Sep 17 00:00:00 2001 From: Reagan Bohan Date: Mon, 21 Apr 2025 08:44:43 +0000 Subject: [PATCH] Fix mmap aborting with invalid fd in debug mode --- stdlib/src/mmap.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/stdlib/src/mmap.rs b/stdlib/src/mmap.rs index bca367ae4d..9319bab64c 100644 --- a/stdlib/src/mmap.rs +++ b/stdlib/src/mmap.rs @@ -23,13 +23,15 @@ mod mmap { }; use crossbeam_utils::atomic::AtomicCell; use memmap2::{Advice, Mmap, MmapMut, MmapOptions}; + #[cfg(unix)] + use nix::sys::stat::fstat; use nix::unistd; use num_traits::Signed; use std::fs::File; - use std::io::Write; + use std::io::{self, Write}; use std::ops::{Deref, DerefMut}; #[cfg(unix)] - use std::os::unix::io::{FromRawFd, IntoRawFd, RawFd}; + use std::os::unix::io::{FromRawFd, RawFd}; fn advice_try_from_i32(vm: &VirtualMachine, i: i32) -> PyResult { Ok(match i { @@ -299,7 +301,7 @@ mod mmap { fn py_new( cls: PyTypeRef, MmapNewArgs { - fileno: mut fd, + fileno: fd, length, flags, prot, @@ -348,12 +350,10 @@ mod mmap { }; if fd != -1 { - let file = unsafe { File::from_raw_fd(fd) }; - let metadata = file.metadata().map_err(|err| err.to_pyexception(vm))?; - let file_len: libc::off_t = metadata.len().try_into().expect("file size overflow"); - // File::from_raw_fd will consume the fd, so we - // have to get it again. - fd = file.into_raw_fd(); + let metadata = fstat(fd) + .map_err(|err| io::Error::from_raw_os_error(err as i32).to_pyexception(vm))?; + let file_len = metadata.st_size; + if map_size == 0 { if file_len == 0 { return Err(vm.new_value_error("cannot mmap an empty file".to_owned()));