Visitar URL original
Return EBADF for negative stat file descriptors by youknowdot · Pull Request #9008 · RustPython/RustPython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/host_env/src/fileutils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ pub use windows::{StatStruct, fstat};

#[cfg(not(windows))]
pub fn fstat(fd: crate::crt_fd::Borrowed<'_>) -> std::io::Result<StatStruct> {
// Unlike a directory fd, fstat accepts no negative descriptor sentinels.
if fd.as_raw() < 0 {
return Err(std::io::Error::from_raw_os_error(libc::EBADF));
}
rustix::fs::fstat(fd).map_err(Into::into)
}

Expand Down
30 changes: 30 additions & 0 deletions tests/negative_fstat.rs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do not add python test code in rust file

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#![allow(clippy::tests_outside_test_module)]

#[cfg(unix)]
#[test]
fn stat_rejects_negative_file_descriptors() {
use rustpython::{InterpreterBuilder, InterpreterBuilderExt};

InterpreterBuilder::new()
.init_stdlib()
.interpreter()
.enter(|vm| {
let source = r#"
import errno
import os

for stat in (os.stat, os.fstat):
for fd in (-1, -5, -9, -100, -(2**31)):
try:
stat(fd)
except OSError as exc:
assert exc.errno == errno.EBADF, (stat, fd, exc)
else:
raise AssertionError((stat, fd, 'accepted a negative file descriptor'))
"#;
if let Err(err) = vm.run_simple_string(source) {
vm.print_exception(&err);
panic!("negative descriptor regression failed");
}
});
}
Loading