private static extern bool BackupSeek(
     SafeFileHandle hFile,
     uint dwLowBytesToSeek,
     uint dwHighBytesToSeek,
     out uint lpdwLowByteSeeked,
     out uint lpdwHighByteSeeked,
     ref IntPtr lpContext);
Пример #2
0
 private static extern bool GetMailslotInfo(
     SafeFileHandle hMailslot,   // メールスロットのハンドル
     IntPtr lpMaxMessageSize,    // 最大メッセージサイズ
     out int lpNextSize,         // 次のメッセージのサイズ
     IntPtr lpMessageCount,      // メッセージ数
     IntPtr lpReadTimeout        // 読み取りタイムアウトの間隔
   );
        private SerialPortFixer(string portName)
        {
            const int dwFlagsAndAttributes = 0x40000000;
            const int dwAccess = unchecked((int) 0xC0000000);

            if ((portName == null) || !portName.StartsWith("COM", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("Invalid Serial Port", "portName");
            }
            var hFile = CreateFile(@"\\.\" + portName, dwAccess, 0, IntPtr.Zero, 3, dwFlagsAndAttributes,
                IntPtr.Zero);
            if (hFile.IsInvalid)
            {
                WinIoError();
            }
            try
            {
                var fileType = GetFileType(hFile);
                if ((fileType != 2) && (fileType != 0))
                {
                    throw new ArgumentException("Invalid Serial Port", "portName");
                }
                m_Handle = hFile;
                InitializeDcb();
            }
            catch
            {
                hFile.Close();
                m_Handle = null;
                throw;
            }
        }
Пример #4
0
		/// <summary>
		/// Get HID attributes.
		/// </summary>
		/// <param name="hidHandle"> HID handle retrieved with CreateFile </param>
		/// <param name="deviceAttributes"> HID attributes structure </param>
		/// <returns> true on success </returns>

		internal Boolean GetAttributes(SafeFileHandle hidHandle, ref NativeMethods.HIDD_ATTRIBUTES deviceAttributes)
		{
			Boolean success;
			try
			{
				//  ***
				//  API function:
				//  HidD_GetAttributes

				//  Purpose:
				//  Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID, 
				//  Product ID, and Product Version Number for a device.

				//  Accepts:
				//  A handle returned by CreateFile.
				//  A pointer to receive a HIDD_ATTRIBUTES structure.

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

				success = NativeMethods.HidD_GetAttributes(hidHandle, ref deviceAttributes);
			}

			catch (Exception ex)
			{
				DisplayException(ModuleName, ex);
				throw;
			}
			return success;
		}
Пример #5
0
        public DriveAccess(string Path)
        {
            if (Path == null || Path.Length == 0)
                throw new ArgumentNullException("Path");

            driveHandle = CreateFile(Path, 0xC0000000, 0x03, IntPtr.Zero, 0x03, 0x80, IntPtr.Zero);
            if (driveHandle.IsInvalid)
            {
                driveHandle.Close();
                driveHandle.Dispose();
                driveHandle = null;
                throw new Exception("Win32 Exception : 0x" + Convert.ToString(Marshal.GetHRForLastWin32Error(), 16).PadLeft(8, '0'));
            }
            driveStream = new FileStream(driveHandle, FileAccess.ReadWrite);

            IntPtr p = Marshal.AllocHGlobal(24);
            uint returned;
            if (DeviceIoControl(driveHandle.DangerousGetHandle(), 0x00070000, IntPtr.Zero, 0, p, 40, out returned, IntPtr.Zero))
                unsafe { driveGeometry = new DriveGeometry((byte*)p.ToPointer()); }
            else
            {
                Marshal.FreeHGlobal(p);
                throw new Exception("Could not get the drive geometry information!");
            }
            Marshal.FreeHGlobal(p);
        }
Пример #6
0
        public Boolean Connect()
        {
            try
            {
                handle = CreateFile(@"\\.\pipe\" + strPipeName, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);

                if (handle == null) return false;

                if (handle.IsInvalid)
                {
                    blConnected = false;
                    return false;
                }

                blConnected = true;

                readThread = new Thread(new ThreadStart(readFromPipe));
                readThread.Start();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
 private static unsafe int ReadFileNative(SafeFileHandle hFile, byte[] bytes, int offset, int count, int mustBeZero, out int errorCode)
 {
     int num;
     int num2;
     if ((bytes.Length - offset) < count)
     {
         throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition"));
     }
     if (bytes.Length == 0)
     {
         errorCode = 0;
         return 0;
     }
     WaitForAvailableConsoleInput(hFile);
     fixed (byte* numRef = bytes)
     {
         num = ReadFile(hFile, numRef + offset, count, out num2, Win32Native.NULL);
     }
     if (num == 0)
     {
         errorCode = Marshal.GetLastWin32Error();
         if (errorCode == 0x6d)
         {
             return 0;
         }
         return -1;
     }
     errorCode = 0;
     return num2;
 }
Пример #8
0
        /// <summary>
        /// Connects to the server with a pipename.
        /// </summary>
        /// <param name="pipename">The name of the pipe to connect to.</param>
        public void Connect(string pipename)
        {
            if (Connected)
                throw new Exception("Already connected to pipe server.");

            PipeName = pipename;

            handle =
               CreateFile(
                  PipeName,
                  0xC0000000, // GENERIC_READ | GENERIC_WRITE = 0x80000000 | 0x40000000
                  0,
                  IntPtr.Zero,
                  3, // OPEN_EXISTING
                  0x40000000, // FILE_FLAG_OVERLAPPED
                  IntPtr.Zero);

            //could not create handle - server probably not running
            if (handle.IsInvalid)
                return;

            Connected = true;

            //start listening for messages
            readThread = new Thread(Read)
                             {
                                 IsBackground = true
                             };
            readThread.Start();
        }
Пример #9
0
 public bool Initialize()
 {
     if (!AttachConsole(ATTACH_PARENT_PROCESS)) AllocConsole();
     if (GetConsoleWindow() == IntPtr.Zero)
     {
         FreeConsole();
         return false;
     }
     oldOutput = Console.Out;
     oldEncoding = Console.OutputEncoding;
     var encoding = new UTF8Encoding(false);
     SetConsoleOutputCP((uint)encoding.CodePage);
     Console.OutputEncoding = encoding;
     Stream outStream;
     try
     {
         var safeFileHandle = new SafeFileHandle(GetStdHandle(STD_OUTPUT_HANDLE), true);
         outStream = new FileStream(safeFileHandle, FileAccess.Write);
     }
     catch (Exception)
     {
         outStream = Console.OpenStandardOutput();
     }
     Console.SetOut(new StreamWriter(outStream, encoding) { AutoFlush = true });
     return true;
 }
Пример #10
0
        public Win32MemoryMapPager(string file,
            NativeFileAttributes options = NativeFileAttributes.Normal,
            NativeFileAccess access = NativeFileAccess.GenericRead | NativeFileAccess.GenericWrite)
        {
            _access = access;
            _fileInfo = new FileInfo(file);
            bool noData = _fileInfo.Exists == false || _fileInfo.Length == 0;
            _handle = NativeFileMethods.CreateFile(file, access,
                NativeFileShare.Read | NativeFileShare.Write | NativeFileShare.Delete, IntPtr.Zero,
                NativeFileCreationDisposition.OpenAlways, options, IntPtr.Zero);
            if (_handle.IsInvalid)
            {
                int lastWin32ErrorCode = Marshal.GetLastWin32Error();
                throw new IOException("Failed to open file storage of Win32MemoryMapPager",
                    new Win32Exception(lastWin32ErrorCode));
            }

            _fileStream = new FileStream(_handle, FileAccess.ReadWrite);

            if (noData)
            {
                NumberOfAllocatedPages = 0;
            }
            else
            {
                NumberOfAllocatedPages = _fileInfo.Length/PageSize;
                PagerState.Release();
                PagerState = CreateNewPagerState();
            }
        }
Пример #11
0
        /// <summary>
        /// Polls a File Descriptor for the passed in flags.
        /// </summary>
        /// <param name="fd">The descriptor to poll</param>
        /// <param name="events">The events to poll for</param>
        /// <param name="timeout">The amount of time to wait; -1 for infinite, 0 for immediate return, and a positive number is the number of milliseconds</param>
        /// <param name="triggered">The events that were returned by the poll call. May be PollEvents.POLLNONE in the case of a timeout.</param>
        /// <returns>An error or Error.SUCCESS.</returns>
        internal static unsafe Error Poll(SafeFileHandle fd, PollEvents events, int timeout, out PollEvents triggered)
        {
            bool gotRef = false;
            try
            {
                fd.DangerousAddRef(ref gotRef);

                var pollEvent = new PollEvent
                {
                    FileDescriptor = fd.DangerousGetHandle().ToInt32(),
                    Events = events,
                };

                uint unused;
                Error err = Poll(&pollEvent, 1, timeout, &unused);
                triggered = pollEvent.TriggeredEvents;
                return err;
            }
            finally
            {
                if (gotRef)
                {
                    fd.DangerousRelease();
                }
            }
        }
Пример #12
0
        public ImageOverFilter()
            : base("CSharp Image Overlay Filter")
        {
            vid.DSplugin = true;



            NativeMethods.AllocConsole();
            IntPtr stdHandle = NativeMethods.GetStdHandle(STD_OUTPUT_HANDLE);
            SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
            FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
            Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
            StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);
            Console.WriteLine("This text you can see in console window.");

            AMMediaType pmt = new AMMediaType() { majorType = MediaType.Video, subType = MediaSubType.YUY2, formatType = MediaType.Video, formatPtr = IntPtr.Zero };
            SetMediaType(PinDirection.Input, pmt);
            pmt.Free();
            
            pmt = new AMMediaType() { majorType = MediaType.Video, subType = MediaSubType.RGB24, formatType = MediaType.Video, formatPtr = IntPtr.Zero };
            SetMediaType(PinDirection.Output, pmt);
            pmt.Free();
        }
Пример #13
0
        /// <summary>
        /// Creates a file stream with the given filename that is deleted when either the
        /// stream is closed, or the application is terminated.
        /// </summary>
        /// <remarks>
        /// If the file already exists, it is overwritten without any error (CREATE_ALWAYS).
        /// </remarks>
        /// <param name="fileName">The full path to the file to create.</param>
        /// <returns>A Stream with read and write access.</returns>
        public static FileStream CreateTempFile(string fileName)
        {
            FileStream stream;
            IntPtr hFile = SafeNativeMethods.CreateFileW(
                fileName,
                NativeConstants.GENERIC_READ | NativeConstants.GENERIC_WRITE,
                NativeConstants.FILE_SHARE_READ,
                IntPtr.Zero,
                NativeConstants.CREATE_ALWAYS,
                NativeConstants.FILE_ATTRIBUTE_TEMPORARY |
                    NativeConstants.FILE_FLAG_DELETE_ON_CLOSE |
                    NativeConstants.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,
                IntPtr.Zero);

            if (hFile == NativeConstants.INVALID_HANDLE_VALUE)
            {
                NativeMethods.ThrowOnWin32Error("CreateFileW returned INVALID_HANDLE_VALUE");
            }

            SafeFileHandle sfhFile = new SafeFileHandle(hFile, true);
            try
            {
                stream = new FileStream(sfhFile, FileAccess.ReadWrite);
            }

            catch (Exception)
            {
                SafeNativeMethods.CloseHandle(hFile);
                hFile = IntPtr.Zero;
                throw;
            }

            return stream;
        }
Пример #14
0
 // Methods
 public Device(string path)
 {
     IntPtr ptr;
     this.Handle = GetDeviceHandle(path);
     this.Attributes = new Hid.HIDD_ATTRIBUTES();
     Hid.HidD_GetAttributes(this.Handle, ref this.Attributes);
     if (Marshal.GetLastWin32Error() != 0)
     {
         throw new Win32Exception("Cannot get device attributes.");
     }
     this.Capabilities = new Hid.HIDP_CAPS();
     if (Hid.HidD_GetPreparsedData(this.Handle, out ptr))
     {
         try
         {
             Hid.HidP_GetCaps(ptr, out this.Capabilities);
         }
         finally
         {
             Hid.HidD_FreePreparsedData(ref ptr);
         }
     }
     if (Marshal.GetLastWin32Error() != 0)
     {
         throw new Win32Exception("Cannot get device capabilities.");
     }
     SafeFileHandle handle = new SafeFileHandle(this.Handle, true);
     this.DataStream = new FileStream(handle, FileAccess.ReadWrite, this.Capabilities.InputReportByteLength, true);
     timeout = 3000;
 }
Пример #15
0
 internal static extern SafeMemoryMappedFileHandle CreateFileMapping(
     SafeFileHandle hFile,
     ref SECURITY_ATTRIBUTES lpFileMappingAttributes,
     int flProtect,
     int dwMaximumSizeHigh,
     int dwMaximumSizeLow,
     string lpName);
Пример #16
0
        //Connect to a server using the same pipe
        public bool Connect()
        {
            try
            {
                _handle = CreateFile(@"\\.\pipe\" + _pipeName, GenericRead | GenericWrite, 0, IntPtr.Zero,
                    OpenExisting, FileFlagOverlapped, IntPtr.Zero);

                if (_handle == null)
                    return false;

                if (_handle.IsInvalid)
                {
                    _connected = false;
                    return false;
                }

                _connected = true;

                _readThread = new Thread(ReadFromPipe);
                _readThread.Start();

                return true;
            }
            catch
            {
                return false;
            }
        }
Пример #17
0
        /// <summary>
        /// 获取扇区信息
        /// </summary>
        /// <param name="DriverName">G:</param>
        public DiskUtil(string DriverName)
        {
            try
            {

                if (DriverName == null && DriverName.Trim().Length == 0) return;
                this.DriveName = DriverName;

                if (DriverName.Length >= 3)
                {
                    _DriverStream = new FileStream(DriverName, FileMode.Open, FileAccess.Read);
                }
                else
                {
                    _DriverHandle = CreateFileA("\\\\.\\" + this.DriveName.Trim(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

                    _DriverStream = new System.IO.FileStream(_DriverHandle, System.IO.FileAccess.Read);
                }

            }

            catch (Exception)
            {

            }
        }
Пример #18
0
		public static extern bool ReadFile(
			SafeFileHandle hFile,
			byte* pBuffer,
			int numBytesToRead,
			out int pNumberOfBytesRead,
			NativeOverlapped* lpOverlapped
			);
Пример #19
0
		private SerialPortFixer(string portName)
		{
			if (portName == null || !portName.StartsWith("COM", StringComparison.OrdinalIgnoreCase))
			{
				throw new ArgumentException("Invalid Serial Port", "portName");
			}
			else
			{
				SafeFileHandle safeFileHandle = SerialPortFixer.CreateFile(string.Concat("\\\\.\\", portName), -1073741824, 0, IntPtr.Zero, 3, 1073741824, IntPtr.Zero);
				if (safeFileHandle.IsInvalid)
				{
					SerialPortFixer.WinIoError();
				}
				try
				{
					int fileType = SerialPortFixer.GetFileType(safeFileHandle);
					if (fileType == 2 || fileType == 0)
					{
						this.m_Handle = safeFileHandle;
						this.InitializeDcb();
					}
					else
					{
						throw new ArgumentException("Invalid Serial Port", "portName");
					}
				}
				catch
				{
					safeFileHandle.Close();
					this.m_Handle = null;
					throw;
				}
				return;
			}
		}
Пример #20
0
 public void PrintScoresMatrix(SafeFileHandle handle)
     {
     if (this.nativeDesignScorer != IntPtr.Zero)
         {
         NadirHelper.PrintScoresMatrix(this.nativeDesignScorer, handle.DangerousGetHandle());
         }
     }
Пример #21
0
 public static extern bool ReadFile(
   SafeFileHandle hFile,
   IntPtr pBuffer,
   int numberOfBytesToRead,
   int[] pNumberOfBytesRead,
   NativeOverlapped[] lpOverlapped // should be fixed, if not null
   );
Пример #22
0
 public static IntPtr CreateFileMapping(SafeFileHandle handle,
     FileMapProtection flProtect, long ddMaxSize, string lpName)
 {
     var Hi = (int) (ddMaxSize/int.MaxValue);
     var Lo = (int) (ddMaxSize%int.MaxValue);
     return CreateFileMapping(handle.DangerousGetHandle(), IntPtr.Zero, flProtect, Hi, Lo, lpName);
 }
        private SerialPortFixer(string portName)
        {
            const int dwFlagsAndAttributes = 0x40000000;
            const int dwAccess = unchecked((int)0xC0000000);

            if (string.IsNullOrEmpty(portName))
            {
                throw new ArgumentException("Invalid Serial Port", "portName");
            }
            SafeFileHandle hFile = NativeMethods.CreateFile(@"\\.\" + portName, dwAccess, 0, IntPtr.Zero, 3, dwFlagsAndAttributes,
                                              IntPtr.Zero);
            if (hFile.IsInvalid)
            {
                WinIoError();
            }
            try
            {
                int fileType = NativeMethods.GetFileType(hFile);
                if ((fileType != 2) && (fileType != 0))
                {
                    throw new ArgumentException("Invalid Serial Port", "portName");
                }
                m_Handle = hFile;
                InitializeDcb();
            }
            catch
            {
                hFile.Close();
                m_Handle = null;
                throw;
            }
        }
Пример #24
0
        internal override bool TryReadValue(out long value)
        {
            try
            {
                IntPtr fileIntPtr = NativeMethods.CreateFileW(filename + ":" + Key, NativeConstants.GENERIC_READ, NativeConstants.FILE_SHARE_WRITE, IntPtr.Zero, NativeConstants.OPEN_ALWAYS, 0, IntPtr.Zero);
                if (fileIntPtr.ToInt32() <= 0)
                {
                    value = 0;
                    return false;
                }

                SafeFileHandle streamHandle = new SafeFileHandle(fileIntPtr, true);
                using (BinaryReader reader = new BinaryReader(new FileStream(streamHandle, FileAccess.Read)))
                {
                    value = reader.ReadInt64();
                }
                streamHandle.Close();

                return true;
            }
            catch
            {
                value = 0;
                return false;
            }
        }
Пример #25
0
 static extern uint FilterConnectCommunicationPort(
     string lpPortName,           // LPCWSTR lpPortName,
     uint dwOptions,              // DWORD dwOptions,
     IntPtr lpContext,            // LPCVOID lpContext,
     uint dwSizeOfContext,        // WORD dwSizeOfContext
     IntPtr lpSecurityAttributes, // LP_SECURITY_ATTRIBUTES lpSecurityAttributes
     out SafeFileHandle hPort);  // HANDLE *hPort
Пример #26
0
		///  <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)
		{
			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.
				//  ***

				Boolean success = NativeMethods.HidD_FlushQueue(hidHandle);

				return success;
			}

			catch (Exception ex)
			{
				DisplayException(ModuleName, ex);
				throw;
			}
		}
Пример #27
0
        /* open hid device */
        public bool Open(HIDInfo dev)
        {
            /* safe file handle */
            SafeFileHandle shandle;

            /* opens hid device file */
            handle = Native.CreateFile(dev.Path,
                Native.GENERIC_READ | Native.GENERIC_WRITE,
                Native.FILE_SHARE_READ | Native.FILE_SHARE_WRITE,
                IntPtr.Zero, Native.OPEN_EXISTING, Native.FILE_FLAG_OVERLAPPED,
                IntPtr.Zero);

            /* whops */
            if (handle == Native.INVALID_HANDLE_VALUE) {
                return false;
            }

            /* build up safe file handle */
            shandle = new SafeFileHandle(handle, false);

            /* prepare stream - async */
            _fileStream = new FileStream(shandle, FileAccess.ReadWrite,
                32, true);

            /* report status */
            return true;
        }
Пример #28
0
	    public FilePager(string file)
        {
            _fileInfo = new FileInfo(file);

            var noData = _fileInfo.Exists == false || _fileInfo.Length == 0;

            _safeFileHandle = NativeFileMethods.CreateFile(file,
	            NativeFileAccess.GenericRead | NativeFileAccess.GenericWrite,
	            NativeFileShare.Read, IntPtr.Zero,
	            NativeFileCreationDisposition.OpenAlways,
	            NativeFileAttributes.Write_Through | NativeFileAttributes.NoBuffering ,
	            IntPtr.Zero);

            if (_safeFileHandle.IsInvalid)
            {
                throw new Win32Exception();
            }

            _fileStream = new FileStream(_safeFileHandle, FileAccess.ReadWrite);

            if (noData)
            {
                NumberOfAllocatedPages = 0;
            }
            else
            {
				NumberOfAllocatedPages = _fileInfo.Length / PageSize;
	            PagerState.Release();
                PagerState = CreateNewPagerState();
            }
        }
Пример #29
0
 internal __ConsoleStream(SafeFileHandle handle, FileAccess access)
 { 
     Contract.Assert(handle != null && !handle.IsInvalid, "__ConsoleStream expects a valid handle!");
     _handle = handle; 
     _canRead = access == FileAccess.Read; 
     _canWrite = access == FileAccess.Write;
 } 
Пример #30
0
    int RunTest()
    {
        try
        {
            try
            {
                using (SafeFileHandle sfh = new SafeFileHandle(CreateFile("test.txt", 0x40000000, 0, 0, 2, 0x80, 0), true))
                {

                    ThreadPool.BindHandle(sfh);
                }
            }
            catch (Exception ex)
            {
                if (ex.ToString().IndexOf("0x80070057") != -1) // E_INVALIDARG, the handle isn't overlapped
                {
                    Console.WriteLine("Test passed");
                    return (100);
                }
                else
                {
                    Console.WriteLine("Got wrong error: {0}", ex);
                }
            }
        }
        finally
        {
            if (File.Exists("test.txt"))
            {
                File.Delete("test.txt");
            }
        }
        Console.WriteLine("Didn't get argument null exception");
        return (99);
    }
 static extern Boolean WinUsb_Initialize(SafeFileHandle DeviceHandle, ref IntPtr InterfaceHandle);
 internal static extern int FStat(SafeFileHandle fd, out FileStatus output);
Пример #33
0
 internal static partial int FSync(SafeFileHandle fd);
Пример #34
0
 internal static unsafe extern int WriteFile(SafeFileHandle handle, byte *bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
Пример #35
0
 static extern bool FlushFileBuffers(SafeFileHandle hFile);
Пример #36
0
 public static extern bool MiniDumpWriteDump(IntPtr hProcess, uint ProcessId, SafeFileHandle hFile, MINIDUMP_TYPE DumpType, ref MINIDUMP_EXCEPTION_INFORMATION ExceptionParam, IntPtr UserStreamParam, IntPtr CallbackParam);
 internal static extern int GetFileSize(SafeFileHandle hFile, out int lpFileSizeHigh);
 internal static extern bool ClearCommError(SafeFileHandle hFile, ref int lpErrors, ref Comstat lpStat);
Пример #39
0
 static extern bool WriteConsoleOutputW(
     SafeFileHandle hConsoleOutput,
     CharInfo[] lpBuffer,
     Coord dwBufferSize,
     Coord dwBufferCoord,
     ref SmallRect lpWriteRegion);
 internal static extern int GetFileType(SafeFileHandle hFile);
Пример #41
0
        /// <summary>Sends an ATA command in 48-bit LBA mode</summary>
        /// <returns>0 if no error occurred, otherwise, errno</returns>
        /// <param name="fd">File handle</param>
        /// <param name="buffer">Buffer for SCSI command response</param>
        /// <param name="timeout">Timeout in seconds</param>
        /// <param name="duration">Time it took to execute the command in milliseconds</param>
        /// <param name="sense"><c>True</c> if ATA error returned non-OK status</param>
        /// <param name="registers">Registers to send to drive</param>
        /// <param name="errorRegisters">Registers returned by drive</param>
        /// <param name="protocol">ATA protocol to use</param>
        internal static int SendAtaCommand(SafeFileHandle fd, AtaRegistersLba48 registers,
                                           out AtaErrorRegistersLba48 errorRegisters, AtaProtocol protocol,
                                           ref byte[] buffer, uint timeout, out double duration, out bool sense)
        {
            duration       = 0;
            sense          = false;
            errorRegisters = new AtaErrorRegistersLba48();

            if (buffer == null)
            {
                return(-1);
            }

            uint offsetForBuffer = (uint)(Marshal.SizeOf(typeof(AtaPassThroughEx)) + Marshal.SizeOf(typeof(uint)));

            var aptdBuf = new AtaPassThroughExBuffer
            {
                aptd = new AtaPassThroughEx
                {
                    TimeOutValue       = timeout,
                    DataBufferOffset   = (IntPtr)offsetForBuffer,
                    Length             = (ushort)Marshal.SizeOf(typeof(AtaPassThroughEx)),
                    DataTransferLength = (uint)buffer.Length,
                    PreviousTaskFile   = new AtaTaskFile
                    {
                        CylinderHigh = (byte)((registers.LbaHigh & 0xFF00) >> 8),
                        CylinderLow  = (byte)((registers.LbaMid & 0xFF00) >> 8),
                        Features     = (byte)((registers.Feature & 0xFF00) >> 8),
                        SectorCount  = (byte)((registers.SectorCount & 0xFF00) >> 8),
                        SectorNumber = (byte)((registers.LbaLow & 0xFF00) >> 8)
                    },
                    CurrentTaskFile = new AtaTaskFile
                    {
                        Command      = registers.Command, CylinderHigh = (byte)(registers.LbaHigh & 0xFF),
                        CylinderLow  = (byte)(registers.LbaMid & 0xFF),
                        DeviceHead   = registers.DeviceHead,
                        Features     = (byte)(registers.Feature & 0xFF),
                        SectorCount  = (byte)(registers.SectorCount & 0xFF),
                        SectorNumber = (byte)(registers.LbaLow & 0xFF)
                    }
                },
                dataBuffer = new byte[64 * 512]
            };

            switch (protocol)
            {
            case AtaProtocol.PioIn:
            case AtaProtocol.UDmaIn:
            case AtaProtocol.Dma:
                aptdBuf.aptd.AtaFlags = AtaFlags.DataIn;

                break;

            case AtaProtocol.PioOut:
            case AtaProtocol.UDmaOut:
                aptdBuf.aptd.AtaFlags = AtaFlags.DataOut;

                break;
            }

            switch (protocol)
            {
            case AtaProtocol.Dma:
            case AtaProtocol.DmaQueued:
            case AtaProtocol.FpDma:
            case AtaProtocol.UDmaIn:
            case AtaProtocol.UDmaOut:
                aptdBuf.aptd.AtaFlags |= AtaFlags.Dma;

                break;
            }

            aptdBuf.aptd.AtaFlags |= AtaFlags.ExtendedCommand;

            // Unknown if needed
            aptdBuf.aptd.AtaFlags |= AtaFlags.DrdyRequired;

            uint k     = 0;
            int  error = 0;

            Array.Copy(buffer, 0, aptdBuf.dataBuffer, 0, buffer.Length);

            DateTime start = DateTime.Now;

            sense = !Extern.DeviceIoControlAta(fd, WindowsIoctl.IoctlAtaPassThrough, ref aptdBuf,
                                               (uint)Marshal.SizeOf(aptdBuf), ref aptdBuf,
                                               (uint)Marshal.SizeOf(aptdBuf), ref k, IntPtr.Zero);

            DateTime end = DateTime.Now;

            if (sense)
            {
                error = Marshal.GetLastWin32Error();
            }

            Array.Copy(aptdBuf.dataBuffer, 0, buffer, 0, buffer.Length);

            duration = (end - start).TotalMilliseconds;

            errorRegisters.SectorCount = (ushort)((aptdBuf.aptd.PreviousTaskFile.SectorCount << 8) +
                                                  aptdBuf.aptd.CurrentTaskFile.SectorCount);

            errorRegisters.LbaLow = (ushort)((aptdBuf.aptd.PreviousTaskFile.SectorNumber << 8) +
                                             aptdBuf.aptd.CurrentTaskFile.SectorNumber);

            errorRegisters.LbaMid = (ushort)((aptdBuf.aptd.PreviousTaskFile.CylinderLow << 8) +
                                             aptdBuf.aptd.CurrentTaskFile.CylinderLow);

            errorRegisters.LbaHigh = (ushort)((aptdBuf.aptd.PreviousTaskFile.CylinderHigh << 8) +
                                              aptdBuf.aptd.CurrentTaskFile.CylinderHigh);

            errorRegisters.DeviceHead = aptdBuf.aptd.CurrentTaskFile.DeviceHead;
            errorRegisters.Error      = aptdBuf.aptd.CurrentTaskFile.Error;
            errorRegisters.Status     = aptdBuf.aptd.CurrentTaskFile.Status;

            sense = errorRegisters.Error != 0 || (errorRegisters.Status & 0xA5) != 0;

            return(error);
        }
 internal static extern bool SetCommState(SafeFileHandle hFile, ref Dcb lpDcb);
 private static extern int GetFileType(SafeFileHandle handle);
Пример #44
0
        /// <summary>Sends a MMC/SD command</summary>
        /// <returns>The result of the command.</returns>
        /// <param name="fd">File handle</param>
        /// <param name="command">MMC/SD opcode</param>
        /// <param name="buffer">Buffer for MMC/SD command response</param>
        /// <param name="timeout">Timeout in seconds</param>
        /// <param name="duration">Time it took to execute the command in milliseconds</param>
        /// <param name="sense"><c>True</c> if MMC/SD returned non-OK status</param>
        /// <param name="write"><c>True</c> if data is sent from host to card</param>
        /// <param name="isApplication"><c>True</c> if command should be preceded with CMD55</param>
        /// <param name="flags">Flags indicating kind and place of response</param>
        /// <param name="blocks">How many blocks to transfer</param>
        /// <param name="argument">Command argument</param>
        /// <param name="response">Response registers</param>
        /// <param name="blockSize">Size of block in bytes</param>
        internal static int SendMmcCommand(SafeFileHandle fd, MmcCommands command, bool write, bool isApplication,
                                           MmcFlags flags, uint argument, uint blockSize, uint blocks,
                                           ref byte[] buffer, out uint[] response, out double duration, out bool sense,
                                           uint timeout = 0)
        {
            var commandData       = new SffdiskDeviceCommandData();
            var commandDescriptor = new SdCmdDescriptor();

            commandData.size    = (ushort)Marshal.SizeOf(commandData);
            commandData.command = SffdiskDcmd.DeviceCommand;
            commandData.protocolArgumentSize    = (ushort)Marshal.SizeOf(commandDescriptor);
            commandData.deviceDataBufferSize    = blockSize * blocks;
            commandDescriptor.commandCode       = (byte)command;
            commandDescriptor.cmdClass          = isApplication ? SdCommandClass.AppCmd : SdCommandClass.Standard;
            commandDescriptor.transferDirection = write ? SdTransferDirection.Write : SdTransferDirection.Read;

            commandDescriptor.transferType = flags.HasFlag(MmcFlags.CommandAdtc) ? SdTransferType.SingleBlock
                                                 : SdTransferType.CmdOnly;

            commandDescriptor.responseType = 0;

            if (flags.HasFlag(MmcFlags.ResponseR1) ||
                flags.HasFlag(MmcFlags.ResponseSpiR1))
            {
                commandDescriptor.responseType = SdResponseType.R1;
            }

            if (flags.HasFlag(MmcFlags.ResponseR1B) ||
                flags.HasFlag(MmcFlags.ResponseSpiR1B))
            {
                commandDescriptor.responseType = SdResponseType.R1b;
            }

            if (flags.HasFlag(MmcFlags.ResponseR2) ||
                flags.HasFlag(MmcFlags.ResponseSpiR2))
            {
                commandDescriptor.responseType = SdResponseType.R2;
            }

            if (flags.HasFlag(MmcFlags.ResponseR3) ||
                flags.HasFlag(MmcFlags.ResponseSpiR3))
            {
                commandDescriptor.responseType = SdResponseType.R3;
            }

            if (flags.HasFlag(MmcFlags.ResponseR4) ||
                flags.HasFlag(MmcFlags.ResponseSpiR4))
            {
                commandDescriptor.responseType = SdResponseType.R4;
            }

            if (flags.HasFlag(MmcFlags.ResponseR5) ||
                flags.HasFlag(MmcFlags.ResponseSpiR5))
            {
                commandDescriptor.responseType = SdResponseType.R5;
            }

            if (flags.HasFlag(MmcFlags.ResponseR6))
            {
                commandDescriptor.responseType = SdResponseType.R6;
            }

            byte[] commandB = new byte[commandData.size + commandData.protocolArgumentSize +
                                       commandData.deviceDataBufferSize];

            Array.Copy(buffer, 0, commandB, commandData.size + commandData.protocolArgumentSize, buffer.Length);
            IntPtr hBuf = Marshal.AllocHGlobal(commandB.Length);

            Marshal.StructureToPtr(commandData, hBuf, true);
            var descriptorOffset = IntPtr.Add(hBuf, commandData.size);

            Marshal.StructureToPtr(commandDescriptor, descriptorOffset, true);
            Marshal.Copy(hBuf, commandB, 0, commandB.Length);
            Marshal.FreeHGlobal(hBuf);

            int      error = 0;
            DateTime start = DateTime.Now;

            sense = !Extern.DeviceIoControl(fd, WindowsIoctl.IoctlSffdiskDeviceCommand, commandB, (uint)commandB.Length,
                                            commandB, (uint)commandB.Length, out _, IntPtr.Zero);

            DateTime end = DateTime.Now;

            if (sense)
            {
                error = Marshal.GetLastWin32Error();
            }

            buffer = new byte[blockSize * blocks];
            Buffer.BlockCopy(commandB, commandB.Length - buffer.Length, buffer, 0, buffer.Length);

            response = new uint[4];
            duration = (end - start).TotalMilliseconds;

            return(error);
        }
Пример #45
0
 internal static extern bool CloseHandle(SafeFileHandle hDevice);
        public static IList <Win32StreamInfo> ListStreams(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath");
            }
            if (-1 != filePath.IndexOfAny(Path.GetInvalidPathChars()))
            {
                throw new ArgumentException(Resources.Error_InvalidFileChars, "filePath");
            }

            var result = new List <Win32StreamInfo>();

            using (SafeFileHandle hFile = SafeCreateFile(filePath, NativeFileAccess.GenericRead, FileShare.Read, IntPtr.Zero, FileMode.Open, NativeFileFlags.BackupSemantics, IntPtr.Zero))
                using (var hName = new StreamName())
                {
                    if (!hFile.IsInvalid)
                    {
                        var    streamId           = new Win32StreamId();
                        int    dwStreamHeaderSize = Marshal.SizeOf(streamId);
                        bool   finished           = false;
                        IntPtr context            = IntPtr.Zero;
                        int    bytesRead;
                        string name;

                        try
                        {
                            while (!finished)
                            {
                                // Read the next stream header:
                                if (!BackupRead(hFile, ref streamId, dwStreamHeaderSize, out bytesRead, false, false, ref context))
                                {
                                    finished = true;
                                }
                                else if (dwStreamHeaderSize != bytesRead)
                                {
                                    finished = true;
                                }
                                else
                                {
                                    // Read the stream name:
                                    if (0 >= streamId.StreamNameSize)
                                    {
                                        name = null;
                                    }
                                    else
                                    {
                                        hName.EnsureCapacity(streamId.StreamNameSize);
                                        if (!BackupRead(hFile, hName.MemoryBlock, streamId.StreamNameSize, out bytesRead, false, false, ref context))
                                        {
                                            name     = null;
                                            finished = true;
                                        }
                                        else
                                        {
                                            // Unicode chars are 2 bytes:
                                            name = hName.ReadStreamName(bytesRead >> 1);
                                        }
                                    }

                                    // Add the stream info to the result:
                                    if (!string.IsNullOrEmpty(name))
                                    {
                                        result.Add(new Win32StreamInfo
                                        {
                                            StreamType       = (FileStreamType)streamId.StreamId,
                                            StreamAttributes = (FileStreamAttributes)streamId.StreamAttributes,
                                            StreamSize       = streamId.Size.ToInt64(),
                                            StreamName       = name
                                        });
                                    }

                                    // Skip the contents of the stream:
                                    int bytesSeekedLow, bytesSeekedHigh;
                                    if (!finished && !BackupSeek(hFile, streamId.Size.Low, streamId.Size.High, out bytesSeekedLow, out bytesSeekedHigh, ref context))
                                    {
                                        finished = true;
                                    }
                                }
                            }
                        }
                        finally
                        {
                            // Abort the backup:
                            BackupRead(hFile, hName.MemoryBlock, 0, out bytesRead, true, false, ref context);
                        }
                    }
                }

            return(result);
        }
Пример #47
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(SafeFileHandle hDevInfo,
                                                           ref DeviceInterfaceData deviceInterfaceData,
                                                           IntPtr deviceInterfaceDetailData,
                                                           uint deviceInterfaceDetailDataSize,
                                                           ref uint requiredSize,
                                                           IntPtr deviceInfoData);
 private static extern bool GetFileSizeEx(SafeFileHandle handle, out LargeInteger size);
Пример #49
0
 internal static extern bool DeviceIoControl(SafeFileHandle hDevice, WindowsIoctl ioControlCode,
                                             byte[]         inBuffer,
                                             uint nInBufferSize, byte[] outBuffer,
                                             uint nOutBufferSize,
                                             out uint pBytesReturned, IntPtr overlapped);
Пример #50
0
 public static extern bool SetupDiDestroyDeviceInfoList(SafeFileHandle hDevInfo);
Пример #51
0
    private void initDevice(string devicePath)
    {
        deviceConnected = false;

        //create file handles using CT_CreateFile
        handle = Kernel32.CreateFile(devicePath, Kernel32.GENERIC_READ | Kernel32.GENERIC_WRITE, Kernel32.FILE_SHARE_READ | Kernel32.FILE_SHARE_WRITE, IntPtr.Zero, Kernel32.OPEN_EXISTING, 0, IntPtr.Zero);

        //get capabilites - use getPreParsedData, and getCaps
        //store the reportlengths
        IntPtr ptrToPreParsedData = new IntPtr();

        HID.HidD_GetPreparsedData(handle, ref ptrToPreParsedData);

        capabilities = new HIDP_CAPS();
        HID.HidP_GetCaps(ptrToPreParsedData, ref capabilities);

        HIDD_ATTRIBUTES attributes = new HIDD_ATTRIBUTES();

        HID.HidD_GetAttributes(handle, ref attributes);

        string productName = "";
        string SN          = "";
        string manfString  = "";
        IntPtr buffer      = Marshal.AllocHGlobal(126);//max alloc for string;

        if (HID.HidD_GetProductString(handle, buffer, 126))
        {
            productName = Marshal.PtrToStringAuto(buffer);
        }
        if (HID.HidD_GetSerialNumberString(handle, buffer, 126))
        {
            SN = Marshal.PtrToStringAuto(buffer);
        }
        if (HID.HidD_GetManufacturerString(handle, buffer, 126))
        {
            manfString = Marshal.PtrToStringAuto(buffer);
        }
        Marshal.FreeHGlobal(buffer);

        //Call freePreParsedData to release some stuff
        HID.HidD_FreePreparsedData(ref ptrToPreParsedData);

        if (handle.IsInvalid)
        {
            return;
        }

        deviceConnected = true;

        //If connection was sucsessful, record the values in a global struct
        productInfo                      = new InterfaceDetails();
        productInfo.devicePath           = devicePath;
        productInfo.manufacturer         = manfString;
        productInfo.product              = productName;
        productInfo.serialNumber         = SN;
        productInfo.PID                  = (ushort)attributes.ProductID;
        productInfo.VID                  = (ushort)attributes.VendorID;
        productInfo.versionNumber        = (ushort)attributes.VersionNumber;
        productInfo.IN_reportByteLength  = (int)capabilities.InputReportByteLength;
        productInfo.OUT_reportByteLength = (int)capabilities.OutputReportByteLength;
    }
Пример #52
0
 public static extern bool SetupDiEnumDeviceInterfaces(SafeFileHandle hDevInfo,
                                                       IntPtr devInfo,
                                                       ref Guid interfaceClassGuid,
                                                       uint memberIndex,
                                                       ref DeviceInterfaceData deviceInterfaceData);
Пример #53
0
        private string Prompt(string prompt, bool echo)
        {
            var fileAccessFlags = FileAccess.GenericRead
                                  | FileAccess.GenericWrite;
            var fileAttributes          = FileAttributes.Normal;
            var fileCreationDisposition = FileCreationDisposition.OpenExisting;
            var fileShareFlags          = FileShare.Read
                                          | FileShare.Write;

            using (SafeFileHandle stdout = Kernel32.CreateFile(fileName: ConsoleOutName,
                                                               desiredAccess: fileAccessFlags,
                                                               shareMode: fileShareFlags,
                                                               securityAttributes: IntPtr.Zero,
                                                               creationDisposition: fileCreationDisposition,
                                                               flagsAndAttributes: fileAttributes,
                                                               templateFile: IntPtr.Zero))
                using (SafeFileHandle stdin = Kernel32.CreateFile(fileName: ConsoleInName,
                                                                  desiredAccess: fileAccessFlags,
                                                                  shareMode: fileShareFlags,
                                                                  securityAttributes: IntPtr.Zero,
                                                                  creationDisposition: fileCreationDisposition,
                                                                  flagsAndAttributes: fileAttributes,
                                                                  templateFile: IntPtr.Zero))
                {
                    string input;
                    var    sb      = new StringBuilder(BufferReadSize);
                    uint   read    = 0;
                    uint   written = 0;

                    if (stdin.IsInvalid || stdout.IsInvalid)
                    {
                        _trace.WriteLine("Not a TTY, abandoning prompt.");
                        return(null);
                    }

                    // Prompt the user
                    sb.Append($"{prompt}: ");
                    if (!Kernel32.WriteConsole(buffer: sb,
                                               consoleOutputHandle: stdout,
                                               numberOfCharsToWrite: (uint)sb.Length,
                                               numberOfCharsWritten: out written,
                                               reserved: IntPtr.Zero))
                    {
                        Win32Error.ThrowIfError(Marshal.GetLastWin32Error(), "Failed to write prompt text");
                    }

                    sb.Clear();

                    // Read input from the user
                    using (new TtyContext(_trace, stdin, echo))
                    {
                        if (!Kernel32.ReadConsole(buffer: sb,
                                                  consoleInputHandle: stdin,
                                                  numberOfCharsToRead: BufferReadSize,
                                                  numberOfCharsRead: out read,
                                                  reserved: IntPtr.Zero))
                        {
                            Win32Error.ThrowIfError(Marshal.GetLastWin32Error(), "Unable to read prompt input from standard input");
                        }

                        // Record input from the user into local storage, stripping any EOL chars
                        input = sb.ToString(0, (int)read);
                        input = input.Trim('\n', '\r').Trim('\n');

                        sb.Clear();
                    }

                    // Write the final newline to stdout manually if we had disabled echo
                    if (!echo)
                    {
                        sb.Append(Environment.NewLine);
                        if (!Kernel32.WriteConsole(buffer: sb,
                                                   consoleOutputHandle: stdout,
                                                   numberOfCharsToWrite: (uint)sb.Length,
                                                   numberOfCharsWritten: out written,
                                                   reserved: IntPtr.Zero))
                        {
                            Win32Error.ThrowIfError(Marshal.GetLastWin32Error(), "Failed to write final newline in secret prompting");
                        }
                    }

                    return(input);
                }
        }
Пример #54
0
    public static InterfaceDetails[] getConnectedDevices()
    {
        InterfaceDetails[] devices = new InterfaceDetails[0];

        //Create structs to hold interface information
        SP_DEVINFO_DATA devInfo = new SP_DEVINFO_DATA();

        devInfo.cbSize = (uint)Marshal.SizeOf(devInfo);
        SP_DEVICE_INTERFACE_DATA devIface = new SP_DEVICE_INTERFACE_DATA();

        devIface.cbSize = (uint)(Marshal.SizeOf(devIface));

        Guid G = new Guid();

        HID.HidD_GetHidGuid(ref G); //Get the guid of the HID device class

        IntPtr deviceInfo = SetupAPI.SetupDiGetClassDevs(ref G, IntPtr.Zero, IntPtr.Zero, SetupAPI.DIGCF_DEVICEINTERFACE | SetupAPI.DIGCF_PRESENT);
        //Loop through all available entries in the device list, until false
        int j = 0;

        while (true)
        {
            if (!SetupAPI.SetupDiEnumDeviceInterfaces(deviceInfo, IntPtr.Zero, ref G, (uint)j, ref devIface))
            {
                break;
            }
            uint   requiredSize = 0;
            IntPtr detailMemory = Marshal.AllocHGlobal((int)requiredSize);
            SP_DEVICE_INTERFACE_DETAIL_DATA functionClassDeviceData = (SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(detailMemory, typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
            functionClassDeviceData.cbSize = Marshal.SizeOf(functionClassDeviceData);
            if (!SetupAPI.SetupDiGetDeviceInterfaceDetail(deviceInfo, ref devIface, ref functionClassDeviceData, requiredSize, out requiredSize, ref devInfo))
            {
                Marshal.FreeHGlobal(detailMemory);
                break;
            }
            string devicePath = functionClassDeviceData.DevicePath;
            Marshal.FreeHGlobal(detailMemory);

            //create file handles using CT_CreateFile
            SafeFileHandle tempHandle = Kernel32.CreateFile(devicePath, Kernel32.GENERIC_READ | Kernel32.GENERIC_WRITE, Kernel32.FILE_SHARE_READ | Kernel32.FILE_SHARE_WRITE,
                                                            IntPtr.Zero, Kernel32.OPEN_EXISTING, 0, IntPtr.Zero);

            //get capabilites - use getPreParsedData, and getCaps
            //store the reportlengths
            IntPtr ptrToPreParsedData = new IntPtr();
            bool   ppdSucsess         = HID.HidD_GetPreparsedData(tempHandle, ref ptrToPreParsedData);
            if (!ppdSucsess)
            {
                continue;
            }

            HIDP_CAPS capabilities = new HIDP_CAPS();
            HID.HidP_GetCaps(ptrToPreParsedData, ref capabilities);

            HIDD_ATTRIBUTES attributes = new HIDD_ATTRIBUTES();
            HID.HidD_GetAttributes(tempHandle, ref attributes);

            string    productName = "";
            string    SN          = "";
            string    manfString  = "";
            const int bufferLen   = 128;
            IntPtr    buffer      = Marshal.AllocHGlobal(bufferLen);
            if (HID.HidD_GetProductString(tempHandle, buffer, bufferLen))
            {
                productName = Marshal.PtrToStringAuto(buffer);
            }
            if (HID.HidD_GetSerialNumberString(tempHandle, buffer, bufferLen))
            {
                SN = Marshal.PtrToStringAuto(buffer);
            }
            if (HID.HidD_GetManufacturerString(tempHandle, buffer, bufferLen))
            {
                manfString = Marshal.PtrToStringAuto(buffer);
            }
            Marshal.FreeHGlobal(buffer);

            //Call freePreParsedData to release some stuff
            HID.HidD_FreePreparsedData(ref ptrToPreParsedData);

            //If connection was sucsessful, record the values in a global struct
            InterfaceDetails productInfo = new InterfaceDetails();
            productInfo.devicePath           = devicePath;
            productInfo.manufacturer         = manfString;
            productInfo.product              = productName;
            productInfo.PID                  = (ushort)attributes.ProductID;
            productInfo.VID                  = (ushort)attributes.VendorID;
            productInfo.versionNumber        = (ushort)attributes.VersionNumber;
            productInfo.IN_reportByteLength  = (int)capabilities.InputReportByteLength;
            productInfo.OUT_reportByteLength = (int)capabilities.OutputReportByteLength;
            productInfo.serialNumber         = SN; //Check that serial number is actually a number

            int newSize = devices.Length + 1;
            Array.Resize(ref devices, newSize);
            devices[newSize - 1] = productInfo;
            ++j;
        }
        SetupAPI.SetupDiDestroyDeviceInfoList(deviceInfo);

        return(devices);
    }
Пример #55
0
 public static extern bool DeviceIoControl(SafeFileHandle device,
                                           IOControlCode ioControlCode,
                                           [MarshalAs(UnmanagedType.AsAny)][In] object inBuffer,
                                           uint inBufferSize,
                                           [MarshalAs(UnmanagedType.AsAny)][Out] object outBuffer,
                                           uint nOutBufferSize, out uint bytesReturned, IntPtr overlapped);
Пример #56
0
 public UnbufferedFileStream(SafeFileHandle fileHandle, FileAccess access, int bufferSize, bool isAsync)
     : base(fileHandle, access, bufferSize, isAsync) =>
     this.fileHandle = fileHandle;
Пример #57
0
 static extern bool SetHandleInformation(SafeFileHandle hObject, HANDLE_FLAGS dwMask, uint flags);
Пример #58
0
 public static extern bool GetFileInformationByHandle(SafeFileHandle handle, out ByHandleFileInformation lpFileInformation);
Пример #59
0
 private static extern bool DuplicateHandle(SafeFileHandle hSourceProcessHandle, SafeFileHandle hSourceHandle, SafeFileHandle hTargetProcessHandle, out SafeFileHandle lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
Пример #60
0
        // There is an issue launching Cygwin apps that if a process is launched using a bitness mismatched console,
        // process launch will fail. To avoid that, launch cygpath with its own console. This requires calling CreateProcess
        // directly because the creation flags are not exposed in System.Diagnostics.Process.
        //
        // Return true if successful. False otherwise.
        private bool LaunchCygPathAndReadResult(string cygwinPath, string miDebuggerPath, out string windowsPath)
        {
            windowsPath = "";

            if (String.IsNullOrEmpty(miDebuggerPath))
            {
                return(false);
            }

            string cygpathPath = Path.Combine(Path.GetDirectoryName(miDebuggerPath), "cygpath.exe");

            if (!File.Exists(cygpathPath))
            {
                return(false);
            }

            List <IDisposable> disposableHandles = new List <IDisposable>();

            try
            {
                // Create the anonymous pipe that will act as stdout for the cygpath process
                SECURITY_ATTRIBUTES pPipeSec = new SECURITY_ATTRIBUTES();
                pPipeSec.bInheritHandle = 1;
                SafeFileHandle stdoutRead;
                SafeFileHandle stdoutWrite;
                if (!CreatePipe(out stdoutRead, out stdoutWrite, ref pPipeSec, 4096))
                {
                    Debug.Fail("Unexpected failure CreatePipe in LaunchCygPathAndReadResult");
                    return(false);
                }
                SetHandleInformation(stdoutRead, HANDLE_FLAGS.INHERIT, 0);
                disposableHandles.Add(stdoutRead);
                disposableHandles.Add(stdoutWrite);


                const int   STARTF_USESTDHANDLES = 0x00000100;
                const int   STARTF_USESHOWWINDOW = 0x00000001;
                const int   SW_HIDE     = 0;
                STARTUPINFO startupInfo = new STARTUPINFO();
                startupInfo.dwFlags     = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
                startupInfo.hStdOutput  = stdoutWrite;
                startupInfo.wShowWindow = SW_HIDE;
                startupInfo.cb          = Marshal.SizeOf(startupInfo);

                PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION();
                SECURITY_ATTRIBUTES processSecurityAttributes = new SECURITY_ATTRIBUTES();
                SECURITY_ATTRIBUTES threadSecurityAttributes  = new SECURITY_ATTRIBUTES();

                processSecurityAttributes.nLength = Marshal.SizeOf(processSecurityAttributes);
                threadSecurityAttributes.nLength  = Marshal.SizeOf(threadSecurityAttributes);

                const uint DETACHED_PROCESS = 0x00000008;
                uint       flags            = DETACHED_PROCESS;
                // ex: "C:\\cygwin64\\bin\\cygpath.exe -w " + cygwinPath,
                string command = String.Concat(cygpathPath, " -w ", cygwinPath);
                if (!CreateProcess(
                        null,
                        command,
                        ref processSecurityAttributes,
                        ref threadSecurityAttributes,
                        true,
                        flags,
                        IntPtr.Zero,
                        null,
                        ref startupInfo,
                        out processInfo
                        ))
                {
                    Debug.Fail("Launching cygpath for source mapping failed");
                    return(false);
                }
                SafeFileHandle processSH = new SafeFileHandle(processInfo.hProcess, true);
                SafeFileHandle threadSH  = new SafeFileHandle(processInfo.hThread, true);
                disposableHandles.Add(processSH);
                disposableHandles.Add(threadSH);

                const int timeout = 5000;
                if (WaitForSingleObject(processInfo.hProcess, timeout) != 0)
                {
                    Debug.Fail("cygpath failed to map source file.");
                    return(false);
                }

                uint exitCode = 0;
                if (!GetExitCodeProcess(processInfo.hProcess, out exitCode))
                {
                    Debug.Fail("cygpath failed to get exit code from cygpath.");
                    return(false);
                }

                if (exitCode != 0)
                {
                    Debug.Fail("cygpath returned error exit code.");
                    return(false);
                }

                FileStream   fs = new FileStream(stdoutRead, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                windowsPath = sr.ReadLine();
            }
            finally
            {
                foreach (IDisposable h in disposableHandles)
                {
                    h.Dispose();
                }
            }

            return(true);
        }