@@ -509,7 +509,6 @@ impl FromRawFd for File {
509509
510510pub fn readdir ( path : & Path ) -> io:: Result < ReadDir > {
511511 let fd_raw = run_path_with_cstr ( path, |path| cvt ( unsafe { abi:: opendir ( path. as_ptr ( ) ) } ) ) ?;
512- let fd = unsafe { FileDesc :: from_raw_fd ( fd_raw as i32 ) } ;
513512 let root = path. to_path_buf ( ) ;
514513
515514 // read all director entries
@@ -519,17 +518,22 @@ pub fn readdir(path: &Path) -> io::Result<ReadDir> {
519518 // reserve memory to receive all directory entries
520519 vec. resize ( sz, 0 ) ;
521520
522- let readlen =
523- unsafe { abi:: getdents64 ( fd. as_raw_fd ( ) , vec. as_mut_ptr ( ) as * mut dirent64 , sz) } ;
521+ let readlen = unsafe { abi:: getdents64 ( fd_raw, vec. as_mut_ptr ( ) as * mut dirent64 , sz) } ;
524522 if readlen > 0 {
525523 // shrink down to the minimal size
526524 vec. resize ( readlen. try_into ( ) . unwrap ( ) , 0 ) ;
525+ unsafe {
526+ abi:: close ( fd_raw) ;
527+ }
527528 break ;
528529 }
529530
530531 // if the buffer is too small, getdents64 returns EINVAL
531532 // otherwise, getdents64 returns an error number
532533 if readlen != ( -abi:: errno:: EINVAL ) . into ( ) {
534+ unsafe {
535+ abi:: close ( fd_raw) ;
536+ }
533537 return Err ( Error :: from_raw_os_error ( readlen. try_into ( ) . unwrap ( ) ) ) ;
534538 }
535539
@@ -539,6 +543,9 @@ pub fn readdir(path: &Path) -> io::Result<ReadDir> {
539543 // 1 MB for directory entries should be enough
540544 // stop here to avoid an endless loop
541545 if sz > 0x100000 {
546+ unsafe {
547+ abi:: close ( fd_raw) ;
548+ }
542549 return Err ( Error :: from ( ErrorKind :: Uncategorized ) ) ;
543550 }
544551 }
0 commit comments