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/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, 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..c4a2670d0ca 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 (File.Exists(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..ac76e426ea2 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 (!File.Exists(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 5b108a97978..bd81955ba2f 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 @@ -895,113 +895,57 @@ internal static bool IsAdministrator() #endif } - internal static bool NativeItemExists(string path) + internal static bool ItemExists(string path) { - bool unusedIsDirectory; - Exception unusedException; + try + { + return ItemExists(path, out bool _); + } + catch + { + } - return NativeItemExists(path, out unusedIsDirectory, out unusedException); + return false; } - // 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) + internal static bool ItemExists(string path, out bool isDirectory) { - exception = null; + isDirectory = false; 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) + try { - 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); - } + // Use 'File.GetAttributes()' because we want to get access exceptions. + FileAttributes attributes = File.GetAttributes(path); + isDirectory = attributes.HasFlag(FileAttributes.Directory); - isDirectory = false; + return (int)attributes != -1; + } + catch (IOException) + { return false; } - - isDirectory = (result & ((int)NativeMethods.FileAttributes.Directory)) == - ((int)NativeMethods.FileAttributes.Directory); - - return true; -#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) + internal static bool FileExists(string path) { - bool isDirectory; - Exception ioException; - - bool itemExists = NativeItemExists(path, out isDirectory, out ioException); - if (ioException != null) - { - throw ioException; - } + bool itemExists = ItemExists(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) + internal static bool DirectoryExists(string path) { - bool isDirectory; - Exception ioException; - - bool itemExists = NativeItemExists(path, out isDirectory, out ioException); - if (ioException != null) - { - throw ioException; - } + 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 1fccb4e07d5..85f4504486a 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,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.ItemExists(path, out bool isDirectory)) { if (isDirectory) { @@ -2174,7 +2164,7 @@ protected override void NewItem( // non-existing targets on either Windows or Linux. try { - exists = CheckItemExists(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 } @@ -2207,7 +2197,7 @@ protected override void NewItem( try { - symLinkExists = CheckItemExists(path, out isSymLinkDirectory); + symLinkExists = Utils.ItemExists(path, out isSymLinkDirectory); } catch (Exception e) { @@ -2336,7 +2326,7 @@ protected override void NewItem( try { - exists = CheckItemExists(strTargetPath, out isDirectory); + exists = Utils.ItemExists(strTargetPath, out isDirectory); } catch (Exception e) { @@ -2364,7 +2354,7 @@ protected override void NewItem( try { - pathExists = CheckItemExists(path, out isPathDirectory); + pathExists = Utils.ItemExists(path, out isPathDirectory); } catch (Exception e) { @@ -2484,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, @@ -2921,15 +2891,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.ItemExists(directory.FullName, out bool _)) + { + // Directory does not exist + return; + } } - - if (accessException != null) + catch (Exception accessException) { ErrorRecord errorRecord = new ErrorRecord(accessException, "RemoveFileSystemItemUnAuthorizedAccess", ErrorCategory.PermissionDenied, directory); @@ -3249,19 +3219,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.ItemExists(path, out bool _); FileSystemItemProviderDynamicParameters itemExistsDynamicParameters = DynamicParameters as FileSystemItemProviderDynamicParameters; @@ -3566,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; @@ -3940,7 +3898,7 @@ private void CopyDirectoryFromRemoteSession( CreateDirectory(destination, false); // If failed to create directory - if (!Utils.NativeDirectoryExists(destination)) + if (!Utils.DirectoryExists(destination)) { return; } @@ -5013,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); @@ -5647,7 +5605,7 @@ protected override bool IsItemContainer(string path) path = NormalizePath(path); - return Utils.NativeDirectoryExists(path); + return Utils.DirectoryExists(path); } #region MoveItem @@ -6063,16 +6021,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.ItemExists(path, out bool isDirectory)) { if (isDirectory) { @@ -6231,16 +6181,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.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); }