Skip to content

Commit

Permalink
close file descriptor after reading the directory entries
Browse files Browse the repository at this point in the history
  • Loading branch information
stlankes committed Jan 18, 2024
1 parent f461c4a commit 2e7dba1
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions library/std/src/sys/pal/hermit/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,6 @@ impl FromRawFd for File {

pub fn readdir(path: &Path) -> io::Result<ReadDir> {
let fd_raw = run_path_with_cstr(path, |path| cvt(unsafe { abi::opendir(path.as_ptr()) }))?;
let fd = unsafe { FileDesc::from_raw_fd(fd_raw as i32) };
let root = path.to_path_buf();

// read all director entries
Expand All @@ -519,17 +518,22 @@ pub fn readdir(path: &Path) -> io::Result<ReadDir> {
// reserve memory to receive all directory entries
vec.resize(sz, 0);

let readlen =
unsafe { abi::getdents64(fd.as_raw_fd(), vec.as_mut_ptr() as *mut dirent64, sz) };
let readlen = unsafe { abi::getdents64(fd_raw, vec.as_mut_ptr() as *mut dirent64, sz) };
if readlen > 0 {
// shrink down to the minimal size
vec.resize(readlen.try_into().unwrap(), 0);
unsafe {
abi::close(fd_raw);
}
break;
}

// if the buffer is too small, getdents64 returns EINVAL
// otherwise, getdents64 returns an error number
if readlen != (-abi::errno::EINVAL).into() {
unsafe {
abi::close(fd_raw);
}
return Err(Error::from_raw_os_error(readlen.try_into().unwrap()));
}

Expand All @@ -539,6 +543,9 @@ pub fn readdir(path: &Path) -> io::Result<ReadDir> {
// 1 MB for directory entries should be enough
// stop here to avoid an endless loop
if sz > 0x100000 {
unsafe {
abi::close(fd_raw);
}
return Err(Error::from(ErrorKind::Uncategorized));
}
}
Expand Down

0 comments on commit 2e7dba1

Please sign in to comment.