From 1dd861b10f8651877ee6fa708c9718dc68ff2f8e Mon Sep 17 00:00:00 2001 From: Stefan Holderbach Date: Sun, 16 Mar 2025 16:33:36 +0100 Subject: [PATCH] Close find handle in `ls` windows unsafe code (#15314) While inspecting the Windows specific code of `ls` for #15311 I stumbled upon an unrelated issue in the alternate metadata gathering on Windows (added by #5703). The handle created by performing `FindFirstFileW` was never closed, leading to a potential leak. Fixed by running `FindClose` as soon as the operation succeeds. https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirstfilew#remarks --- crates/nu-command/src/filesystem/ls.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/nu-command/src/filesystem/ls.rs b/crates/nu-command/src/filesystem/ls.rs index e80d49f846..cda0fc0826 100644 --- a/crates/nu-command/src/filesystem/ls.rs +++ b/crates/nu-command/src/filesystem/ls.rs @@ -802,7 +802,7 @@ mod windows_helper { use std::os::windows::prelude::OsStrExt; use windows::Win32::Foundation::FILETIME; use windows::Win32::Storage::FileSystem::{ - FindFirstFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY, + FindClose, FindFirstFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_REPARSE_POINT, WIN32_FIND_DATAW, }; use windows::Win32::System::SystemServices::{ @@ -925,7 +925,14 @@ mod windows_helper { windows::core::PCWSTR(filename_wide.as_ptr()), &mut find_data, ) { - Ok(_) => Ok(find_data), + Ok(handle) => { + // Don't forget to close the Find handle + // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirstfilew#remarks + // Assumption: WIN32_FIND_DATAW is a pure data struct, so we can let our + // find_data outlive the handle. + let _ = FindClose(handle); + Ok(find_data) + } Err(e) => Err(ShellError::Io(IoError::new_with_additional_context( std::io::ErrorKind::Other, span,