/// <summary> /// Creates or opens a <see cref="IAsyncFile"/>. Throws on failure. /// </summary> /// <exception cref="BuildXL.Native.IO.NativeWin32Exception">Thrown on failure</exception> public static IAsyncFile CreateOrOpen( string path, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode creationDisposition, FileFlagsAndAttributes flagsAndAttributes, IIOCompletionManager ioCompletionManager = null) { IAsyncFile file; OpenFileResult result = TryCreateOrOpen( path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes | FileFlagsAndAttributes.FileFlagOverlapped, out file, ioCompletionManager); if (file != null) { Contract.Assert(result.Succeeded); return(file); } Contract.Assert(!result.Succeeded); throw result.ThrowForError(); }
static IntPtr StgCreateStorageEx_Hooked([MarshalAs(UnmanagedType.LPWStr)][In] string pwcsName, [In] STGM grfMode, [In] STGFMT stgfmt, [In] FileFlagsAndAttributes grfAttrs, [In] IntPtr pStgOptions, [In] IntPtr pSecurityDescriptor, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [Out][MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 6)] out object ppObjectOpen) { try { Main This = (Main)HookRuntimeInfo.Callback; lock (This.Queue) { This.Interface.OnCreateFile(RemoteHooking.GetCurrentThreadId(), new[] { pwcsName }); /*This.Queue.Push("[" + RemoteHooking.GetCurrentProcessId() + ":" + * RemoteHooking.GetCurrentThreadId() + "]: \"" + InFileName + "\""); * InFileName = InFileName.Replace("C", "D");*/ } } catch { } return(StgCreateStorageEx( pwcsName, grfMode, stgfmt, grfAttrs, pStgOptions, pSecurityDescriptor, riid, out ppObjectOpen)); }
/// <inheritdoc /> public OpenFileResult TryOpenFileById( SafeFileHandle existingHandleOnVolume, FileId fileId, FileDesiredAccess desiredAccess, FileShare shareMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) => throw new NotImplementedException();
public static extern SafeFileHandle CreateFile([MarshalAs(UnmanagedType.LPTStr)] string filename, [MarshalAs(UnmanagedType.U4)] FileAccess access, [MarshalAs(UnmanagedType.U4)] FileShare share, IntPtr securityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition, [MarshalAs(UnmanagedType.U4)] FileFlagsAndAttributes flagsAndAttributes, IntPtr templateFile);
/// <summary> /// Returns an <see cref="IAsyncFile"/>. Does not throw on failure. /// </summary> private static OpenFileResult TryCreateOrOpen( string path, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode creationDisposition, FileFlagsAndAttributes flagsAndAttributes, out IAsyncFile openedFile, IIOCompletionManager ioCompletionManager = null) { SafeFileHandle handle; OpenFileResult result = FileUtilities.TryCreateOrOpenFile( path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes | FileFlagsAndAttributes.FileFlagOverlapped, out handle); if (handle != null) { Contract.Assert(result.Succeeded && !handle.IsInvalid); openedFile = CreateAsyncFile(handle, desiredAccess, ownsHandle: true, ioCompletionManager: ioCompletionManager, path: path); } else { Contract.Assert(!result.Succeeded); openedFile = null; } return(result); }
private static OpenFileResult TryOpenDirectory( string directoryPath, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode fileMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { Contract.Requires(!string.IsNullOrEmpty(directoryPath)); if (flagsAndAttributes.HasFlag(FileFlagsAndAttributes.FileFlagOpenReparsePoint) && IsSymlink(directoryPath)) { return(TryOpenSymlink(directoryPath, desiredAccess, shareMode, fileMode, out handle)); } try { FileStream fs = new FileStream(directoryPath, fileMode, FileDesiredAccessToFileAccess(desiredAccess), shareMode, DefaultBufferSize, FileFlagsAndAttributesToFileOptions(flagsAndAttributes | FileFlagsAndAttributes.FileFlagBackupSemantics)); handle = fs.SafeFileHandle; return(OpenFileResult.Create(NativeIOConstants.ErrorSuccess, fileMode, handleIsValid: true, openingById: false)); } catch (Exception ex) { handle = null; int nativeErrorCode = (int)NativeErrorCodeForException(ex); Logger.Log.StorageTryOpenDirectoryFailure(Events.StaticContext, directoryPath, nativeErrorCode); return(OpenFileResult.Create(nativeErrorCode, fileMode, handleIsValid: false, openingById: false)); } }
/// <inheritdoc /> public OpenFileResult TryCreateOrOpenFile( string path, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode creationDisposition, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { if (flagsAndAttributes.HasFlag(FileFlagsAndAttributes.FileFlagOpenReparsePoint) && IsSymlink(path)) { return(TryOpenSymlink(path, desiredAccess, shareMode, creationDisposition, out handle)); } try { FileStream fs = new FileStream(path, creationDisposition, FileDesiredAccessToFileAccess(desiredAccess), shareMode, DefaultBufferSize, FileFlagsAndAttributesToFileOptions(flagsAndAttributes)); handle = fs.SafeFileHandle; return(OpenFileResult.Create(NativeIOConstants.ErrorSuccess, creationDisposition, handleIsValid: true, openingById: false)); } catch (Exception ex) { handle = null; var errorCode = NativeErrorCodeForException(ex); Logger.Log.StorageTryOpenOrCreateFileFailure(Events.StaticContext, path, (int)creationDisposition, (int)errorCode); return(OpenFileResult.Create((int)errorCode, creationDisposition, handleIsValid: false, openingById: false)); } }
/// <inheritdoc /> public TResult UsingFileHandleAndFileLength <TResult>( string path, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode creationDisposition, FileFlagsAndAttributes flagsAndAttributes, Func <SafeFileHandle, long, TResult> handleStream) { SafeFileHandle handle; var openResult = s_fileSystem.TryCreateOrOpenFile( path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes, out handle); if (!openResult.Succeeded) { openResult .CreateFailureForError() .Annotate($"{nameof(s_fileSystem.TryCreateOrOpenFile)} failed in {nameof(UsingFileHandleAndFileLength)}") .Throw(); } using (handle) { Contract.Assert(handle != null && !handle.IsInvalid); var maybeTarget = s_fileSystem.TryGetReparsePointTarget(path); var length = maybeTarget.Succeeded ? maybeTarget.Result.Length : new FileInfo(path).Length; return(handleStream(handle, length)); } }
public static extern SafeFileHandle CreateFileW( string lpFileName, FileDesiredAccess dwDesiredAccess, FileShare dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, FileFlagsAndAttributes dwFlagsAndAttributes, IntPtr hTemplateFile);
public static extern IntPtr CreateFileW( string lpFileName, FileAccessMode dwDesiredAccess, FileShareMode dwShareMode, IntPtr lpSecurityAttributes, // always 0 FileCreationDisposition dwCreationDisposition, FileFlagsAndAttributes dwFlagsAndAttributes, // typically just FILE_FLAG_OVERLAPPED IntPtr hTemplateFile);
public static extern IntPtr CreateFile( string fileName, FileAccessRightFlags desiredAccess, FileShareModeFlags shareMode, IntPtr securityAttributes, FileCreationDisposition creationDisposition, FileFlagsAndAttributes flagsAndAttributes, IntPtr templateFile);
public static extern IntPtr CreateFile( string fileName, FileAccessRightFlags desiredAccess, FileShareModeFlags shareMode, IntPtr securityAttributes, FileCreationDisposition creationDisposition, FileFlagsAndAttributes flagsAndAttributes, IntPtr templateFile);
public static extern SafeFileHandle CreateFile( string lpFileName, FileDesiredAccess dwDesiredAccess, FileShareFlags dwShareMode, IntPtr lpSecurityAttributes, FileCreationDisposition dwCreationDisposition, FileFlagsAndAttributes dwFlagsAndAttributes, IntPtr hTemplateFile );
/// <see cref="IFileSystem.TryOpenDirectory(string, FileDesiredAccess, FileShare, FileFlagsAndAttributes, out SafeFileHandle)"/> public static OpenFileResult TryOpenDirectory( string directoryPath, FileDesiredAccess desiredAccess, FileShare shareMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { return(s_fileSystem.TryOpenDirectory(directoryPath, desiredAccess, shareMode, flagsAndAttributes, out handle)); }
/// <see cref="IFileSystem.TryReOpenFile(SafeFileHandle, FileDesiredAccess, FileShare, FileFlagsAndAttributes, out SafeFileHandle)"/> public static ReOpenFileStatus TryReOpenFile( SafeFileHandle existing, FileDesiredAccess desiredAccess, FileShare shareMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle reopenedHandle) { return(s_fileSystem.TryReOpenFile(existing, desiredAccess, shareMode, flagsAndAttributes, out reopenedHandle)); }
/// <see cref="IFileSystem.TryOpenFileById(SafeFileHandle, FileId, FileDesiredAccess, FileShare, FileFlagsAndAttributes, out SafeFileHandle)"/> public static OpenFileResult TryOpenFileById( SafeFileHandle existingHandleOnVolume, FileId fileId, FileDesiredAccess desiredAccess, FileShare shareMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { return(s_fileSystem.TryOpenFileById(existingHandleOnVolume, fileId, desiredAccess, shareMode, flagsAndAttributes, out handle)); }
/// <see cref="IFileSystem.TryCreateOrOpenFile(string, FileDesiredAccess, FileShare, FileMode, FileFlagsAndAttributes, out SafeFileHandle)"/> public static OpenFileResult TryCreateOrOpenFile( string path, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode creationDisposition, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { return(s_fileSystem.TryCreateOrOpenFile(path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes, out handle)); }
/// <inheritdoc /> public OpenFileResult TryOpenDirectory( string directoryPath, FileDesiredAccess desiredAccess, FileShare shareMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { Contract.Requires(!string.IsNullOrEmpty(directoryPath)); return(TryOpenDirectory(directoryPath, desiredAccess, shareMode, FileMode.Open, flagsAndAttributes, out handle)); }
/// <summary> /// Creates an instance of <see cref="NamedPipeServerStream"/> and immediately connects a client to it. /// </summary> /// <param name="serverDirection">Server direction.</param> /// <param name="serverOptions">Server options.</param> /// <param name="clientOptions">Client options.</param> /// <param name="clientHandle">Output client handle.</param> /// <returns>An instance of <see cref="NamedPipeServerStream"/>.</returns> public static NamedPipeServerStream CreateNamedPipeServerStream( PipeDirection serverDirection, PipeOptions serverOptions, PipeOptions clientOptions, out SafeFileHandle clientHandle) { string pipeName = @"BuildXL-" + Guid.NewGuid().ToString("N"); var pipeServerStream = new NamedPipeServerStream( pipeName, serverDirection, maxNumberOfServerInstances: 1, transmissionMode: PipeTransmissionMode.Byte, options: serverOptions, inBufferSize: PipeBufferSize, outBufferSize: PipeBufferSize); FileDesiredAccess clientDesiredAccess = FileDesiredAccess.None; if ((PipeDirection.In & serverDirection) != 0) { clientDesiredAccess |= FileDesiredAccess.GenericWrite; } if ((PipeDirection.Out & serverDirection) != 0) { clientDesiredAccess |= FileDesiredAccess.GenericRead; } FileFlagsAndAttributes clientFlags = clientOptions == PipeOptions.Asynchronous ? FileFlagsAndAttributes.FileFlagOverlapped : 0; OpenFileResult openClientHandle = FileUtilities.TryCreateOrOpenFile( @"\\.\pipe\" + pipeName, clientDesiredAccess, FileShare.None, FileMode.Open, clientFlags | FileFlagsAndAttributes.SecurityAnonymous, out clientHandle); if (!openClientHandle.Succeeded) { throw openClientHandle.CreateExceptionForError(); } // Client should be made inheritable. SetInheritable(clientHandle); pipeServerStream.WaitForConnection(); return(pipeServerStream); }
/// <inheritdoc /> public OpenFileResult TryOpenDirectory( string directoryPath, FileDesiredAccess desiredAccess, FileShare shareMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { Contract.Requires(!string.IsNullOrEmpty(directoryPath)); Contract.Ensures(Contract.Result <OpenFileResult>().Succeeded == (Contract.ValueAtReturn(out handle) != null)); Contract.Ensures(!Contract.Result <OpenFileResult>().Succeeded || !Contract.ValueAtReturn(out handle).IsInvalid); return(TryOpenDirectory(directoryPath, desiredAccess, shareMode, FileMode.Open, flagsAndAttributes, out handle)); }
/////////////////////////////////////////////////////////////////////// #if NATIVE && WINDOWS public static bool HasFlags( FileFlagsAndAttributes flags, FileFlagsAndAttributes hasFlags, bool all ) { if (all) { return((flags & hasFlags) == hasFlags); } else { return((flags & hasFlags) != FileFlagsAndAttributes.FILE_ATTRIBUTE_NONE); } }
/// <see cref="IFileUtilities.UsingFileHandleAndFileLength"/> public static TResult UsingFileHandleAndFileLength <TResult>( string path, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode creationDisposition, FileFlagsAndAttributes flagsAndAttributes, Func <SafeFileHandle, long, TResult> handleStream) => s_fileUtilities.UsingFileHandleAndFileLength( path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes, handleStream);
/// <inheritdoc /> public OpenFileResult TryCreateOrOpenFile( string path, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode creationDisposition, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { return(TryOpen( path, desiredAccess, shareMode, creationDisposition, flagsAndAttributes.HasFlag(FileFlagsAndAttributes.FileFlagOpenReparsePoint) && IsSymlink(path), out handle)); }
private bool OpenDevice() { try { FileShareMode shareModeExclusive = FileShareMode.FILE_SHARE_NONE; FileShareMode shareModeNormal = FileShareMode.FILE_SHARE_READ | FileShareMode.FILE_SHARE_WRITE; FileDesiredAccess desiredAccess = FileDesiredAccess.GENERIC_READ | FileDesiredAccess.GENERIC_WRITE; FileCreationDisposition creationDisposition = FileCreationDisposition.OPEN_EXISTING; FileFlagsAndAttributes flagsAttributes = FileFlagsAndAttributes.FILE_FLAG_NORMAL | FileFlagsAndAttributes.FILE_FLAG_OVERLAPPED | FileFlagsAndAttributes.FILE_FLAG_NO_BUFFERING; //Try to open the device exclusively FileHandle = CreateFile(DevicePath, desiredAccess, shareModeExclusive, IntPtr.Zero, creationDisposition, flagsAttributes, IntPtr.Zero); Exclusive = true; //Try to open the device normally if (FileHandle == null || FileHandle.IsInvalid || FileHandle.IsClosed) { //Debug.WriteLine("Failed to open device exclusively, opening normally."); FileHandle = CreateFile(DevicePath, desiredAccess, shareModeNormal, IntPtr.Zero, creationDisposition, flagsAttributes, IntPtr.Zero); Exclusive = false; } //Check if the device is opened if (FileHandle == null || FileHandle.IsInvalid || FileHandle.IsClosed) { //Debug.WriteLine("Failed to open hid device: " + DevicePath); Connected = false; Installed = false; return(false); } else { //Debug.WriteLine("Opened hid device: " + DevicePath + ", exclusively: " + Exclusive); Connected = true; Installed = true; return(true); } } catch (Exception ex) { Debug.WriteLine("Failed to open hid device: " + ex.Message); Connected = false; Installed = false; return(false); } }
/// <summary> /// Handles intercepted file access. /// </summary> /// <param name="fileName"></param> /// <param name="desiredAccess"></param> /// <param name="shareMode"></param> /// <param name="securityAttributes"></param> /// <param name="creationDisposition"></param> /// <param name="flagsAndAttributes"></param> /// <param name="templateFile"></param> /// <returns></returns> public IntPtr CreateFile(string fileName, FileAccessRightFlags desiredAccess, FileShareModeFlags shareMode, IntPtr securityAttributes, FileCreationDisposition creationDisposition, FileFlagsAndAttributes flagsAndAttributes, IntPtr templateFile) { var request = new FileRequest { CreationDisposition = creationDisposition, Path = fileName, ResourceType = ResourceType.File }; using (EngineCore.Engine.GetEngineProcessingSpace()) { var virtualPath = _fileSystem.GetVirtualPath(request); return HostFileSystem.NativeMethods.CreateFile( virtualPath, desiredAccess, shareMode, securityAttributes, creationDisposition, flagsAndAttributes, templateFile); } }
private OpenFileResult TryOpenDirectory( string directoryPath, FileDesiredAccess desiredAccess, FileShare shareMode, FileMode fileMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle handle) { Contract.Requires(!string.IsNullOrEmpty(directoryPath)); return(TryOpen( directoryPath, desiredAccess, shareMode, fileMode, flagsAndAttributes.HasFlag(FileFlagsAndAttributes.FileFlagOpenReparsePoint) && IsSymlink(directoryPath), out handle)); }
/// <summary> /// Tries to open a handle to the given file as identified by a (<paramref name="volumeSerial"/>, <paramref name="fileId"/>) pair. /// If the result is <see cref="OpenFileByIdResult.Succeeded"/>, <paramref name="fileHandle"/> has been set to a valid handle. /// </summary> /// <remarks> /// This method is not thread safe (see <see cref="FileAccessor"/> remarks). /// </remarks> public OpenFileByIdResult TryOpenFileById( ulong volumeSerial, FileId fileId, FileDesiredAccess desiredAccess, FileShare shareMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle fileHandle) { Contract.Requires(!Disposed); Contract.Ensures((Contract.Result <OpenFileByIdResult>() == OpenFileByIdResult.Succeeded) == (Contract.ValueAtReturn(out fileHandle) != null)); Contract.Ensures((Contract.Result <OpenFileByIdResult>() != OpenFileByIdResult.Succeeded) || !Contract.ValueAtReturn(out fileHandle).IsInvalid); SafeFileHandle volumeRootHandle = TryGetVolumeRoot(volumeSerial); if (volumeRootHandle == null) { fileHandle = null; return(OpenFileByIdResult.FailedToOpenVolume); } OpenFileResult openResult = FileUtilities.TryOpenFileById( volumeRootHandle, fileId, desiredAccess, shareMode, flagsAndAttributes, out fileHandle); if (!openResult.Succeeded) { Contract.Assert(fileHandle == null); if (openResult.Status.IsNonexistent()) { return(OpenFileByIdResult.FailedToFindFile); } else { return(OpenFileByIdResult.FailedToAccessExistentFile); } } return(OpenFileByIdResult.Succeeded); }
/// <summary> /// Handles intercepted file access. /// </summary> /// <param name="fileName"></param> /// <param name="desiredAccess"></param> /// <param name="shareMode"></param> /// <param name="securityAttributes"></param> /// <param name="creationDisposition"></param> /// <param name="flagsAndAttributes"></param> /// <param name="templateFile"></param> /// <returns></returns> public IntPtr CreateFile(string fileName, FileAccessRightFlags desiredAccess, FileShareModeFlags shareMode, IntPtr securityAttributes, FileCreationDisposition creationDisposition, FileFlagsAndAttributes flagsAndAttributes, IntPtr templateFile) { var request = new FileRequest { CreationDisposition = creationDisposition, Path = fileName, ResourceType = ResourceType.File }; using (EngineCore.Engine.GetEngineProcessingSpace()) { var virtualPath = _fileSystem.GetVirtualPath(request); return(HostFileSystem.NativeMethods.CreateFile( virtualPath, desiredAccess, shareMode, securityAttributes, creationDisposition, flagsAndAttributes, templateFile)); } }
/// <summary>Initializes a new instance of the <see cref="TempFile"/> class and retrieves a handle to the file.</summary> /// <param name="dwDesiredAccess">The desired access.</param> /// <param name="dwShareMode">The share mode.</param> /// <param name="dwCreationDisposition">The creation disposition.</param> /// <param name="dwFlagsAndAttributes">The flags and attributes.</param> public TempFile(Kernel32.FileAccess dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition = FileMode.OpenOrCreate, FileFlagsAndAttributes dwFlagsAndAttributes = FileFlagsAndAttributes.FILE_ATTRIBUTE_NORMAL) : this(string.Empty) =>
/// <inheritdoc /> public ReOpenFileStatus TryReOpenFile( SafeFileHandle existing, FileDesiredAccess desiredAccess, FileShare shareMode, FileFlagsAndAttributes flagsAndAttributes, out SafeFileHandle reopenedHandle) => throw new NotImplementedException();
=> 0; // TODO: Task #1272136 (FileContentTable) /// <nodoc /> private static FileOptions FileFlagsAndAttributesToFileOptions(FileFlagsAndAttributes flagsAndAttributes) => s_fileOptionsFlags.Aggregate(FileOptions.None, (acc, kvp) => flagsAndAttributes.HasFlag(kvp.Key) ? acc | kvp.Value : acc);
public static extern IntPtr CreateFile(string lpFileName, ACCESS_MASK dwDesiredAccess, FILE_SHARE dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, FileFlagsAndAttributes dwFlagsAndAttributes, IntPtr hTemplateFile);
public static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, FILE_SHARE dwShareMode, [In] ref SECURITY_ATTRIBUTES lpSecurityAttributes, FileMode dwCreationDisposition, FileFlagsAndAttributes dwFlagsAndAttributes, IntPtr hTemplateFile);
public static extern HRESULT StgOpenStorageEx([MarshalAs(UnmanagedType.LPWStr)] string pwcsName, STGM grfMode, STGFMT stgfmt, FileFlagsAndAttributes grfAttrs, ref STGOPTIONS pStgOptions, IntPtr reserved2, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 6)] out object ppObjectOpen);
public TempFile(Kernel32.FileAccess dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition = FileMode.OpenOrCreate, FileFlagsAndAttributes dwFlagsAndAttributes = FileFlagsAndAttributes.FILE_ATTRIBUTE_NORMAL) : this() { hFile = CreateFile(FullName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero); }