Inheritance: System.Runtime.InteropServices.SafeHandle
コード例 #1
0
ファイル: Platform.cs プロジェクト: schmich/debuggernaut
 public static extern SafeFileMapViewHandle MapViewOfFile(
     SafeFileHandle hFileMappingObject,
     FileMapAccess dwDesiredAccess,
     uint dwFileOffsetHigh,
     uint dwFileOffsetLow,
     uint dwNumberOfBytesToMap
     );
コード例 #2
0
        public BackupFileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access)
        {
            if (handle == null)
            {
                throw new ArgumentNullException();
            }
            if (handle.IsInvalid)
            {
                throw new ArgumentException();
            }
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new PlatformNotSupportedException();
            }
            switch (access)
            {
                case FileAccess.Read:
                case FileAccess.Write:
                    this.SafeFileHandle = handle;
                    this.Access = access;
                    return;

                case FileAccess.ReadWrite:
                    throw new ArgumentException();
            }
            throw new InvalidEnumArgumentException();
        }
コード例 #3
0
        /// <summary>Opens the specified file with the requested flags and mode.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="flags">The flags with which to open the file.</param>
        /// <param name="mode">The mode for opening the file.</param>
        /// <returns>A SafeFileHandle for the opened file.</returns>
        internal static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode)
        {
            Debug.Assert(path != null);

            SafeFileHandle handle = new SafeFileHandle(ownsHandle: true);

            // If we fail to open the file due to a path not existing, we need to know whether to blame
            // the file itself or its directory.  If we're creating the file, then we blame the directory,
            // otherwise we blame the file.
            bool enoentDueToDirectory = (flags & Interop.Sys.OpenFlags.O_CREAT) != 0;

            // Open the file. 
            int fd;
            while (Interop.CheckIo(fd = Interop.Sys.Open(path, flags, mode), path, isDirectory: enoentDueToDirectory,
                errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e)) ;
            handle.SetHandle(fd);

            // Make sure it's not a directory; we do this after opening it once we have a file descriptor 
            // to avoid race conditions.
            Interop.Sys.FileStatus status;
            if (Interop.Sys.FStat(fd, out status) != 0)
            {
                handle.Dispose();
                throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), path);
            }
            if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR)
            {
                handle.Dispose();
                throw Interop.GetExceptionForIoErrno(Interop.Error.EACCES.Info(), path, isDirectory: true);
            }

            return handle;
        }
コード例 #4
0
 public static extern bool DuplicateTokenEx(
     SafeFileHandle hExistingToken,
     uint dwDesiredAccess,
     SecurityAttributes lpTokenAttributes,
     SecurityImpersonationLevel impersonationLevel,
     TokenType tokenType,
     out IntPtr hNewToken);
コード例 #5
0
ファイル: Hid.cs プロジェクト: raipat/nia-brew
            ///  <summary>
            ///  reads a Feature report from the device.
            ///  </summary>
            ///  
            ///  <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param>
            ///  <param name="readHandle"> the handle for reading Input reports from the device. </param>
            ///  <param name="writeHandle"> the handle for writing Output reports to the device. </param>
            ///  <param name="myDeviceDetected"> tells whether the device is currently attached.</param>
            ///  <param name="inFeatureReportBuffer"> contains the requested report.</param>
            ///  <param name="success"> read success</param>

            public override void Read(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, ref Boolean myDeviceDetected, ref Byte[] inFeatureReportBuffer, ref Boolean success) 
            {                 
                try 
                { 
                    //  ***
                    //  API function: HidD_GetFeature
                    //  Attempts to read a Feature report from the device.
                    
                    //  Requires:
                    //  A handle to a HID
                    //  A pointer to a buffer containing the report ID and report
                    //  The size of the buffer. 
                    
                    //  Returns: true on success, false on failure.
                    //  ***                    
                   
                    success = HidD_GetFeature(hidHandle, ref inFeatureReportBuffer[0], inFeatureReportBuffer.Length); 
                                        
                    Debug.Print( "HidD_GetFeature success = " + success );                     
                } 
                catch ( Exception ex ) 
                { 
                    DisplayException( MODULE_NAME, ex ); 
                    throw ; 
                }                 
            }             
コード例 #6
0
ファイル: Hid.cs プロジェクト: sky8273/GenericHid
        ///  <summary>
        ///  Remove any input reports waiting in the buffer.
        ///  </summary>
        ///
        ///  <param name="hidHandle">A handle to a device.</param>
        ///
        ///  <returns>True on success. False on failure.</returns>
        internal Boolean FlushQueue(SafeFileHandle hidHandle)
        {
            Boolean success = false;

             traceSource.TraceEvent(TraceEventType.Verbose, 1, "FlushQueue");

             try
             {
            //  ***
            //  API function: HidD_FlushQueue

            //  Purpose: Removes any Input reports waiting in the buffer.

            //  Accepts: a handle to the device.

            //  Returns: True on success, False on failure.
            //  ***

            success = NativeMethods.HidD_FlushQueue(hidHandle);
             }
             catch (Exception ex)
             {
            DisplayException(MethodBase.GetCurrentMethod().Name, ex, ShowMsgBoxOnException);
             }

             return success;
        }
コード例 #7
0
ファイル: Hid.cs プロジェクト: rbray89/usbpov
        ///  <summary>
        ///  Remove any Input reports waiting in the buffer.
        ///  </summary>
        ///  
        ///  <param name="hidHandle"> a handle to a device.   </param>
        ///  
        ///  <returns>
        ///  True on success, False on failure.
        ///  </returns>
        internal Boolean FlushQueue( SafeFileHandle hidHandle )
        {
            Boolean success = false;

            try
            {
                //  ***
                //  API function: HidD_FlushQueue

                //  Purpose: Removes any Input reports waiting in the buffer.

                //  Accepts: a handle to the device.

                //  Returns: True on success, False on failure.
                //  ***

                success = HidD_FlushQueue( hidHandle );

                return success;
            }
            catch ( Exception ex )
            {
                DisplayException( MODULE_NAME, ex );
                throw ;
            }
        }
コード例 #8
0
ファイル: Win32.cs プロジェクト: Bia10/clrn
 public static extern bool WriteFile(
     SafeFileHandle hFile,
     IntPtr pBuffer,
     int nNumberOfBytesToWrite,
     ref uint lpNumberOfBytesWritten,
     IntPtr overlapped
     );
コード例 #9
0
ファイル: Win32Pipe.cs プロジェクト: fschwiet/PShochu
 private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, AdvApi32PInvoke.SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize)
 {
     if ((!Kernel32.CreatePipe(out hReadPipe, out hWritePipe, ref lpPipeAttributes, nSize) || hReadPipe.IsInvalid) || hWritePipe.IsInvalid)
     {
         throw new Win32Exception();
     }
 }
コード例 #10
0
ファイル: Kernel32.cs プロジェクト: fparaggio/atmo
        public static extern bool WriteFile(
			SafeFileHandle hFile,
			byte[] lpBuffer,
			uint nNumberOfBytesToWrite,
			out uint lpNumberOfBytesWritten,
			IntPtr lpOverlapped
		);
コード例 #11
0
ファイル: Win32Pipe.cs プロジェクト: fschwiet/PShochu
        public static void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs)
        {
            AdvApi32PInvoke.SECURITY_ATTRIBUTES lpPipeAttributes = new AdvApi32PInvoke.SECURITY_ATTRIBUTES();
            lpPipeAttributes.bInheritHandle = true;
            SafeFileHandle hWritePipe = null;
            try
            {
                if (parentInputs)
                {
                    CreatePipeWithSecurityAttributes(out childHandle, out hWritePipe, lpPipeAttributes, 0);
                }
                else
                {
                    CreatePipeWithSecurityAttributes(out hWritePipe, out childHandle, lpPipeAttributes, 0);
                }

                if (!Kernel32.DuplicateHandle(Kernel32.GetCurrentProcess(), hWritePipe, Kernel32.GetCurrentProcess(), out parentHandle,
                    0, false, Kernel32.DUPLICATE_SAME_ACCESS))
                {
                    throw new Win32Exception();
                }
            }
            finally
            {
                if ((hWritePipe != null) && !hWritePipe.IsInvalid)
                {
                    hWritePipe.Close();
                }
            }
        }
コード例 #12
0
 public static extern Boolean LogonUser(
     String lpszUserName,
     String lpszDomain,
     String lpszPassword,
     LogonType dwLogonType,
     LogonProvider dwLogonProvider,
     out SafeFileHandle phToken);
コード例 #13
0
ファイル: mode2.cs プロジェクト: GraphicGame/CSLightStudio
    void InitConsole()
    {
#if UNITY_STANDALONE

        FreeConsole();
        AllocConsole();
        IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
        Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
        System.IO.FileStream fileStream = new System.IO.FileStream(safeFileHandle, System.IO.FileAccess.Write);
        System.Text.Encoding encoding = System.Text.Encoding.ASCII;
        System.IO.StreamWriter standardOutput = new System.IO.StreamWriter(fileStream, encoding);
        standardOutput.AutoFlush = true;
        Console.SetOut(standardOutput);
        Application.RegisterLogCallbackThreaded((text, trace, type) =>
        {
            if (type == LogType.Error)
            {
                Console.ForegroundColor = ConsoleColor.Red;
            }
            else if (type == LogType.Warning)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.White;
            }
            Console.WriteLine(text);
        });
#endif

    }
コード例 #14
0
ファイル: StartupInfo.cs プロジェクト: chrisforbes/dbgtool
 public STARTUPINFO()
 {
     this.cb = Marshal.SizeOf(this);
     this.hStdInput = new SafeFileHandle(new IntPtr(0), false);
     this.hStdOutput = new SafeFileHandle(new IntPtr(0), false);
     this.hStdError = new SafeFileHandle(new IntPtr(0), false);
 }
コード例 #15
0
 public static extern Boolean ReadFile(
     SafeFileHandle hFile,
     IntPtr lpBuffer,
     Int32 nNumberOfBytesToRead,
     ref Int32 lpNumberOfBytesRead,
     IntPtr lpOverlapped
     );
コード例 #16
0
        private static FileStream CreateSharedBackingObject(
            Interop.libc.MemoryMappedProtections protections, long capacity,
            out string mapName, out SafeMemoryMappedFileHandle.FileStreamSource fileStreamSource)
        {
            // The POSIX shared memory object name must begin with '/'.  After that we just want something short and unique.
            mapName = "/" + MemoryMapObjectFilePrefix + Guid.NewGuid().ToString("N");
            fileStreamSource = SafeMemoryMappedFileHandle.FileStreamSource.ManufacturedSharedMemory;

            // Determine the flags to use when creating the shared memory object
            Interop.libc.OpenFlags flags = (protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 ?
                Interop.libc.OpenFlags.O_RDWR :
                Interop.libc.OpenFlags.O_RDONLY;
            flags |= Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_EXCL; // CreateNew

            // Determine the permissions with which to create the file
            Interop.libc.Permissions perms = default(Interop.libc.Permissions);
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_READ) != 0)
                perms |= Interop.libc.Permissions.S_IRUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0)
                perms |= Interop.libc.Permissions.S_IWUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_EXEC) != 0)
                perms |= Interop.libc.Permissions.S_IXUSR;

            // Create the shared memory object. Then enlarge it to the requested capacity.
            int fd;
            Interop.CheckIo(fd = Interop.libc.shm_open(mapName, flags, (int)perms), mapName);
            SafeFileHandle fileHandle = new SafeFileHandle((IntPtr)fd, ownsHandle: true);

            // Wrap the handle in a stream and return it.
            var fs = new FileStream(fileHandle, TranslateProtectionsToFileAccess(protections));
            fs.SetLength(capacity);
            return fs;
        }
コード例 #17
0
ファイル: DriverVista.cs プロジェクト: Azzuro/IR-Server-Suite
 private static extern bool DeviceIoControl(
   SafeFileHandle handle,
   [MarshalAs(UnmanagedType.U4)] IoCtrl ioControlCode,
   IntPtr inBuffer, int inBufferSize,
   IntPtr outBuffer, int outBufferSize,
   out int bytesReturned,
   IntPtr overlapped);
コード例 #18
0
 public static extern Boolean WriteFile(
     SafeFileHandle hFile,
     Byte[] lpBuffer,
     Int32 nNumberOfBytesToWrite,
     ref Int32 lpNumberOfBytesWritten,
     IntPtr lpOverlapped
     );
コード例 #19
0
		public static extern bool ReadFile (
			SafeFileHandle hFile,
			byte[] lpBuffer,
			int nNumberOfBytesToRead,
			out int lpNumberOfBytesRead,
			IntPtr lpOverlapped
		);
コード例 #20
0
ファイル: JobObject.cs プロジェクト: kleopatra999/vs-chromium
 public void Dispose()
 {
     if (_handle != null) {
     _handle.Dispose();
     _handle = null;
       }
 }
コード例 #21
0
        private static SafeMemoryMappedFileHandle CreateCore(
            SafeFileHandle fileHandle, string mapName, HandleInheritability inheritability,
            MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity)
        {
            Interop.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);

            // split the long into two ints
            int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL));
            int capacityHigh = unchecked((int)(capacity >> 32));

            SafeMemoryMappedFileHandle handle = fileHandle != null ?
                Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) :
                Interop.mincore.CreateFileMapping(Interop.INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName);

            int errorCode = Marshal.GetLastWin32Error();
            if (!handle.IsInvalid)
            {
                if (errorCode == Interop.ERROR_ALREADY_EXISTS)
                {
                    handle.Dispose();
                    throw Win32Marshal.GetExceptionForWin32Error(errorCode);
                }
            }
            else if (handle.IsInvalid)
            {
                throw Win32Marshal.GetExceptionForWin32Error(errorCode);
            }

            return handle;
        }
コード例 #22
0
 /// <summary>Opens a SafeFileHandle for a file descriptor created by a provided delegate.</summary>
 /// <param name="fdFunc">
 /// The function that creates the file descriptor. Returns the file descriptor on success, or -1 on error,
 /// with Marshal.GetLastWin32Error() set to the error code.
 /// </param>
 /// <returns>The created SafeFileHandle.</returns>
 internal static SafeFileHandle Open(Func<int> fdFunc)
 {
     var handle = new SafeFileHandle(ownsHandle: true);
     int fd;
     while (Interop.CheckIo(fd = fdFunc())) ;
     handle.SetHandle(fd);
     return handle;
 }
コード例 #23
0
        public DeviceIoWrapperBase(SafeFileHandle handle, bool ownsHandle = false)
        {
            if (handle.IsInvalid)
                throw new ArgumentException("Handle is invalid");

            _ownsHandle = ownsHandle;
            Handle = handle;
        }
コード例 #24
0
ファイル: NativeMethods.cs プロジェクト: goldshtn/minidumper
   public static extern bool DuplicateHandle(
 HandleRef hSourceProcessHandle,
 SafeHandle hSourceHandle,
 HandleRef hTargetProcess,
 out SafeFileHandle targetHandle,
 int dwDesiredAccess,
 bool bInheritHandle,
 int dwOptions);
コード例 #25
0
 public void Close()
 {
     if (_diskHandle != null)
     {
         _diskHandle.Dispose();
         _diskHandle = null;
     }
 }
コード例 #26
0
        internal static new IFileSystemInformation Create(string originalPath, SafeFileHandle fileHandle, NativeMethods.FileManagement.BY_HANDLE_FILE_INFORMATION info, IFileService fileService)
        {
            if ((info.dwFileAttributes & System.IO.FileAttributes.Directory) == 0) throw new ArgumentOutOfRangeException(nameof(info));

            var directoryInfo = new DirectoryInformation(fileService);
            directoryInfo.PopulateData(originalPath, fileHandle, info);
            return directoryInfo;
        }
コード例 #27
0
 internal WinHidDevice(UsbApiBase usbApi,
                       SafeFileHandle usbHandle,
                       string devicePath) 
     : base(usbApi, usbHandle)
 {
     mDevicePath = devicePath;
     mSafeDevHandle = usbHandle;
 }
コード例 #28
0
		public static extern bool DuplicateHandle (
			IntPtr hSourceProcessHandle,
			SafeFileHandle hSourceHandle,
			IntPtr hTargetProcessHandle,
			out SafeFileHandle lpTargetHandle,
			uint dwDesiredAccess,
			bool bInheritHandle,
			uint dwOptions
		);
コード例 #29
0
 internal static extern bool DeviceIoControl(Microsoft.Win32.SafeHandles.SafeFileHandle hDevice,
                                             uint IoControlCode,
                                             [MarshalAs(UnmanagedType.AsAny)]
                                             [In] object InBuffer,
                                             uint nInBufferSize,
                                             [MarshalAs(UnmanagedType.AsAny)]
                                             [Out] object OutBuffer,
                                             uint nOutBufferSize,
                                             ref uint pBytesReturned,
                                             [In] ref System.Threading.NativeOverlapped Overlapped);
コード例 #30
0
 internal static extern bool DeviceIoControl(
     Microsoft.Win32.SafeHandles.SafeFileHandle hDevice,
     EIOControlCode ioControlCode,
     [In] IntPtr inBuffer,
     uint nInBufferSize,
     [Out] IntPtr outBuffer,
     uint nOutBufferSize,
     out uint pBytesReturned,
     [In] IntPtr overlapped
     );
コード例 #31
0
ファイル: BatteryBarGraph.cs プロジェクト: rotom407/Infomate
 static extern bool DeviceIoControl(
     Microsoft.Win32.SafeHandles.SafeFileHandle hDevice,
     uint IoControlCode,
     ref BATTERY_WAIT_STATUS InBuffer,
     int nInBufferSize,
     ref BATTERY_STATUS OutBuffer,
     int nOutBufferSize,
     ref int pBytesReturned,
     IntPtr Overlapped
     );
コード例 #32
0
 public static extern bool DeviceIoControl(
     Microsoft.Win32.SafeHandles.SafeFileHandle hDevice,
     IntPtr IoControlCode,
     [In] byte[] InBuffer,
     uint nInBufferSize,
     [Out] byte[] OutBuffer,
     uint nOutBufferSize,
     ref uint pBytesReturned,
     IntPtr Overlapped
     );
コード例 #33
0
 public static void CreatePipe(out SafeFileHandle readPipeHandle, out SafeFileHandle writePipeHandle, PipeSecurity pipeSecurity = null)
 {
     using (var securityAttributes = pipeSecurity == null ? new SecurityAttributes(true) : new SecurityAttributes(pipeSecurity))
     {
         if (!NativeMethods.CreatePipe(out readPipeHandle, out writePipeHandle, securityAttributes, 0))
         {
             ErrorHelper.ThrowCustomWin32Exception();
         }
     }
 }
コード例 #34
0
ファイル: DiskDevice.cs プロジェクト: thohng/WinFLASHTool
 static extern bool DeviceIoControl(
     Microsoft.Win32.SafeHandles.SafeFileHandle hDevice,
     int IoControlCode,
     IntPtr InBuffer,
     int nInBufferSize,
     IntPtr outBuffer,
     int nOutBufferSize,
     out int pBytesReturned,
     IntPtr Overlapped
     );
コード例 #35
0
ファイル: WinUsbDevice.cs プロジェクト: GSharp-Project/GSharp
 internal WinUsbDevice(UsbApiBase usbApi,
     SafeFileHandle usbHandle,
     SafeHandle handle,
     string devicePath)
     : base(usbApi, handle)
 {
     mDevicePath = devicePath;
     mSafeDevHandle = usbHandle;
     mPowerPolicies = new PowerPolicies(this);
 }
コード例 #36
0
 internal static extern bool DeviceIoControl
 (
     Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle,
     uint ioControlCode,
     IntPtr inBuffer,
     uint cbInBuffer,
     IntPtr outBuffer,
     uint cbOutBuffer,
     out uint cbBytesReturned,
     IntPtr overlapped
 );
コード例 #37
0
 internal static extern UInt32 NtCreateFile
 (
     out Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle,
     Int32 desiredAccess,
     ref OBJECT_ATTRIBUTES objectAttributes,
     out IO_STATUS_BLOCK ioStatusBlock,
     ref Int64 allocationSize,
     UInt32 fileAttributes,
     System.IO.FileShare shareAccess,
     UInt32 createDisposition,
     UInt32 createOptions,
     SafeHandle eaBuffer,
     UInt32 eaLength
 );
コード例 #38
0
ファイル: Win32.cs プロジェクト: michael2012z/xenadmin
 public static extern bool FlushFileBuffers(Microsoft.Win32.SafeHandles.SafeFileHandle hFile);
コード例 #39
0
 public static extern bool GetFileInformationByHandle(
     Microsoft.Win32.SafeHandles.SafeFileHandle hFile,
     out BY_HANDLE_FILE_INFORMATION lpFileInformation
     );
コード例 #40
0
 private static extern bool DeviceIoControl(Microsoft.Win32.SafeHandles.SafeFileHandle hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, IntPtr lpOutBuffer, uint nOutBufferSize, ref uint lpBytesReturned, IntPtr lpOverlapped);
コード例 #41
0
        private unsafe void OpenSqlFileStream
        (
            string sPath,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            long allocationSize
        )
        {
            //-----------------------------------------------------------------
            // precondition validation
            // these should be checked by any caller of this method
            // ensure we have validated and normalized the path before
            Debug.Assert(sPath != null);
            Debug.Assert(transactionContext != null);

            if (access != System.IO.FileAccess.Read && access != System.IO.FileAccess.Write && access != System.IO.FileAccess.ReadWrite)
            {
                throw ADP.ArgumentOutOfRange("access");
            }

            // FileOptions is a set of flags, so AND the given value against the set of values we do not support
            if ((options & ~(System.IO.FileOptions.WriteThrough | System.IO.FileOptions.Asynchronous | System.IO.FileOptions.RandomAccess | System.IO.FileOptions.SequentialScan)) != 0)
            {
                throw ADP.ArgumentOutOfRange("options");
            }

            //-----------------------------------------------------------------
            // normalize the provided path
            // * compress path to remove any occurrences of '.' or '..'
            // * trim whitespace from the beginning and end of the path
            // * ensure that the path starts with '\\'
            // * ensure that the path does not start with '\\.\'
            sPath = GetFullPathInternal(sPath);

            Microsoft.Win32.SafeHandles.SafeFileHandle hFile    = null;
            Interop.NtDll.DesiredAccess     nDesiredAccess      = Interop.NtDll.DesiredAccess.FILE_READ_ATTRIBUTES | Interop.NtDll.DesiredAccess.SYNCHRONIZE;
            Interop.NtDll.CreateOptions     dwCreateOptions     = 0;
            Interop.NtDll.CreateDisposition dwCreateDisposition = 0;
            System.IO.FileShare             nShareAccess        = System.IO.FileShare.None;

            switch (access)
            {
            case System.IO.FileAccess.Read:

                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_READ_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OPEN;
                break;

            case System.IO.FileAccess.Write:
                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
                break;

            case System.IO.FileAccess.ReadWrite:
            default:
                // we validate the value of 'access' parameter in the beginning of this method
                Debug.Assert(access == System.IO.FileAccess.ReadWrite);

                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_READ_DATA | Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
                break;
            }

            if ((options & System.IO.FileOptions.WriteThrough) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_WRITE_THROUGH;
            }

            if ((options & System.IO.FileOptions.Asynchronous) == 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT;
            }

            if ((options & System.IO.FileOptions.SequentialScan) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SEQUENTIAL_ONLY;
            }

            if ((options & System.IO.FileOptions.RandomAccess) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_RANDOM_ACCESS;
            }

            try
            {
                // NOTE: the Name property is intended to reveal the publicly available moniker for the
                // FILESTREAM attributed column data. We will not surface the internal processing that
                // takes place to create the mappedPath.
                string mappedPath = InitializeNtPath(sPath);
                int    retval     = 0;
                Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out uint oldMode);

                try
                {
                    if (transactionContext.Length >= ushort.MaxValue)
                    {
                        throw ADP.ArgumentOutOfRange("transactionContext");
                    }

                    int headerSize = sizeof(Interop.NtDll.FILE_FULL_EA_INFORMATION);
                    int fullSize   = headerSize + transactionContext.Length + s_eaNameString.Length;

                    byte[] buffer = ArrayPool <byte> .Shared.Rent(fullSize);

                    fixed(byte *b = buffer)
                    {
                        Interop.NtDll.FILE_FULL_EA_INFORMATION *ea = (Interop.NtDll.FILE_FULL_EA_INFORMATION *)b;
                        ea->NextEntryOffset = 0;
                        ea->Flags           = 0;
                        ea->EaNameLength    = (byte)(s_eaNameString.Length - 1); // Length does not include terminating null character.
                        ea->EaValueLength   = (ushort)transactionContext.Length;

                        // We could continue to do pointer math here, chose to use Span for convenience to
                        // make sure we get the other members in the right place.
                        Span <byte> data = buffer.AsSpan(headerSize);

                        s_eaNameString.AsSpan().CopyTo(data);
                        data = data.Slice(s_eaNameString.Length);
                        transactionContext.AsSpan().CopyTo(data);

                        (int status, IntPtr handle) = Interop.NtDll.CreateFile(
                            path: mappedPath.AsSpan(),
                            rootDirectory: IntPtr.Zero,
                            createDisposition: dwCreateDisposition,
                            desiredAccess: nDesiredAccess,
                            shareAccess: nShareAccess,
                            fileAttributes: 0,
                            createOptions: dwCreateOptions,
                            eaBuffer: b,
                            eaLength: (uint)fullSize);
                        retval = status;
                        hFile  = new SafeFileHandle(handle, true);
                    }

                    ArrayPool <byte> .Shared.Return(buffer);
                }
                finally
                {
                    Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
                }

                switch (retval)
                {
                case 0:
                    break;

                case Interop.Errors.ERROR_SHARING_VIOLATION:
                    throw ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlFileStream_FileAlreadyInTransaction));

                case Interop.Errors.ERROR_INVALID_PARAMETER:
                    throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_InvalidParameter));

                case Interop.Errors.ERROR_FILE_NOT_FOUND:
                {
                    System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                default:
                {
                    uint error = Interop.NtDll.RtlNtStatusToDosError(retval);
                    if (error == ERROR_MR_MID_NOT_FOUND)
                    {
                        // status code could not be mapped to a Win32 error code
                        error = (uint)retval;
                    }

                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error));
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }
                }

                if (hFile.IsInvalid)
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Interop.Errors.ERROR_INVALID_HANDLE);
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK)
                {
                    hFile.Dispose();
                    throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_PathNotValidDiskResource));
                }

                // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
                // through current data and then append new data to the end, so we need to tell SQL Server to preserve
                // the existing file contents.
                if (access == System.IO.FileAccess.ReadWrite)
                {
                    uint ioControlCode = Interop.Kernel32.CTL_CODE(FILE_DEVICE_FILE_SYSTEM,
                                                                   IoControlCodeFunctionCode, (byte)Interop.Kernel32.IoControlTransferType.METHOD_BUFFERED,
                                                                   (byte)Interop.Kernel32.IoControlCodeAccess.FILE_ANY_ACCESS);

                    if (!Interop.Kernel32.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out uint cbBytesReturned, IntPtr.Zero))
                    {
                        System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(e);
                        throw e;
                    }
                }

                // now that we've successfully opened a handle on the path and verified that it is a file,
                // use the SafeFileHandle to initialize our internal System.IO.FileStream instance
                System.Diagnostics.Debug.Assert(_m_fs == null);
                _m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
            }
            catch
            {
                if (hFile != null && !hFile.IsInvalid)
                {
                    hFile.Dispose();
                }

                throw;
            }
        }
コード例 #42
0
 private static extern bool SetCommState(Microsoft.Win32.SafeHandles.SafeFileHandle hFile, IntPtr lpDCB);
コード例 #43
0
        private void OpenSqlFileStream
        (
            string path,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            Int64 allocationSize
        )
        {
            //-----------------------------------------------------------------
            // precondition validation

            // these should be checked by any caller of this method

            // ensure we have validated and normalized the path before
            Debug.Assert(path != null);
            Debug.Assert(transactionContext != null);

            if (access != FileAccess.Read && access != FileAccess.Write && access != FileAccess.ReadWrite)
            {
                throw ADP.ArgumentOutOfRange("access");
            }

            // FileOptions is a set of flags, so AND the given value against the set of values we do not support
            if ((options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.SequentialScan)) != 0)
            {
                throw ADP.ArgumentOutOfRange("options");
            }

            //-----------------------------------------------------------------

            // normalize the provided path
            //   * compress path to remove any occurences of '.' or '..'
            //   * trim whitespace from the beginning and end of the path
            //   * ensure that the path starts with '\\'
            //   * ensure that the path does not start with '\\.\'
            //   * ensure that the path is not longer than Int16.MaxValue
            path = GetFullPathInternal(path);

            // ensure the running code has permission to read/write the file
            DemandAccessPermission(path, access);

            FileFullEaInformation    eaBuffer   = null;
            SecurityQualityOfService qos        = null;
            UnicodeString            objectName = null;

            Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null;

            int nDesiredAccess = UnsafeNativeMethods.FILE_READ_ATTRIBUTES | UnsafeNativeMethods.SYNCHRONIZE;

            UInt32 dwCreateOptions     = 0;
            UInt32 dwCreateDisposition = 0;

            System.IO.FileShare shareAccess = System.IO.FileShare.None;

            switch (access)
            {
            case System.IO.FileAccess.Read:
                nDesiredAccess     |= UnsafeNativeMethods.FILE_READ_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OPEN;
                break;

            case System.IO.FileAccess.Write:
                nDesiredAccess     |= UnsafeNativeMethods.FILE_WRITE_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE;
                break;

            case System.IO.FileAccess.ReadWrite:
            default:
                // we validate the value of 'access' parameter in the beginning of this method
                Debug.Assert(access == System.IO.FileAccess.ReadWrite);

                nDesiredAccess     |= UnsafeNativeMethods.FILE_READ_DATA | UnsafeNativeMethods.FILE_WRITE_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE;
                break;
            }

            if ((options & System.IO.FileOptions.WriteThrough) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_WRITE_THROUGH;
            }

            if ((options & System.IO.FileOptions.Asynchronous) == 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SYNCHRONOUS_IO_NONALERT;
            }

            if ((options & System.IO.FileOptions.SequentialScan) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SEQUENTIAL_ONLY;
            }

            if ((options & System.IO.FileOptions.RandomAccess) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_RANDOM_ACCESS;
            }

            try
            {
                eaBuffer = new FileFullEaInformation(transactionContext);

                qos = new SecurityQualityOfService(UnsafeNativeMethods.SecurityImpersonationLevel.SecurityAnonymous,
                                                   false, false);

                // NOTE: the Name property is intended to reveal the publicly available moniker for the
                //   FILESTREAM attributed column data. We will not surface the internal processing that
                //   takes place to create the mappedPath.
                string mappedPath = InitializeNtPath(path);
                objectName = new UnicodeString(mappedPath);

                UnsafeNativeMethods.OBJECT_ATTRIBUTES oa;
                oa.length                   = Marshal.SizeOf(typeof(UnsafeNativeMethods.OBJECT_ATTRIBUTES));
                oa.rootDirectory            = IntPtr.Zero;
                oa.attributes               = (int)UnsafeNativeMethods.Attributes.CaseInsensitive;
                oa.securityDescriptor       = IntPtr.Zero;
                oa.securityQualityOfService = qos;
                oa.objectName               = objectName;

                UnsafeNativeMethods.IO_STATUS_BLOCK ioStatusBlock;

                uint oldMode;
                uint retval = 0;

                UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode);
                try
                {
                    Bid.Trace("<sc.SqlFileStream.OpenSqlFileStream|ADV> %d#, desiredAccess=0x%08x, allocationSize=%I64d, fileAttributes=0x%08x, shareAccess=0x%08x, dwCreateDisposition=0x%08x, createOptions=0x%08x\n",
                              ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition, dwCreateOptions);

                    retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess,
                                                              ref oa, out ioStatusBlock, ref allocationSize,
                                                              0, shareAccess, dwCreateDisposition, dwCreateOptions,
                                                              eaBuffer, (uint)eaBuffer.Length);
                }
                finally
                {
                    UnsafeNativeMethods.SetErrorModeWrapper(oldMode, out oldMode);
                }

                switch (retval)
                {
                case 0:
                    break;

                case UnsafeNativeMethods.STATUS_SHARING_VIOLATION:
                    throw ADP.InvalidOperation(Res.GetString(Res.SqlFileStream_FileAlreadyInTransaction));

                case UnsafeNativeMethods.STATUS_INVALID_PARAMETER:
                    throw ADP.Argument(Res.GetString(Res.SqlFileStream_InvalidParameter));

                case UnsafeNativeMethods.STATUS_OBJECT_NAME_NOT_FOUND:
                {
                    System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                default:
                {
                    uint error = UnsafeNativeMethods.RtlNtStatusToDosError(retval);
                    if (error == UnsafeNativeMethods.ERROR_MR_MID_NOT_FOUND)
                    {
                        // status code could not be mapped to a Win32 error code
                        error = retval;
                    }

                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error));
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }
                }

                if (hFile.IsInvalid)
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(UnsafeNativeMethods.ERROR_INVALID_HANDLE);
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                UnsafeNativeMethods.FileType fileType = UnsafeNativeMethods.GetFileType(hFile);
                if (fileType != UnsafeNativeMethods.FileType.Disk)
                {
                    hFile.Dispose();
                    throw ADP.Argument(Res.GetString(Res.SqlFileStream_PathNotValidDiskResource));
                }

                // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
                //   through current data and then append new data to the end, so we need to tell SQL Server to preserve
                //   the existing file contents.
                if (access == System.IO.FileAccess.ReadWrite)
                {
                    uint ioControlCode = UnsafeNativeMethods.CTL_CODE(UnsafeNativeMethods.FILE_DEVICE_FILE_SYSTEM,
                                                                      IoControlCodeFunctionCode, (byte)UnsafeNativeMethods.Method.METHOD_BUFFERED,
                                                                      (byte)UnsafeNativeMethods.Access.FILE_ANY_ACCESS);
                    uint cbBytesReturned = 0;

                    if (!UnsafeNativeMethods.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out cbBytesReturned, IntPtr.Zero))
                    {
                        System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(e);
                        throw e;
                    }
                }

                // now that we've successfully opened a handle on the path and verified that it is a file,
                //   use the SafeFileHandle to initialize our internal System.IO.FileStream instance
                // NOTE: need to assert UnmanagedCode permissions for this constructor. This is relatively benign
                //   in that we've done much the same validation as in the FileStream(string path, ...) ctor case
                //   most notably, validating that the handle type corresponds to an on-disk file.
                bool bRevertAssert = false;
                try
                {
                    SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                    sp.Assert();
                    bRevertAssert = true;

                    System.Diagnostics.Debug.Assert(m_fs == null);
                    m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
                }
                finally
                {
                    if (bRevertAssert)
                    {
                        SecurityPermission.RevertAssert();
                    }
                }
            }
            catch
            {
                if (hFile != null && !hFile.IsInvalid)
                {
                    hFile.Dispose();
                }

                throw;
            }
            finally
            {
                if (eaBuffer != null)
                {
                    eaBuffer.Dispose();
                    eaBuffer = null;
                }

                if (qos != null)
                {
                    qos.Dispose();
                    qos = null;
                }

                if (objectName != null)
                {
                    objectName.Dispose();
                    objectName = null;
                }
            }
        }
コード例 #44
0
 internal static extern FileType GetFileType
 (
     Microsoft.Win32.SafeHandles.SafeFileHandle hFile
 );
コード例 #45
0
 public static extern uint SetFilePointer(
     [In] Microsoft.Win32.SafeHandles.SafeFileHandle hFile,
     [In] int lDistanceToMove,
     [In, Out] ref int lpDistanceToMoveHigh,
     [In] EMoveMethod dwMoveMethod);