From d364c67a5e964c4488f3c570ad3f726a393cfe04 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Wed, 23 May 2018 17:20:51 +0500 Subject: [PATCH 01/20] Remove unneeded p/invokes --- .../CoreCLR/CorePsPlatform.cs | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index aa9b119125f..fb970821796 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -551,16 +551,6 @@ internal static string NonWindowsGetHostName() return Unix.NativeMethods.GetFullyQualifiedName() ?? string.Empty; } - internal static bool NonWindowsIsFile(string path) - { - return Unix.NativeMethods.IsFile(path); - } - - internal static bool NonWindowsIsDirectory(string path) - { - return Unix.NativeMethods.IsDirectory(path); - } - internal static bool NonWindowsIsSameFileSystemItem(string pathOne, string pathTwo) { return Unix.NativeMethods.IsSameFileSystemItem(pathOne, pathTwo); @@ -773,14 +763,6 @@ internal static extern int CreateHardLink([MarshalAs(UnmanagedType.LPStr)]string [return: MarshalAs(UnmanagedType.LPStr)] internal static extern string GetUserFromPid(int pid); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool IsFile([MarshalAs(UnmanagedType.LPStr)]string filePath); - - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool IsDirectory([MarshalAs(UnmanagedType.LPStr)]string filePath); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool IsSameFileSystemItem([MarshalAs(UnmanagedType.LPStr)]string filePathOne, From 01d2685e547da2f98777a42206a374949b759611 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Thu, 24 May 2018 09:31:04 +0500 Subject: [PATCH 02/20] Create NativeItemExists based on File.GetAttributes(path) --- .../engine/Utils.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 5b108a97978..f9d66ca0c0d 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -903,6 +903,26 @@ internal static bool NativeItemExists(string path) return NativeItemExists(path, out unusedIsDirectory, out unusedException); } + internal static bool NativeItemExists(string path, out bool isDirectory) + { + if (String.IsNullOrEmpty(path)) + { + isDirectory = false; + return false; + } +#if !UNIX + if (IsReservedDeviceName(path)) + { + isDirectory = false; + return false; + } +#endif + // Use 'File.GetAttributes()' to get access exceptions + FileAttributes attributes = File.GetAttributes(path); + isDirectory = attributes.HasFlag(FileAttributes.Directory); + return (int)attributes != -1; + } + // This is done through P/Invoke since File.Exists and Directory.Exists pay 13% performance degradation // through the CAS checks, and are terribly slow for network paths. internal static bool NativeItemExists(string path, out bool isDirectory, out Exception exception) From 1637ad14399fd4414d645c54de24aba27c229471 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Thu, 24 May 2018 10:13:40 +0500 Subject: [PATCH 03/20] Update NativeItemExists w/o throw --- src/System.Management.Automation/engine/Utils.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index f9d66ca0c0d..7ef9cd85b6c 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -897,10 +897,15 @@ internal static bool IsAdministrator() internal static bool NativeItemExists(string path) { - bool unusedIsDirectory; - Exception unusedException; - - return NativeItemExists(path, out unusedIsDirectory, out unusedException); + bool result = false; + try + { + result = NativeItemExists(path, out bool unused); + } + catch + { + } + return false; } internal static bool NativeItemExists(string path, out bool isDirectory) From 058ac676b6e2c2b34880e4b93ec0af729ab04596 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Wed, 23 May 2018 18:06:02 +0500 Subject: [PATCH 04/20] Replace NativeItemExists in GetPathItems --- .../namespaces/FileSystemProvider.cs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 1fccb4e07d5..83c59c8e246 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -1502,17 +1502,7 @@ private void GetPathItems( path = NormalizePath(path); - // Get the directory object - bool isDirectory; - Exception accessException; - bool exists = Utils.NativeItemExists(path, out isDirectory, out accessException); - - if (accessException != null) - { - throw accessException; - } - - if (exists) + if (Utils.NativeItemExists(path, out bool isDirectory)) { if (isDirectory) { From 286d7144ca19e9654e1ba5ad041eaee8853d95c1 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Wed, 23 May 2018 19:13:41 +0500 Subject: [PATCH 05/20] Replace NativeItemExists in RemoveDirectoryInfoItem --- .../namespaces/FileSystemProvider.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 83c59c8e246..7fccd26fab7 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2911,15 +2911,15 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool return; } - bool isDirectory; - Exception accessException; - - if (!Utils.NativeItemExists(directory.FullName, out isDirectory, out accessException)) + try { - return; + if (!Utils.NativeItemExists(directory.FullName, out bool unused)) + { + // Directory does not exist + return; + } } - - if (accessException != null) + catch (Exception accessException) { ErrorRecord errorRecord = new ErrorRecord(accessException, "RemoveFileSystemItemUnAuthorizedAccess", ErrorCategory.PermissionDenied, directory); From 4e941d6491f87cb16c891e891e0b3be53ba33b0f Mon Sep 17 00:00:00 2001 From: iSazonov Date: Wed, 23 May 2018 19:20:46 +0500 Subject: [PATCH 06/20] Replace NativeItemExists in ItemExists --- .../namespaces/FileSystemProvider.cs | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 7fccd26fab7..b6c60bdade1 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -3239,19 +3239,7 @@ private bool ItemExists(string path, out ErrorRecord error) try { - bool notUsed; - Exception accessException; - - // First see if the file exists - if (Utils.NativeItemExists(path, out notUsed, out accessException)) - { - result = true; - } - - if (accessException != null) - { - throw accessException; - } + result = Utils.NativeItemExists(path, out bool unused); FileSystemItemProviderDynamicParameters itemExistsDynamicParameters = DynamicParameters as FileSystemItemProviderDynamicParameters; From b5156810ebbc1b134e3efd810ca11f6da5ac8ff9 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Wed, 23 May 2018 20:23:36 +0500 Subject: [PATCH 07/20] Replace NativeItemExists in GetProperty --- .../namespaces/FileSystemProvider.cs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index b6c60bdade1..6e4677a0fbc 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -6041,16 +6041,8 @@ public void GetProperty(string path, Collection providerSpecificPickList try { FileSystemInfo fileSystemObject = null;// Get the directory object - bool isDirectory; - Exception accessException; - bool exists = Utils.NativeItemExists(path, out isDirectory, out accessException); - if (accessException != null) - { - throw accessException; - } - - if (exists) + if (Utils.NativeItemExists(path, out bool isDirectory)) { if (isDirectory) { From 5d85a4d8cb1aaddbfe41ee2fd530552dbc14c87d Mon Sep 17 00:00:00 2001 From: iSazonov Date: Wed, 23 May 2018 20:28:22 +0500 Subject: [PATCH 08/20] Replace NativeItemExists in SetProperty --- .../namespaces/FileSystemProvider.cs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 6e4677a0fbc..567f8da1e3f 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -6201,16 +6201,7 @@ public void SetProperty(string path, PSObject propertyToSet) // Create a PSObject with either a DirectoryInfo or FileInfo object // at its core. - bool isDirectory; - Exception accessException; - bool exists = Utils.NativeItemExists(path, out isDirectory, out accessException); - - if (accessException != null) - { - throw accessException; - } - - if (exists) + if (Utils.NativeItemExists(path, out bool isDirectory)) { if (isDirectory) { From 23e44ac8e1d42e1094f7c9a53b88feebdeeae813 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Thu, 24 May 2018 10:37:42 +0500 Subject: [PATCH 09/20] Replace CheckItemExists with NativeItemExists --- .../namespaces/FileSystemProvider.cs | 28 +++---------------- 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 567f8da1e3f..abf03501009 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2164,7 +2164,7 @@ protected override void NewItem( // non-existing targets on either Windows or Linux. try { - exists = CheckItemExists(strTargetPath, out isDirectory); + exists = Utils.NativeItemExists(strTargetPath, out isDirectory); if (itemType == ItemType.SymbolicLink) exists = true; // pretend the target exists if we're making a symbolic link } @@ -2197,7 +2197,7 @@ protected override void NewItem( try { - symLinkExists = CheckItemExists(path, out isSymLinkDirectory); + symLinkExists = Utils.NativeItemExists(path, out isSymLinkDirectory); } catch (Exception e) { @@ -2326,7 +2326,7 @@ protected override void NewItem( try { - exists = CheckItemExists(strTargetPath, out isDirectory); + exists = Utils.NativeItemExists(strTargetPath, out isDirectory); } catch (Exception e) { @@ -2354,7 +2354,7 @@ protected override void NewItem( try { - pathExists = CheckItemExists(path, out isPathDirectory); + pathExists = Utils.NativeItemExists(path, out isPathDirectory); } catch (Exception e) { @@ -2474,26 +2474,6 @@ private static bool WinCreateJunction(string path, string strTargetPath) return junctionCreated; } - /// - /// Checks if the item exists and throws exception on access. - /// - /// - /// - /// - private static bool CheckItemExists(string strTargetPath, out bool isDirectory) - { - Exception accessException; - - bool exists = Utils.NativeItemExists(strTargetPath, out isDirectory, out accessException); - - if (accessException != null) - { - throw accessException; - } - - return exists; - } - private enum ItemType { Unknown, From c6573fb778c6b7bbd4189ab3fa6253d14d727a91 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Thu, 24 May 2018 10:51:28 +0500 Subject: [PATCH 10/20] Update NativeFileExists and NativeDirectoryExists --- .../engine/Utils.cs | 24 +++---------------- 1 file changed, 3 insertions(+), 21 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 7ef9cd85b6c..3e0007983cf 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -505,7 +505,7 @@ internal static bool IsValidPSEditionValue(string editionValue) T policy = null; #if !UNIX // On Windows, group policy settings from registry take precedence. - // If the requested policy is not defined in registry, we query the configuration file. + // If the requested policy is not defined in registry, we query the configuration file. policy = GetPolicySettingFromGPO(preferenceOrder); if (policy != null) { return policy; } #endif @@ -999,34 +999,16 @@ internal static bool NativeItemExists(string path, out bool isDirectory, out Exc #endif } - // This is done through P/Invoke since we pay 13% performance degradation - // through the CAS checks required by File.Exists and Directory.Exists internal static bool NativeFileExists(string path) { - bool isDirectory; - Exception ioException; - - bool itemExists = NativeItemExists(path, out isDirectory, out ioException); - if (ioException != null) - { - throw ioException; - } + bool itemExists = NativeItemExists(path, out bool isDirectory); return (itemExists && (!isDirectory)); } - // This is done through P/Invoke since we pay 13% performance degradation - // through the CAS checks required by File.Exists and Directory.Exists internal static bool NativeDirectoryExists(string path) { - bool isDirectory; - Exception ioException; - - bool itemExists = NativeItemExists(path, out isDirectory, out ioException); - if (ioException != null) - { - throw ioException; - } + bool itemExists = NativeItemExists(path, out bool isDirectory); return (itemExists && isDirectory); } From fdb166721af9fcc8359060082ecf7d285b87cb31 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Thu, 24 May 2018 10:53:35 +0500 Subject: [PATCH 11/20] Remove old NativeItemExists --- .../engine/Utils.cs | 71 ------------------- 1 file changed, 71 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 3e0007983cf..c5561075437 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -928,77 +928,6 @@ internal static bool NativeItemExists(string path, out bool isDirectory) return (int)attributes != -1; } - // This is done through P/Invoke since File.Exists and Directory.Exists pay 13% performance degradation - // through the CAS checks, and are terribly slow for network paths. - internal static bool NativeItemExists(string path, out bool isDirectory, out Exception exception) - { - exception = null; - - if (String.IsNullOrEmpty(path)) - { - isDirectory = false; - return false; - } -#if UNIX - isDirectory = Platform.NonWindowsIsDirectory(path); - return Platform.NonWindowsIsFile(path); -#else - - if (IsReservedDeviceName(path)) - { - isDirectory = false; - return false; - } - - int result = NativeMethods.GetFileAttributes(path); - if (result == -1) - { - int errorCode = Marshal.GetLastWin32Error(); - if (errorCode == 5) - { - // Handle "Access denied" specifically. - Win32Exception win32Exception = new Win32Exception(errorCode); - exception = new UnauthorizedAccessException(win32Exception.Message, win32Exception); - } - else if (errorCode == 32) - { - // Errorcode 32 is 'ERROR_SHARING_VIOLATION' i.e. - // The process cannot access the file because it is being used by another process. - // GetFileAttributes may return INVALID_FILE_ATTRIBUTES for a system file or directory because of this error. - // GetFileAttributes function tries to open the file with FILE_READ_ATTRIBUTES access right but it fails if the - // sharing flag for the file is set to 0x00000000.This flag prevents it from opening a file for delete, read, or - // write access. For example: C:\pagefile.sys is always opened by OS with sharing flag 0x00000000. - // But FindFirstFile is still able to get attributes as this api retrieves the required information using a find - // handle generated with FILE_LIST_DIRECTORY access. - // Fall back to FindFirstFile to check if the file actually exists. - IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); - NativeMethods.WIN32_FIND_DATA findData; - IntPtr findHandle = NativeMethods.FindFirstFile(path, out findData); - if (findHandle != INVALID_HANDLE_VALUE) - { - isDirectory = (findData.dwFileAttributes & NativeMethods.FileAttributes.Directory) != 0; - NativeMethods.FindClose(findHandle); - return true; - } - } - else if (errorCode == 53) - { - // ERROR_BAD_NETPATH - The network path was not found. - Win32Exception win32Exception = new Win32Exception(errorCode); - exception = new IOException(win32Exception.Message, win32Exception); - } - - isDirectory = false; - return false; - } - - isDirectory = (result & ((int)NativeMethods.FileAttributes.Directory)) == - ((int)NativeMethods.FileAttributes.Directory); - - return true; -#endif - } - internal static bool NativeFileExists(string path) { bool itemExists = NativeItemExists(path, out bool isDirectory); From cf419bf5216c4e84f647fc62ec51818776e66403 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Thu, 24 May 2018 11:09:56 +0500 Subject: [PATCH 12/20] [Feature] Remove 'Native' from method names NativeItemExists -> ItemExists NativeFileExists -> FileExists NativeDirectoryExists -> DirectoryExists --- .../security/Utils.cs | 2 +- .../engine/CommandSearcher.cs | 2 +- .../engine/Modules/AnalysisCache.cs | 6 ++-- .../engine/Modules/ModuleCmdletBase.cs | 16 +++++----- .../engine/Modules/ModuleUtils.cs | 4 +-- .../engine/SessionStateDriveAPIs.cs | 4 +-- .../engine/Utils.cs | 14 ++++---- .../help/UpdatableHelpSystem.cs | 4 +-- .../namespaces/FileSystemProvider.cs | 32 +++++++++---------- .../namespaces/LocationGlobber.cs | 4 +-- .../utils/ClrFacade.cs | 4 +-- 11 files changed, 46 insertions(+), 46 deletions(-) diff --git a/src/Microsoft.PowerShell.Security/security/Utils.cs b/src/Microsoft.PowerShell.Security/security/Utils.cs index 2f865bbb739..7a63f798d44 100644 --- a/src/Microsoft.PowerShell.Security/security/Utils.cs +++ b/src/Microsoft.PowerShell.Security/security/Utils.cs @@ -204,7 +204,7 @@ internal static string GetFilePathOfExistingFile(PSCmdlet cmdlet, string path) { string resolvedProviderPath = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); - if (Utils.NativeFileExists(resolvedProviderPath)) + if (Utils.FileExists(resolvedProviderPath)) { return resolvedProviderPath; } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 570d4bb6cd9..182804a853d 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -578,7 +578,7 @@ private CommandInfo GetInfoFromPath(string path) do // false loop { - if (!Utils.NativeFileExists(path)) + if (!Utils.FileExists(path)) { CommandDiscovery.discoveryTracer.TraceError("The path does not exist: {0}", path); break; diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index f2f82586fef..48e9fb15774 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -650,7 +650,7 @@ private void Cleanup() var keys = Entries.Keys; foreach (var key in keys) { - if (!Utils.NativeFileExists(key)) + if (!Utils.FileExists(key)) { ModuleCacheEntry unused; removedSomething |= Entries.TryRemove(key, out unused); @@ -690,7 +690,7 @@ private void Serialize(string filename) try { - if (Utils.NativeFileExists(filename)) + if (Utils.FileExists(filename)) { var fileLastWriteTime = new FileInfo(filename).LastWriteTime; if (fileLastWriteTime > this.LastReadTime) @@ -987,7 +987,7 @@ internal static AnalysisCacheData Get() { try { - if (Utils.NativeFileExists(s_cacheStoreLocation)) + if (Utils.FileExists(s_cacheStoreLocation)) { return Deserialize(s_cacheStoreLocation); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 8c64918fd86..f77c957af67 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -297,7 +297,7 @@ internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumer { qualifiedPath = Path.Combine(qualifiedPath, fileBaseName); } - else if (Utils.NativeDirectoryExists(qualifiedPath)) + else if (Utils.DirectoryExists(qualifiedPath)) { // if it points to a directory, add the basename back onto the path... qualifiedPath = Path.Combine(qualifiedPath, Path.GetFileName(fileBaseName)); @@ -924,7 +924,7 @@ private IEnumerable GetModuleForRootedPaths(string[] modulePaths, foreach (string resolvedModulePath in modulePathCollection) { string moduleName = Path.GetFileName(resolvedModulePath); - bool isDirectory = Utils.NativeDirectoryExists(resolvedModulePath); + bool isDirectory = Utils.DirectoryExists(resolvedModulePath); // If the given path is a valid module file, we will load the specific file if (!isDirectory && ModuleIntrinsics.IsPowerShellModuleExtension(Path.GetExtension(moduleName))) @@ -1624,7 +1624,7 @@ internal PSModuleInfo LoadModuleManifest( return loadedModule; } // remove the module if force is specified (and if module is already loaded) - else if (Utils.NativeFileExists(rootedPath)) + else if (Utils.FileExists(rootedPath)) { RemoveModule(loadedModule); } @@ -4111,7 +4111,7 @@ private ExternalScriptInfo FindLocalizedModuleManifest(string path) String filePath = stringBuilder.ToString(); - if (Utils.NativeFileExists(filePath)) + if (Utils.FileExists(filePath)) { localizedFile = filePath; break; @@ -4278,7 +4278,7 @@ private bool GetListOfFilesFromData( // which we can't really do b/c the file doesn't exist. fixedFileName = psHome + "\\" + Path.GetFileName(s); } - else if (verifyFilesExist && !Utils.NativeFileExists(fixedFileName)) + else if (verifyFilesExist && !Utils.FileExists(fixedFileName)) { string message = StringUtil.Format(SessionStateStrings.PathNotFound, fixedFileName); throw new FileNotFoundException(message, fixedFileName); @@ -5002,7 +5002,7 @@ internal PSModuleInfo IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(stri else // reimport the module + return alreadyLoadedModule (alreadyLoadedModule = no need to proceed with regular import) { // If the module has already been loaded, then while loading it the second time, we should load it with the DefaultCommandPrefix specified in the module manifest. (If there is no Prefix from command line) - if (string.IsNullOrEmpty(prefix) && Utils.NativeFileExists(alreadyLoadedModule.Path)) + if (string.IsNullOrEmpty(prefix) && Utils.FileExists(alreadyLoadedModule.Path)) { string defaultPrefix = GetDefaultPrefix(alreadyLoadedModule); if (!string.IsNullOrEmpty(defaultPrefix)) @@ -5178,7 +5178,7 @@ internal PSModuleInfo LoadUsingExtensions(PSModuleInfo parentModule, found = true; return module; } - else if (Utils.NativeFileExists(fileName)) + else if (Utils.FileExists(fileName)) { moduleFileFound = true; // Win8: 325243 - Added the version check so that we do not unload modules with the same name but different version @@ -5328,7 +5328,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str { Dbg.Assert(fileName != null, "Filename argument to LoadModule() shouldn't be null"); - if (!Utils.NativeFileExists(fileName)) + if (!Utils.FileExists(fileName)) { found = false; moduleFileFound = false; diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 8556c742676..a244d9f0e87 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -175,7 +175,7 @@ internal static List GetModuleVersionsFromAbsolutePath(string directory) { string moduleFile = Path.Combine(directory, fileName) + ext; - if (!Utils.NativeFileExists(moduleFile)) + if (!Utils.FileExists(moduleFile)) { continue; } @@ -233,7 +233,7 @@ internal static IEnumerable GetDefaultAvailableModuleFiles(string topDir foreach (string ext in ModuleIntrinsics.PSModuleExtensions) { string moduleFile = Path.Combine(directoryToCheck, proposedModuleName) + ext; - if (!Utils.NativeFileExists(moduleFile)) + if (!Utils.FileExists(moduleFile)) { continue; } diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index 6506db4e6be..5d010b1942b 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -965,9 +965,9 @@ private bool IsAStaleVhdMountedDrive(PSDriveInfo drive) { try { - // Checking for the presence of mounted drive locally using Utils.NativeDirectoryExists API as + // Checking for the presence of mounted drive locally using Utils.DirectoryExists API as // the calls to this API is faster than normal Directory.Exist API. - bool validDrive = Utils.NativeDirectoryExists(drive.Root); + bool validDrive = Utils.DirectoryExists(drive.Root); if (!validDrive) { result = true; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index c5561075437..8989ec31191 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -895,12 +895,12 @@ internal static bool IsAdministrator() #endif } - internal static bool NativeItemExists(string path) + internal static bool ItemExists(string path) { bool result = false; try { - result = NativeItemExists(path, out bool unused); + result = ItemExists(path, out bool unused); } catch { @@ -908,7 +908,7 @@ internal static bool NativeItemExists(string path) return false; } - internal static bool NativeItemExists(string path, out bool isDirectory) + internal static bool ItemExists(string path, out bool isDirectory) { if (String.IsNullOrEmpty(path)) { @@ -928,16 +928,16 @@ internal static bool NativeItemExists(string path, out bool isDirectory) return (int)attributes != -1; } - internal static bool NativeFileExists(string path) + internal static bool FileExists(string path) { - bool itemExists = NativeItemExists(path, out bool isDirectory); + bool itemExists = ItemExists(path, out bool isDirectory); return (itemExists && (!isDirectory)); } - internal static bool NativeDirectoryExists(string path) + internal static bool DirectoryExists(string path) { - bool itemExists = NativeItemExists(path, out bool isDirectory); + bool itemExists = ItemExists(path, out bool isDirectory); return (itemExists && isDirectory); } diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 8e499020294..0c8ca24affa 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -1636,7 +1636,7 @@ internal static string GetFilePath(string path) string fileName = item.Name; // Prerequisite: The directory in the given path must exist and it is case sensitive. - if (Utils.NativeDirectoryExists(directoryPath)) + if (Utils.DirectoryExists(directoryPath)) { // Get the list of files in the directory. string[] fileList = Directory.GetFiles(directoryPath); @@ -1649,7 +1649,7 @@ internal static string GetFilePath(string path) } } #else - if (Utils.NativeFileExists(path)) + if (Utils.FileExists(path)) { return path; } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index abf03501009..55c0843f328 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -114,12 +114,12 @@ private static FileSystemInfo GetFileSystemInfo(string path, ref bool isContaine { isContainer = false; - if (Utils.NativeFileExists(path)) + if (Utils.FileExists(path)) { return new FileInfo(path); } - if (Utils.NativeDirectoryExists(path)) + if (Utils.DirectoryExists(path)) { isContainer = true; return new DirectoryInfo(path); @@ -447,7 +447,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) // Since the drive is fixed, ensure the root is valid. try { - validDrive = Utils.NativeDirectoryExists(drive.Root); + validDrive = Utils.DirectoryExists(drive.Root); } catch (IOException) { @@ -1502,7 +1502,7 @@ private void GetPathItems( path = NormalizePath(path); - if (Utils.NativeItemExists(path, out bool isDirectory)) + if (Utils.ItemExists(path, out bool isDirectory)) { if (isDirectory) { @@ -2164,7 +2164,7 @@ protected override void NewItem( // non-existing targets on either Windows or Linux. try { - exists = Utils.NativeItemExists(strTargetPath, out isDirectory); + exists = Utils.ItemExists(strTargetPath, out isDirectory); if (itemType == ItemType.SymbolicLink) exists = true; // pretend the target exists if we're making a symbolic link } @@ -2197,7 +2197,7 @@ protected override void NewItem( try { - symLinkExists = Utils.NativeItemExists(path, out isSymLinkDirectory); + symLinkExists = Utils.ItemExists(path, out isSymLinkDirectory); } catch (Exception e) { @@ -2326,7 +2326,7 @@ protected override void NewItem( try { - exists = Utils.NativeItemExists(strTargetPath, out isDirectory); + exists = Utils.ItemExists(strTargetPath, out isDirectory); } catch (Exception e) { @@ -2354,7 +2354,7 @@ protected override void NewItem( try { - pathExists = Utils.NativeItemExists(path, out isPathDirectory); + pathExists = Utils.ItemExists(path, out isPathDirectory); } catch (Exception e) { @@ -2893,7 +2893,7 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool try { - if (!Utils.NativeItemExists(directory.FullName, out bool unused)) + if (!Utils.ItemExists(directory.FullName, out bool unused)) { // Directory does not exist return; @@ -3219,7 +3219,7 @@ private bool ItemExists(string path, out ErrorRecord error) try { - result = Utils.NativeItemExists(path, out bool unused); + result = Utils.ItemExists(path, out bool unused); FileSystemItemProviderDynamicParameters itemExistsDynamicParameters = DynamicParameters as FileSystemItemProviderDynamicParameters; @@ -3524,7 +3524,7 @@ private void CopyItemFromRemoteSession(string path, string destinationPath, bool if (op["Items"] != null) { - bool destinationPathIsFile = Utils.NativeFileExists(destinationPath); + bool destinationPathIsFile = Utils.FileExists(destinationPath); PSObject obj = (PSObject)op["Items"]; ArrayList itemsList = (ArrayList)obj.BaseObject; @@ -3898,7 +3898,7 @@ private void CopyDirectoryFromRemoteSession( CreateDirectory(destination, false); // If failed to create directory - if (!Utils.NativeDirectoryExists(destination)) + if (!Utils.DirectoryExists(destination)) { return; } @@ -4971,7 +4971,7 @@ protected override string NormalizeRelativePath( // may contain additional globbing patterns such as '[ab]' // which Directory.EnumerateFiles() processes, giving undesireable // results in this context. - if (!Utils.NativeItemExists(result)) + if (!Utils.ItemExists(result)) { String error = StringUtil.Format(FileSystemProviderStrings.ItemDoesNotExist, path); Exception e = new IOException(error); @@ -5605,7 +5605,7 @@ protected override bool IsItemContainer(string path) path = NormalizePath(path); - return Utils.NativeDirectoryExists(path); + return Utils.DirectoryExists(path); } #region MoveItem @@ -6022,7 +6022,7 @@ public void GetProperty(string path, Collection providerSpecificPickList { FileSystemInfo fileSystemObject = null;// Get the directory object - if (Utils.NativeItemExists(path, out bool isDirectory)) + if (Utils.ItemExists(path, out bool isDirectory)) { if (isDirectory) { @@ -6181,7 +6181,7 @@ public void SetProperty(string path, PSObject propertyToSet) // Create a PSObject with either a DirectoryInfo or FileInfo object // at its core. - if (Utils.NativeItemExists(path, out bool isDirectory)) + if (Utils.ItemExists(path, out bool isDirectory)) { if (isDirectory) { diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index daff55a468c..d58daad29f6 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -504,7 +504,7 @@ private Collection ResolveDriveQualifiedPath( // if the directory exists, just return it try { - if (Utils.NativeDirectoryExists(userPath)) + if (Utils.DirectoryExists(userPath)) { result.Add(new PathInfo(drive, provider, userPath, _sessionState)); return result; @@ -2136,7 +2136,7 @@ internal string GetDriveRootRelativePathFromPSPath( providerInstance, context); } - + return relativePath; } catch (PSNotSupportedException) diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index cb24f0a37a1..03e05527904 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -137,10 +137,10 @@ private static void EncodingRegisterProvider() internal static SecurityZone GetFileSecurityZone(string filePath) { Diagnostics.Assert(Path.IsPathRooted(filePath), "Caller makes sure the path is rooted."); - Diagnostics.Assert(Utils.NativeFileExists(filePath), "Caller makes sure the file exists."); + Diagnostics.Assert(Utils.FileExists(filePath), "Caller makes sure the file exists."); string sysRoot = System.Environment.GetEnvironmentVariable("SystemRoot"); string urlmonPath = Path.Combine(sysRoot, @"System32\urlmon.dll"); - if (Utils.NativeFileExists(urlmonPath)) + if (Utils.FileExists(urlmonPath)) { return MapSecurityZoneWithUrlmon(filePath); } From 67c5d3370560e08c1765af165dcc6d13f689d570 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Wed, 30 May 2018 10:35:57 +0500 Subject: [PATCH 13/20] Fix return in ItemExists --- src/System.Management.Automation/engine/Utils.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 8989ec31191..d94095594e7 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -900,12 +900,13 @@ internal static bool ItemExists(string path) bool result = false; try { - result = ItemExists(path, out bool unused); + result = ItemExists(path, out bool unused); } catch { } - return false; + + return result; } internal static bool ItemExists(string path, out bool isDirectory) From c37761af6795a1fa474989bdb6526623ee66d014 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Tue, 5 Jun 2018 13:07:16 +0500 Subject: [PATCH 14/20] Fix module loading No need in throw here if file not found. (Previously we could throw in rare cases.) --- .../engine/Modules/ModuleCmdletBase.cs | 2 +- src/System.Management.Automation/engine/Modules/ModuleUtils.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index f77c957af67..c4a2670d0ca 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -4111,7 +4111,7 @@ private ExternalScriptInfo FindLocalizedModuleManifest(string path) String filePath = stringBuilder.ToString(); - if (Utils.FileExists(filePath)) + if (File.Exists(filePath)) { localizedFile = filePath; break; diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index a244d9f0e87..ac76e426ea2 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -233,7 +233,7 @@ internal static IEnumerable GetDefaultAvailableModuleFiles(string topDir foreach (string ext in ModuleIntrinsics.PSModuleExtensions) { string moduleFile = Path.Combine(directoryToCheck, proposedModuleName) + ext; - if (!Utils.FileExists(moduleFile)) + if (!File.Exists(moduleFile)) { continue; } From 0f25099387913dfff70b31dc30bd392595c94230 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Tue, 5 Jun 2018 15:37:42 +0500 Subject: [PATCH 15/20] Recover ItemExists() behavior for File not found exception --- .../engine/Utils.cs | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index d94095594e7..cc39c389e8a 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -911,22 +911,33 @@ internal static bool ItemExists(string path) internal static bool ItemExists(string path, out bool isDirectory) { + isDirectory = false; + if (String.IsNullOrEmpty(path)) { - isDirectory = false; return false; } #if !UNIX if (IsReservedDeviceName(path)) { - isDirectory = false; return false; } #endif - // Use 'File.GetAttributes()' to get access exceptions - FileAttributes attributes = File.GetAttributes(path); - isDirectory = attributes.HasFlag(FileAttributes.Directory); - return (int)attributes != -1; + try + { + // Use 'File.GetAttributes()' because we want to get access exceptions. + // TODO: we should review the tricky logic + // (historically we throw 'UnauthorizedAccessException' here) and migrate + // to standard methods 'File.Exist()' and 'Directory.Exists()' where possible. + FileAttributes attributes = File.GetAttributes(path); + isDirectory = attributes.HasFlag(FileAttributes.Directory); + + return (int)attributes != -1; + } + catch (IOException) + { + return false; + } } internal static bool FileExists(string path) From 757d545ea0bc7f2cced4673aa1684a18df097e45 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Thu, 7 Jun 2018 10:34:59 +0500 Subject: [PATCH 16/20] Use "discard" variable --- src/System.Management.Automation/engine/Utils.cs | 5 ++--- .../namespaces/FileSystemProvider.cs | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index cc39c389e8a..a823694ef9f 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -897,16 +897,15 @@ internal static bool IsAdministrator() internal static bool ItemExists(string path) { - bool result = false; try { - result = ItemExists(path, out bool unused); + return ItemExists(path, out bool _); } catch { } - return result; + return false; } internal static bool ItemExists(string path, out bool isDirectory) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 55c0843f328..85f4504486a 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2893,7 +2893,7 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool try { - if (!Utils.ItemExists(directory.FullName, out bool unused)) + if (!Utils.ItemExists(directory.FullName, out bool _)) { // Directory does not exist return; @@ -3219,7 +3219,7 @@ private bool ItemExists(string path, out ErrorRecord error) try { - result = Utils.ItemExists(path, out bool unused); + result = Utils.ItemExists(path, out bool _); FileSystemItemProviderDynamicParameters itemExistsDynamicParameters = DynamicParameters as FileSystemItemProviderDynamicParameters; From db25895ef801dbb64b49c891322624fa9bf49f30 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Thu, 7 Jun 2018 10:48:49 +0500 Subject: [PATCH 17/20] Use File.Exists in GetFileSecurityZone --- src/System.Management.Automation/utils/ClrFacade.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index 03e05527904..a6b887c92bc 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -137,10 +137,10 @@ private static void EncodingRegisterProvider() internal static SecurityZone GetFileSecurityZone(string filePath) { Diagnostics.Assert(Path.IsPathRooted(filePath), "Caller makes sure the path is rooted."); - Diagnostics.Assert(Utils.FileExists(filePath), "Caller makes sure the file exists."); + Diagnostics.Assert(File.Exists(filePath), "Caller makes sure the file exists."); string sysRoot = System.Environment.GetEnvironmentVariable("SystemRoot"); string urlmonPath = Path.Combine(sysRoot, @"System32\urlmon.dll"); - if (Utils.FileExists(urlmonPath)) + if (File.Exists(urlmonPath)) { return MapSecurityZoneWithUrlmon(filePath); } From 2c0fa8ffc491eca14630293ff79d44e2fb413ac1 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Sat, 9 Jun 2018 13:58:44 +0500 Subject: [PATCH 18/20] Remove unneeded #if !UNIX --- src/System.Management.Automation/engine/Utils.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index a823694ef9f..af2b9d8aefe 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -916,12 +916,12 @@ internal static bool ItemExists(string path, out bool isDirectory) { return false; } -#if !UNIX + if (IsReservedDeviceName(path)) { return false; } -#endif + try { // Use 'File.GetAttributes()' because we want to get access exceptions. From 90989641e67cde05555c0182f6dd0a577b44c503 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Sat, 9 Jun 2018 14:10:01 +0500 Subject: [PATCH 19/20] Revert "Use File.Exists in GetFileSecurityZone" This reverts commit db25895ef801dbb64b49c891322624fa9bf49f30. --- src/System.Management.Automation/utils/ClrFacade.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index a6b887c92bc..03e05527904 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -137,10 +137,10 @@ private static void EncodingRegisterProvider() internal static SecurityZone GetFileSecurityZone(string filePath) { Diagnostics.Assert(Path.IsPathRooted(filePath), "Caller makes sure the path is rooted."); - Diagnostics.Assert(File.Exists(filePath), "Caller makes sure the file exists."); + Diagnostics.Assert(Utils.FileExists(filePath), "Caller makes sure the file exists."); string sysRoot = System.Environment.GetEnvironmentVariable("SystemRoot"); string urlmonPath = Path.Combine(sysRoot, @"System32\urlmon.dll"); - if (File.Exists(urlmonPath)) + if (Utils.FileExists(urlmonPath)) { return MapSecurityZoneWithUrlmon(filePath); } From 3963c460ee3e74524edd80485147c1dac7917fd3 Mon Sep 17 00:00:00 2001 From: iSazonov Date: Sat, 9 Jun 2018 14:13:00 +0500 Subject: [PATCH 20/20] Remove unneeded comment --- src/System.Management.Automation/engine/Utils.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index af2b9d8aefe..bd81955ba2f 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -925,9 +925,6 @@ internal static bool ItemExists(string path, out bool isDirectory) try { // Use 'File.GetAttributes()' because we want to get access exceptions. - // TODO: we should review the tricky logic - // (historically we throw 'UnauthorizedAccessException' here) and migrate - // to standard methods 'File.Exist()' and 'Directory.Exists()' where possible. FileAttributes attributes = File.GetAttributes(path); isDirectory = attributes.HasFlag(FileAttributes.Directory);