Exemplo n.º 1
0
 public void PrintScoresMatrix(SafeFileHandle handle)
     {
     if (this.nativeDesignScorer != IntPtr.Zero)
         {
         NadirHelper.PrintScoresMatrix(this.nativeDesignScorer, handle.DangerousGetHandle());
         }
     }
Exemplo n.º 2
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();
                }
            }
        }
Exemplo n.º 3
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);
 }
Exemplo n.º 4
0
        private static void FSync(SafeFileHandle handle)
        {
#if !__MonoCS__ && !USE_UNIX_IO
            WinNative.FlushFileBuffers(handle);
#else
            Syscall.fsync(handle.DangerousGetHandle().ToInt32());
#endif
        }
Exemplo n.º 5
0
			internal Module(ForeignPtr @base, SafeFileHandle handle)
			{
				Contract.Assert(@base.Address> 0);
				this.@base = @base;
				this.handle = handle;

				if (!handle.IsInvalid)
					this.imagePath = Kernel32.GetFinalPathNameByHandle(handle.DangerousGetHandle(), 0);
			}
Exemplo n.º 6
0
        public LocalStorageDevice(string filename, bool enablePrivileges = false,
                                  bool useIoCompletionPort = false, bool unbuffered = false, bool deleteOnClose = false)
        {
            this.filename            = filename;
            this.enablePrivileges    = enablePrivileges;
            this.useIoCompletionPort = useIoCompletionPort;

            if (enablePrivileges)
            {
                Native32.EnableProcessPrivileges();
            }

            Native32.GetDiskFreeSpace(filename.Substring(0, 3),
                                      out lpSectorsPerCluster,
                                      out lpBytesPerSector,
                                      out lpNumberOfFreeClusters,
                                      out lpTotalNumberOfClusters);

            uint fileAccess = Native32.GENERIC_READ | Native32.GENERIC_WRITE;
            //            uint fileShare = unchecked(((uint)FileShare.ReadWrite & ~(uint)FileShare.Inheritable));
            uint fileShare    = unchecked (((uint)FileShare.Read & ~(uint)FileShare.Inheritable));
            uint fileCreation = unchecked ((uint)FileMode.OpenOrCreate);
            uint fileFlags    = Native32.FILE_FLAG_OVERLAPPED;

            if (unbuffered)
            {
                fileFlags = fileFlags | Native32.FILE_FLAG_NO_BUFFERING;
            }

            if (deleteOnClose)
            {
                fileFlags = fileFlags | Native32.FILE_FLAG_DELETE_ON_CLOSE;
            }

            logHandle = Native32.CreateFileW(filename,
                                             fileAccess,
                                             fileShare,
                                             IntPtr.Zero,
                                             fileCreation,
                                             fileFlags,
                                             IntPtr.Zero);

            if (enablePrivileges)
            {
                Native32.EnableVolumePrivileges(filename, logHandle);
            }

            if (useIoCompletionPort)
            {
                ioCompletionPort = Native32.CreateIoCompletionPort(
                    logHandle,
                    IntPtr.Zero,
                    (uint)logHandle.DangerousGetHandle().ToInt64(),
                    0);
            }
            ThreadPool.BindHandle(logHandle);
        }
Exemplo n.º 7
0
        void CancelIo()
        {
            bool ok = NativeMethods.CancelIo(handle.DangerousGetHandle());

            if (!ok)
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and
        /// (offset + count - 1) replaced by the bytes read from the current source. </param>
        /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream. </param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns></returns>
        private int InternalRead(byte[] buffer, int offset, int count)
        {
            int bytesRead = 0;
            var bufBytes  = new byte[count];

            if (!ReadFile(handleValue.DangerousGetHandle(), bufBytes, count, ref bytesRead, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            for (int i = 0; i < bytesRead; i++)
            {
                buffer[offset + i] = bufBytes[i];
            }

            position += count;

            return(bytesRead);
        }
Exemplo n.º 9
0
        /// <summary>
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and
        /// (offset + count - 1) replaced by the bytes read from the current source. </param>
        /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream. </param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns></returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            int BytesRead = 0;
            var BufBytes  = new byte[count];

            if (!ReadFile(handleValue.DangerousGetHandle(), BufBytes, count, ref BytesRead, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            for (int i = 0; i < BytesRead; i++)
            {
                buffer[offset + i] = BufBytes[i];
            }

            _Position += count;

            return(BytesRead);
        }
Exemplo n.º 10
0
        public void Start()
        {
            HIDImports.SP_DEVICE_INTERFACE_DATA spDeviceInterfaceData = new HIDImports.SP_DEVICE_INTERFACE_DATA()
            {
                cbSize = Marshal.SizeOf(typeof(HIDImports.SP_DEVICE_INTERFACE_DATA))
            };

            if (stream != null)
            {
                throw new InvalidOperationException("Connected to a different stream already!");
            }

            HIDImports.HidD_GetHidGuid(out Guid guid);
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, 0x10);

            int num = 0;

            while (HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, num++, ref spDeviceInterfaceData))
            {
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA
                {
                    cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5)
                };

                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref spDeviceInterfaceData, IntPtr.Zero, 0, out uint requiredSize, IntPtr.Zero);
                if (HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref spDeviceInterfaceData, ref deviceInterfaceDetailData, requiredSize, out requiredSize, IntPtr.Zero))
                {
                    HIDImports.HIDD_ATTRIBUTES hiddAttributes = new HIDImports.HIDD_ATTRIBUTES()
                    {
                        Size = Marshal.SizeOf(typeof(HIDImports.HIDD_ATTRIBUTES))
                    };

                    SafeFileHandle handle = HIDImports.CreateFile(deviceInterfaceDetailData.DevicePath, FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    if (HIDImports.HidD_GetAttributes(handle.DangerousGetHandle(), ref hiddAttributes))
                    {
                        if (IsAppleWirelessKeyboard(hiddAttributes.VendorID, hiddAttributes.ProductID))
                        {
                            stream = new FileStream(handle, FileAccess.Read, 0x16, true);
                        }
                        else
                        {
                            handle.Close();
                        }
                    }
                }
            }

            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            if (stream != null)
            {
                byte[] buffer = new byte[0x16];
                stream.BeginRead(buffer, 0, buffer.Length, SpecialKeyStateChanged, buffer);
            }
        }
Exemplo n.º 11
0
        public static string GetTarget(string path)
        {
            SymbolicLinkReparseData reparseDataBuffer;

            using (SafeFileHandle fileHandle = GetFileHandle(path))
            {
                if (fileHandle.IsInvalid)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
#if NET35
                int outBufferSize = Marshal.SizeOf(typeof(SymbolicLinkReparseData));
#else
                int outBufferSize = Marshal.SizeOf <SymbolicLinkReparseData>();
#endif
                IntPtr outBuffer = IntPtr.Zero;
                try
                {
                    outBuffer = Marshal.AllocHGlobal(outBufferSize);
                    bool success = DeviceIoControl(
                        fileHandle.DangerousGetHandle(), ioctlCommandGetReparsePoint, IntPtr.Zero, 0,
                        outBuffer, outBufferSize, out int bytesReturned, IntPtr.Zero);

                    fileHandle.Dispose();

                    if (!success)
                    {
                        if (((uint)Marshal.GetHRForLastWin32Error()) == pathNotAReparsePointError)
                        {
                            return(null);
                        }
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                    }

#if NET35
                    reparseDataBuffer = (SymbolicLinkReparseData)Marshal.PtrToStructure(
                        outBuffer, typeof(SymbolicLinkReparseData));
#else
                    reparseDataBuffer = Marshal.PtrToStructure <SymbolicLinkReparseData>(outBuffer);
#endif
                }
                finally
                {
                    Marshal.FreeHGlobal(outBuffer);
                }
            }
            if (reparseDataBuffer.ReparseTag != symLinkTag)
            {
                return(null);
            }

            string target = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer,
                                                       reparseDataBuffer.PrintNameOffset, reparseDataBuffer.PrintNameLength);

            return(target);
        }
Exemplo n.º 12
0
        private static ByHandleFileInformation?MY_GetFileInfo(SafeFileHandle directoryHandle)
        {
            ByHandleFileInformation objectFileInfo;

            if (!GetFileInformationByHandle(directoryHandle.DangerousGetHandle(), out objectFileInfo))
            {
                return(null);
            }
            return(objectFileInfo);
        }
Exemplo n.º 13
0
        internal static void SetConsoleCursorPosition(SafeFileHandle handle, dotCmd.Native.ConsoleHostNativeMethods.COORD cursorPosition)
        {
            bool result = ConsoleHostNativeMethods.SetConsoleCursorPosition(handle.DangerousGetHandle(), cursorPosition);

            if (result == false)
            {
                int err = Marshal.GetLastWin32Error();
                throw CreateException("Cannot set the curor position", err);
            }
        }
Exemplo n.º 14
0
            private IntPtr CreateDirectoryHandle(string fileName, string subDirectory)
            {
                SafeFileHandle safeHandle = DirectoryMethods.CreateDirectoryHandle(subDirectory);

                // Ideally we'd never wrap in a SafeFileHandle, but for now this is reasonable.
                IntPtr handle = safeHandle.DangerousGetHandle();

                safeHandle.SetHandleAsInvalid();
                return(handle);
            }
Exemplo n.º 15
0
        public static bool InternalDelete(string path, LinkType type)
        {
            if (type == LinkType.None)
            {
                return(false);
            }
            if (!Directory.Exists(path))
            {
                if (File.Exists(path))
                {
                    throw new IOException("Path is not a junction point.");
                }

                return(false);
            }

            using (SafeFileHandle handle = NativeMethods.OpenReparsePoint(path, NativeMethods.EFileAccess.GenericWrite))
            {
                NativeMethods.REPARSE_DATA_BUFFER reparseDataBuffer = new NativeMethods.REPARSE_DATA_BUFFER();

                reparseDataBuffer.ReparseTag        = type == LinkType.Junction ? NativeMethods.IO_REPARSE_TAG_MOUNT_POINT : NativeMethods.IO_REPARSE_TAG_SYM_LINK;
                reparseDataBuffer.ReparseDataLength = 0;
                reparseDataBuffer.PathBuffer        = new byte[0x3ff0];

                int    inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                IntPtr inBuffer     = Marshal.AllocHGlobal(inBufferSize);
                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int  bytesReturned;
                    bool result = NativeMethods.DeviceIoControl(handle.DangerousGetHandle(), NativeMethods.FSCTL_DELETE_REPARSE_POINT,
                                                                inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                    {
                        NativeMethods.ThrowLastWin32Error("Unable to delete junction point.");
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }

                try
                {
                    Directory.Delete(path);
                    return(true);
                }
                catch (IOException ex)
                {
                    throw new IOException("Unable to delete junction point.", ex);
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a junction point from the specified directory to the specified target directory.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        /// <param name="targetDir">The target directory</param>
        /// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param>
        /// <exception cref="IOException">Thrown when the junction point could not be created or when
        /// an existing directory was found and <paramref name="overwrite" /> if false</exception>
        public static void Create(string junctionPoint, string targetDir, bool overwrite)
        {
            targetDir = Path.GetFullPath(targetDir);

            if (!Directory.Exists(targetDir))
            {
                throw new IOException("Target path does not exist or is not a directory.");
            }

            if (Directory.Exists(junctionPoint))
            {
                if (!overwrite)
                {
                    throw new IOException("Directory already exists and overwrite parameter is false.");
                }
            }
            else
            {
                Directory.CreateDirectory(junctionPoint);
            }

            using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite)) {
                byte[] targetDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(targetDir));

                REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER();

                reparseDataBuffer.ReparseTag           = IO_REPARSE_TAG_MOUNT_POINT;
                reparseDataBuffer.ReparseDataLength    = (ushort)(targetDirBytes.Length + 12);
                reparseDataBuffer.SubstituteNameOffset = 0;
                reparseDataBuffer.SubstituteNameLength = (ushort)targetDirBytes.Length;
                reparseDataBuffer.PrintNameOffset      = (ushort)(targetDirBytes.Length + 2);
                reparseDataBuffer.PrintNameLength      = 0;
                reparseDataBuffer.PathBuffer           = new byte[0x3ff0];
                Array.Copy(targetDirBytes, reparseDataBuffer.PathBuffer, targetDirBytes.Length);

                int    inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                IntPtr inBuffer     = Marshal.AllocHGlobal(inBufferSize);

                try {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int  bytesReturned;
                    bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT,
                                                  inBuffer, targetDirBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                    {
                        ThrowLastWin32Error("Unable to create junction point.");
                    }
                }
                finally {
                    Marshal.FreeHGlobal(inBuffer);
                }
            }
        }
Exemplo n.º 17
0
        public override void Write(byte[] buffer, int offset, int count)
        {
            System.Diagnostics.Debug.WriteLine("Writing: " + BitConverter.ToString(buffer));

            if (UseFullReportSize)
            {
                var buf = new byte[22];
                buffer.CopyTo(buf, 0);
                buffer = buf;
            }

            lock (_writerBlock)
            {
                if (UseWriteFile)
                {
                    uint written       = 0;
                    var  nativeOverlap = new NativeOverlapped();

                    // Provide a reset event that will get set once asynchronouse writing has completed
                    var resetEvent = new ManualResetEvent(false);
                    nativeOverlap.EventHandle = resetEvent.SafeWaitHandle.DangerousGetHandle();

                    // success is most likely to be false which can mean it is being completed asynchronously, in this case we need to wait
                    var  dh      = _fileHandle.DangerousGetHandle();
                    bool success = false;
                    try
                    {
                        success = WriteFile(dh, buffer, (uint)buffer.Length, out written, ref nativeOverlap);
                    }
                    catch
                    {
                        System.Diagnostics.Debug.WriteLine("caught!");
                    }
                    uint error = GetLastError();

                    // Wait for the async operation to complete
                    if (!success && error == 997)
                    {
                        resetEvent.WaitOne(8000);
                    }

                    // Example for async and callback
                    //bool success = WriteFileEx(_fileHandle.DangerousGetHandle(), buffer, out written, ref nativeOverlap,
                    //    (errorCode, bytesTransfered, nativeOver) =>
                    //{
                    //    System.Diagnostics.Debug.Write(errorCode);
                    //});
                }
                else
                {
                    _fileStream?.Write(buffer, 0, buffer.Length);
                    // Should we even bother using SetOutputReport?
                }
            }
        }
Exemplo n.º 18
0
        internal static int GetFileType(SafeFileHandle handle)
        {
            var stdId = handle.DangerousGetHandle().ToInt32();

            if (stdId == STD_OUTPUT_HANDLE || stdId == STD_ERROR_HANDLE)
            {
                return(FILE_TYPE_CHAR);
            }

            return(FILE_TYPE_DISK);
        }
        protected override SafeFileHandle OpenFileHandle(string path, FileAccess fileAccess)
        {
            SafeFileHandle originHandle = base.OpenFileHandle(path, fileAccess);

            // Create handle by ptr to force that `SafeFileHandle.Path` is `null`
            SafeFileHandle newHandle = new(originHandle.DangerousGetHandle(), true);

            originHandle.SetHandleAsInvalid();

            return(newHandle);
        }
Exemplo n.º 20
0
        public static bool Build_Volume_Mapping(SafeFileHandle roothandle, Win32Api.USN_JOURNAL_DATA currentUsnState, Action <Win32Api.UsnEntry> func)
        {
            Debug.WriteLine("Starting Build_Volume_Mapping");

            DateTime startTime = DateTime.Now;

            Win32Api.MFT_ENUM_DATA med;
            med.StartFileReferenceNumber = 0;
            med.LowUsn  = 0;
            med.HighUsn = currentUsnState.NextUsn;

            using (var med_struct = new StructWrapper(med))
                using (var rawdata = new Raw_Array_Wrapper(BUF_LEN))
                {
                    uint outBytesReturned = 0;

                    while (Win32Api.DeviceIoControl(
                               roothandle.DangerousGetHandle(),
                               Win32Api.FSCTL_ENUM_USN_DATA,
                               med_struct.Ptr,
                               med_struct.Size,
                               rawdata.Ptr,
                               rawdata.Size,
                               out outBytesReturned,
                               IntPtr.Zero))
                    {
                        outBytesReturned = outBytesReturned - sizeof(Int64);
                        IntPtr pUsnRecord = System.IntPtr.Add(rawdata.Ptr, sizeof(Int64));//need to skip 8 bytes because the first 8 bytes are to a usn number, which isnt in the structure
                        while (outBytesReturned > 60)
                        {
                            var usnEntry = new Win32Api.UsnEntry(pUsnRecord);
                            pUsnRecord = System.IntPtr.Add(pUsnRecord, (int)usnEntry.RecordLength);
                            func(usnEntry);

                            if (usnEntry.RecordLength > outBytesReturned)
                            {
                                outBytesReturned = 0;// prevent overflow
                            }
                            else
                            {
                                outBytesReturned -= usnEntry.RecordLength;
                            }
                        }
                        Marshal.WriteInt64(med_struct.Ptr, Marshal.ReadInt64(rawdata.Ptr, 0));//read the usn that we skipped and place it into the nextusn
                    }
                    var possiblerror = Marshal.GetLastWin32Error();
                    if (possiblerror < 0)
                    {
                        throw new Win32Exception(possiblerror);
                    }
                }
            Debug.WriteLine("Time took: " + (DateTime.Now - startTime).TotalMilliseconds + "ms");
            return(true);
        }
Exemplo n.º 21
0
        public DeviceInterfaceFile(SafeFileHandle fileHandle, FileStream stream)
        {
            _fileHandle = fileHandle;
            _stream     = stream;

            if (!HidD_GetPreparsedData(fileHandle.DangerousGetHandle(), out _preparsedData))
            {
                var lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(lastError, "HidD_GetPreparsedData failed");
            }
        }
        public unsafe void SetConsoleFont(string FontName, int x, int y)
        {
            NativeMethods.CONSOLE_FONT_INFO_EX newInfo = new NativeMethods.CONSOLE_FONT_INFO_EX();
            newInfo.cbSize     = (uint)Marshal.SizeOf(newInfo);
            newInfo.dwFontSize = new NativeMethods.Coord((short)x, (short)y);
            newInfo.nFont      = 0;
            newInfo.FontWeight = 400;
            newInfo.FontFamily = 48;
            newInfo.FontWeight = 0;
            var ptr = new IntPtr(newInfo.FaceName);

            Marshal.Copy(FontName.ToCharArray(), 0, ptr, FontName.Length);
            NativeMethods.SetCurrentConsoleFontEx(STD_OUT_HND.DangerousGetHandle(), false, ref newInfo);
            var size = GetConsoleFontSize();

            if (size.X != x || size.Y != y)
            {
                throw new Exception("Failed to set Textsize to valid Value");
            }
        }
Exemplo n.º 23
0
        public static int[] FindEV3s()
        {
            Guid guid;
            int  index = 0;

            List <int> devices = new List <int>();


            HidImports.HidD_GetHidGuid(out guid);

            IntPtr hDevInfo = HidImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HidImports.DIGCF_DEVICEINTERFACE | HidImports.DIGCF_PRESENT);

            HidImports.SP_DEVICE_INTERFACE_DATA diData = new HidImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            while (HidImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                if (HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    HidImports.HIDD_ATTRIBUTES attrib = new HidImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    SafeFileHandle handle = HidImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.None /*.ReadWrite*/, IntPtr.Zero, FileMode.Open, 0 /*HidImports.EFileAttributes.Overlapped*/, IntPtr.Zero);

                    if (HidImports.HidD_GetAttributes(handle.DangerousGetHandle(), ref attrib))
                    {
                        if (attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            devices.Add(index);
                        }
                    }
                    handle.Close();
                }
                else
                {
                    throw new Exception("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                index++;
            }

            HidImports.SetupDiDestroyDeviceInfoList(hDevInfo);


            return(devices.ToArray());
        }
Exemplo n.º 24
0
        public static string GetFinalPathNameByHandle(SafeFileHandle fileHandle)
        {
            StringBuilder path   = new StringBuilder(10);
            var           length = GetFinalPathNameByHandle(fileHandle.DangerousGetHandle(), path, path.Capacity, 0);

            if (length != 0 && length + 1 > path.Capacity) //low memory. note: the length is in bytes, and path.Capacity is length of wchar.
            {
                path.Capacity = length + 1;
                length        = GetFinalPathNameByHandle(fileHandle.DangerousGetHandle(), path, path.Capacity, 0);
            }

            if (length == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            else
            {
                return(path.ToString());
            }
        }
Exemplo n.º 25
0
        public void Seek(SafeFileHandle handle, long position, SeekOrigin origin)
        {
            int r;

            do
            {
                r = (int)Syscall.lseek(handle.DangerousGetHandle().ToInt32(), position, SeekFlags.SEEK_SET);
            } while (UnixMarshal.ShouldRetrySyscall(r));

            UnixMarshal.ThrowExceptionForLastErrorIf(r);
        }
Exemplo n.º 26
0
        public void SetFileSize(SafeFileHandle handle, long count)
        {
            int r;

            do
            {
                r = Syscall.ftruncate(handle.DangerousGetHandle().ToInt32(), count);
            } while (UnixMarshal.ShouldRetrySyscall(r));

            UnixMarshal.ThrowExceptionForLastErrorIf(r);
            FSync(handle);
        }
Exemplo n.º 27
0
        private static HidDeviceCapabilities GetDeviceCapabilities(SafeFileHandle hidHandle)
        {
            var capabilities         = default(NativeMethods.HIDP_CAPS);
            var preparsedDataPointer = default(IntPtr);

            if (NativeMethods.HidD_GetPreparsedData(hidHandle.DangerousGetHandle(), ref preparsedDataPointer))
            {
                NativeMethods.HidP_GetCaps(preparsedDataPointer, ref capabilities);
                NativeMethods.HidD_FreePreparsedData(preparsedDataPointer);
            }
            return(new HidDeviceCapabilities(capabilities));
        }
Exemplo n.º 28
0
        private static FileStream OpenFileStream(IntPtr handle)
        {
            var fileHandle = new SafeFileHandle(handle, false);
            var ctorParams = AccessTools.ActualParameters(FileStreamCtor,
                                                          new object[]
            {
                fileHandle, fileHandle.DangerousGetHandle(),
                FileAccess.Write
            });

            return((FileStream)Activator.CreateInstance(typeof(FileStream), ctorParams));
        }
Exemplo n.º 29
0
        public static IntPtr CreateFile(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share)
        {
            SafeFileHandle fileHandle     = CreateFileW(path, getAccessFromAccess(access), getShareFromShare(share), IntPtr.Zero, getDispositionFromMode(mode), 0, IntPtr.Zero);
            int            lastWin32Error = Marshal.GetLastWin32Error();

            if (fileHandle.IsInvalid)
            {
                throw new System.ComponentModel.Win32Exception(lastWin32Error);
            }

            return(fileHandle.DangerousGetHandle());
        }
Exemplo n.º 30
0
        /// <summary>
        /// Creates a junction point from the specified directory to the specified target directory.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="sourceDir">The source directory to alias</param>
        /// <param name="targetDir">The target directory to create</param>
        /// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param>
        /// <exception cref="IOException">Thrown when the junction point could not be created or when
        /// an existing directory was found and <paramref name="overwrite" /> if false</exception>
        public static void CreateJunction(string sourceDir, string targetDir, bool overwrite)
        {
            sourceDir = Path.GetFullPath(sourceDir);

            if (!Directory.Exists(sourceDir))
            {
                throw new IOException($"Source path does not exist or is not a directory.");
            }

            if (Directory.Exists(targetDir))
            {
                throw new IOException($"Directory '{targetDir}' already exists.");
            }

            Directory.CreateDirectory(targetDir);

            using (SafeFileHandle handle = OpenReparsePoint(targetDir, EFileAccess.GenericWrite))
            {
                byte[] sourceDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(sourceDir));

                REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER
                {
                    ReparseTag           = IO_REPARSE_TAG_MOUNT_POINT,
                    ReparseDataLength    = (ushort)(sourceDirBytes.Length + 12),
                    SubstituteNameOffset = 0,
                    SubstituteNameLength = (ushort)sourceDirBytes.Length,
                    PrintNameOffset      = (ushort)(sourceDirBytes.Length + 2),
                    PrintNameLength      = 0,
                    PathBuffer           = new byte[0x3ff0]
                };
                Array.Copy(sourceDirBytes, reparseDataBuffer.PathBuffer, sourceDirBytes.Length);

                int    inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                IntPtr inBuffer     = Marshal.AllocHGlobal(inBufferSize);

                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int  bytesReturned;
                    bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT, inBuffer: inBuffer, nInBufferSize: sourceDirBytes.Length + 20, outBuffer: IntPtr.Zero, nOutBufferSize: 0, pBytesReturned: out bytesReturned, lpOverlapped: IntPtr.Zero);

                    if (!result)
                    {
                        ThrowLastWin32Error($"Unable to create junction point \'{sourceDir}\' -> \'{targetDir}\'.");
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }
            }
        }
Exemplo n.º 31
0
            public CodecIndexInput(FileInfo file, Func <Stream, Stream> applyCodecs)
            {
                try
                {
                    this.file        = file;
                    this.applyCodecs = applyCodecs;
                    if (file.Length == 0)
                    {
                        stream = applyCodecs(Stream.Null);
                        return;
                    }

                    fileHandle = Win32NativeFileMethods.CreateFile(file.FullName,
                                                                   Win32NativeFileAccess.GenericRead,
                                                                   Win32NativeFileShare.Read | Win32NativeFileShare.Write | Win32NativeFileShare.Delete,
                                                                   IntPtr.Zero,
                                                                   Win32NativeFileCreationDisposition.OpenExisting,
                                                                   Win32NativeFileAttributes.RandomAccess,
                                                                   IntPtr.Zero);

                    if (fileHandle.IsInvalid)
                    {
                        const int ERROR_FILE_NOT_FOUND = 2;
                        if (Marshal.GetLastWin32Error() == ERROR_FILE_NOT_FOUND)
                        {
                            throw new FileNotFoundException(file.FullName);
                        }
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not open file " + file.FullName);
                    }

                    mmf = Win32MemoryMapNativeMethods.CreateFileMapping(fileHandle.DangerousGetHandle(), IntPtr.Zero, Win32MemoryMapNativeMethods.FileMapProtection.PageReadonly,
                                                                        0, 0, null);
                    if (mmf == IntPtr.Zero)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not create file mapping for " + file.FullName);
                    }

                    basePtr = Win32MemoryMapNativeMethods.MapViewOfFileEx(mmf,
                                                                          Win32MemoryMapNativeMethods.NativeFileMapAccessType.Read,
                                                                          0, 0, UIntPtr.Zero, null);
                    if (basePtr == null)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not map file " + file.FullName);
                    }

                    stream = applyCodecs(new MmapStream(file.FullName, basePtr, file.Length));
                }
                catch (Exception)
                {
                    Dispose(false);
                    throw;
                }
            }
Exemplo n.º 32
0
        /// <summary>
        /// 创建一个串口通信实例
        /// </summary>
        /// <param name="portName">串口名</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">校验,偶校验(2) 无校验(0) 奇校验(1)</param>
        /// <param name="stopBits">停止位,1停止位(0) 1.5停止位(1) 2停止位(2)</param>
        /// <param name="flowControl">流量控制类型</param>
        public XKserialPort(string portName, int baudRate = 9600, byte parity = 0, byte stopBits = 0, FlowControlType flowControl = FlowControlType.None)
        {
            this.BaudRate    = baudRate;
            this.Parity      = parity;
            this.StopBits    = stopBits;
            this.PortName    = portName;
            this.FlowControl = flowControl;
            overlapped       = new OVERLAPPED();

            Open();                                                   //打开端口

            SetupComm((int)(hPort.DangerousGetHandle()), 1024, 1024); //设置端口缓冲区大小
            if (portName.ToUpper().IndexOf("COM") != -1)
            {
                //如果是串口
                SetTimeOuts();//设置默认超时

                //配置串口参数,波特率,无校验,1位停止位
                DCB dcb = initDCB((int)(hPort.DangerousGetHandle()), BaudRate, Parity, StopBits, flowControl);
                SetCommState((int)(hPort.DangerousGetHandle()), ref dcb);
            }
            //清空缓冲区
            PurgeComm((int)(hPort.DangerousGetHandle()), PURGE_TXCLEAR);

            //关闭端口
            hPort.Close();
        }
Exemplo n.º 33
0
        protected override object[] CreateItems()
        {
            Process curProcess = Process.GetCurrentProcess();

            List <Process> result = new List <Process>();

            foreach (Process process in Process.GetProcesses())
            {
                // Skip ourself
                if (process.Id == curProcess.Id)
                {
                    continue;
                }

                // Skip special PIDs
                if (process.Id == 0 || process.Id == 4)
                {
                    continue;
                }

                // Skip EasyHook services
                string processNameLower = process.ProcessName.ToLower();
                if (processNameLower == "easyhook32svc" || processNameLower == "easyhook64svc")
                {
                    continue;
                }
                // And any oSpy instances
                if (processNameLower == "ospy" || processNameLower == "ospy.vshost")
                {
                    continue;
                }

                // And also 64 bit processes on x64
                if (EasyHook.RemoteHooking.IsX64System)
                {
                    SafeHandle processHandle = new SafeFileHandle(WinApi.OpenProcess(WinApi.PROCESS_QUERY_INFORMATION, false, (uint)process.Id), true);
                    if (!processHandle.IsInvalid)
                    {
                        bool processIs32Bit = false;
                        if (WinApi.IsWow64Process(processHandle.DangerousGetHandle(), out processIs32Bit) && !processIs32Bit)
                        {
                            continue;
                        }
                    }
                }

                result.Add(process);
                processIcons[process] = GetProcessIcon(process);
            }

            return(result.ToArray());
        }
Exemplo n.º 34
0
        /// <summary>
        /// Deletes a junction point at the specified source directory along with the directory itself.
        /// Does nothing if the junction point does not exist.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        public static void Delete(string junctionPoint)
        {
            if (!Directory.Exists(junctionPoint))
            {
                if (File.Exists(junctionPoint))
                {
                    throw new IOException("Path is not a junction point.");
                }

                return;
            }

            using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
            {
                REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER
                {
                    ReparseTag        = IO_REPARSE_TAG_MOUNT_POINT,
                    ReparseDataLength = 0,
                    PathBuffer        = new byte[0x3ff0]
                };


                int    inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                IntPtr inBuffer     = Marshal.AllocHGlobal(inBufferSize);
                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int  bytesReturned;
                    bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT,
                                                  inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                    {
                        ThrowLastWin32Error("Unable to delete junction point.");
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }

                try
                {
                    Directory.Delete(junctionPoint);
                }
                catch (IOException ex)
                {
                    throw new IOException("Unable to delete junction point.", ex);
                }
            }
        }
Exemplo n.º 35
0
        public static void CreateJunction(string link, string target)
        {
            var di = new DirectoryInfo(link);

            if (di.Exists)
            {
                if (di.GetFiles().Length > 0 || di.GetDirectories().Length > 0)
                {
                    throw new IOException("Directory already exists and is not empty");
                }
            }
            else
            {
                di.Create();
            }

            using (SafeFileHandle handle = OpenReparsePoint(link, EFileAccess.GenericWrite))
            {
                byte[] linkbytes = Encoding.Unicode.GetBytes(VIRTUAL_NTFS_PATH_PREFIX + Path.GetFullPath(target));

                REPARSE_DATA_BUFFER buffer = new REPARSE_DATA_BUFFER();
                buffer.ReparseTag           = IO_REPARSE_TAG_MOUNT_POINT;
                buffer.ReparseDataLength    = (ushort)(linkbytes.Length + 12);
                buffer.SubstituteNameOffset = 0;
                buffer.SubstituteNameLength = (ushort)linkbytes.Length;
                buffer.PrintNameOffset      = (ushort)(linkbytes.Length + 2);
                buffer.PrintNameLength      = 0;
                buffer.PathBuffer           = new byte[0x3ff0];
                Array.Copy(linkbytes, buffer.PathBuffer, linkbytes.Length);

                int    _size   = Marshal.SizeOf(buffer);
                IntPtr _buffer = Marshal.AllocHGlobal(_size);

                try
                {
                    Marshal.StructureToPtr(buffer, _buffer, false);

                    int  bytesReturned;
                    bool result = NativeMethods.DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT,
                                                                _buffer, linkbytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                    {
                        throw new IOException("Failed to create junction", Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(_buffer);
                }
            }
        }
Exemplo n.º 36
0
		public static bool CreateConsole() {
			if (AllocConsole()) {
				//vs debugger may redirect console out into debug out, so we need to redirect it back
				if (!hConOut.IsInvalid) {
					hConOut.Dispose();
				}
				hConOut = CreateFile("CONOUT$", 0x40000000, FileShare.Write, /*null*/ IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
				if (!hConOut.IsInvalid) {
					SetStdHandle(-11, hConOut.DangerousGetHandle());
				}
				var cw = new StreamWriter(Console.OpenStandardOutput());
				cw.AutoFlush = true;
				Console.SetOut(cw);
				return true;
			}
			return false;
		}
Exemplo n.º 37
0
        static void Main(string[] args)
        {
            const string pipeName = @"\\.\pipe\SamplePipe";
            const int inputBufferSize = 4096;
            const int outputBufferSize = 4096;

            IntPtr hPipe = NativeMethods.CreateNamedPipe(
                                     pipeName,
                                     NativeMethods.PIPE_ACCESS_DUPLEX, // read/write access
                                     NativeMethods.PIPE_TYPE_BYTE | // message type pipe
                                     NativeMethods.PIPE_READMODE_BYTE | // message-read mode
                                     NativeMethods.PIPE_WAIT, // blocking mode
                                     NativeMethods.PIPE_UNLIMITED_INSTANCES, // max. instances
                                     outputBufferSize, // output buffer size
                                     inputBufferSize, // input buffer size
                                     0, // default client time-out for WaitNamePipe Method
                                     IntPtr.Zero); // no security attribute
            SafeFileHandle safeHandle = new SafeFileHandle(hPipe, true);
            if (safeHandle.IsInvalid)
                throw new IOException("Could not open pipe " + pipeName + ".");

            Console.WriteLine("Waiting for client to connect.");
            bool connected = NativeMethods.ConnectNamedPipe(hPipe, IntPtr.Zero) ||
                             Marshal.GetLastWin32Error() == NativeMethods.ERROR_PIPE_CONNECTED;
            if (!connected)
                throw new Win32Exception(Marshal.GetLastWin32Error());
            Console.WriteLine("Connected to client.");

            Stream stream = new FileStream(safeHandle, FileAccess.ReadWrite, 4096);
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes("Hello World\n");
                while (true)
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Flush();//important to send immediately
                    Thread.Sleep(1000);
                }
            }
            finally
            {
                NativeMethods.DisconnectNamedPipe(safeHandle.DangerousGetHandle()); //proper disconnect before closing handle
                stream.Dispose();
            }
        }
Exemplo n.º 38
0
        public static void SetFileSize(SafeFileHandle handle, long count)
        {
#if !__MonoCS__ && !USE_UNIX_IO
            var low = (int)(count & 0xffffffff);
            var high = (int)(count >> 32);
            WinNative.SetFilePointer(handle, low, out high, WinNative.EMoveMethod.Begin);
            if (!WinNative.SetEndOfFile(handle))
            {
                throw new Win32Exception();
            }
#else
            int r;
            do {
                r = Syscall.ftruncate (handle.DangerousGetHandle().ToInt32(), count);
            } while (UnixMarshal.ShouldRetrySyscall (r));
            UnixMarshal.ThrowExceptionForLastErrorIf (r);
#endif
            FSync(handle);
        }
Exemplo n.º 39
0
		public FileStream (SafeFileHandle handle, FileAccess access,
				   int bufferSize, bool isAsync)
			:this (handle.DangerousGetHandle (), access, false, bufferSize, isAsync)
		{
			this.safeHandle = handle;
		}
Exemplo n.º 40
0
		internal static SafeMemoryMappedFileHandle CreateFileMapping(SafeFileHandle hFile, SECURITY_ATTRIBUTES lpAttributes, int fProtect, int dwMaximumSizeHigh, int dwMaximumSizeLow, string lpName)
		{
			var handle = new SafeMemoryMappedFileHandle(hFile.DangerousGetHandle (), false);

			return handle;
		}
Exemplo n.º 41
0
        public static bool TryGetHidInfo(SafeFileHandle hidHandle, out int vendorId, out int productId)
        {
            // create an attributes struct and initialize the size
            NativeMethods.HIDD_ATTRIBUTES attrib = new NativeMethods.HIDD_ATTRIBUTES();
            attrib.Size = Marshal.SizeOf(attrib);

            // get the attributes of the current device
            if (NativeMethods.HidD_GetAttributes(hidHandle.DangerousGetHandle(), ref attrib))
            {
                // if the vendor and product IDs match up
                vendorId = attrib.VendorID;
                productId = attrib.ProductID;
                return true;
            }
            else
            {
                vendorId = 0;
                productId = 0;
                return false;
            }
        }
Exemplo n.º 42
0
        private void OpenWiimoteDeviceHandle(string devicePath)
        {
            // open a read/write handle to our device using the DevicePath returned
            wiiHandle = HIDImports.CreateFile(devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

            // open a read/write handle to the PDA
            pdaHandle = HIDImports.CreateFile("\\\\.\\COM20", FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

            // create an attributes struct and initialize the size
            HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
            attrib.Size = Marshal.SizeOf(attrib);

            // get the attributes of the current device
            if(HIDImports.HidD_GetAttributes(wiiHandle.DangerousGetHandle(), ref attrib))
            {
                // if the vendor and product IDs match up
                if(attrib.VendorID == VID && attrib.ProductID == PID)
                {
                    // create a nice .NET FileStream wrapping the handle above
                    wiiStream = new FileStream(wiiHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                    // create a FileStream wrapping the pdaHandle
                    pdaStream = new FileStream(pdaHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                    // Loop and wait for the PDA to write bytes
                    PDA_ReadWriteLoop();

                }
                else
                {
                    // otherwise this isn't the controller, so close up the file handle
                    wiiHandle.Close();
                    throw new WiimoteException("Attempted to open a non-Wiimote device.");
                }
            }
        }
Exemplo n.º 43
0
 private static HidDeviceAttributes GetDeviceAttributes(SafeFileHandle hidHandle)
 {
     var deviceAttributes = default(NativeMethods.HIDD_ATTRIBUTES);
     deviceAttributes.Size = Marshal.SizeOf(deviceAttributes);
     NativeMethods.HidD_GetAttributes(hidHandle.DangerousGetHandle(), ref deviceAttributes);
     return new HidDeviceAttributes(deviceAttributes);
 }
Exemplo n.º 44
0
        internal static void FindWiimote(WiimoteFoundDelegate wiimoteFound)
        {
            int index = 0;
            bool found = false;
            Guid guid;
            SafeFileHandle mHandle;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while(HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                // actually get the detail struct
                if(HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(string.Format("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error()));

                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if(attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            // it's a Wiimote
                            Debug.WriteLine("Found one!");
                            found = true;

                            // fire the callback function...if the callee doesn't care about more Wiimotes, break out
                            if(!wiimoteFound(diDetail.DevicePath))
                                break;
                        }
                    }
                    mHandle.Close();
                }
                else
                {
                    // failed to get the detail struct
                    throw new WiimoteException("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a Wiimote, throw an exception
            if(!found)
                throw new WiimoteNotFoundException("No Wiimotes found in HID device list.");
        }
Exemplo n.º 45
0
            public CodecIndexInput(FileInfo file, Func<Stream, Stream> applyCodecs)
            {
                try
                {
                    this.file = file;
                    this.applyCodecs = applyCodecs;
                    if (file.Length == 0)
                    {
                        stream = applyCodecs(Stream.Null);
                        return;
                    }

                    fileHandle = Win32NativeFileMethods.CreateFile(file.FullName,
                        Win32NativeFileAccess.GenericRead,
                        Win32NativeFileShare.Read | Win32NativeFileShare.Write | Win32NativeFileShare.Delete,
                        IntPtr.Zero,
                        Win32NativeFileCreationDisposition.OpenExisting,
                        Win32NativeFileAttributes.RandomAccess,
                        IntPtr.Zero);

                    if (fileHandle.IsInvalid)
                    {
                        const int ERROR_FILE_NOT_FOUND = 2;
                        if (Marshal.GetLastWin32Error() == ERROR_FILE_NOT_FOUND)
                            throw new FileNotFoundException(file.FullName);
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not open file " + file.FullName);
                    }

                    mmf = Win32MemoryMapNativeMethods.CreateFileMapping(fileHandle.DangerousGetHandle(), IntPtr.Zero, Win32MemoryMapNativeMethods.FileMapProtection.PageReadonly,
                        0, 0, null);
                    if (mmf == IntPtr.Zero)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not create file mapping for " + file.FullName);
                    }

                    basePtr = Win32MemoryMapNativeMethods.MapViewOfFileEx(mmf,
                        Win32MemoryMapNativeMethods.NativeFileMapAccessType.Read,
                        0, 0, UIntPtr.Zero, null);
                    if (basePtr == null)
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not map file " + file.FullName);

                    stream = applyCodecs(new MmapStream(file.FullName, basePtr, file.Length));
                }
                catch (Exception)
                {
                    Dispose(false);
                    throw;
                }
            }
Exemplo n.º 46
0
        protected override object[] CreateItems()
        {
            Process curProcess = Process.GetCurrentProcess();

            List<Process> result = new List<Process>();
            foreach (Process process in Process.GetProcesses())
            {
                // Skip ourself
                if (process.Id == curProcess.Id)
                    continue;

                // Skip special PIDs
                if (process.Id == 0 || process.Id == 4)
                    continue;

                // Skip EasyHook services
                string processNameLower = process.ProcessName.ToLower();
                if (processNameLower == "easyhook32svc" || processNameLower == "easyhook64svc")
                    continue;
                // And any oSpy instances
                if (processNameLower == "ospy" || processNameLower == "ospy.vshost")
                    continue;

                // And also 64 bit processes on x64
                if (EasyHook.RemoteHooking.IsX64System)
                {
                    SafeHandle processHandle = new SafeFileHandle(WinApi.OpenProcess(WinApi.PROCESS_QUERY_INFORMATION, false, (uint) process.Id), true);
                    if (!processHandle.IsInvalid)
                    {
                        bool processIs32Bit = false;
                        if (WinApi.IsWow64Process(processHandle.DangerousGetHandle(), out processIs32Bit) && !processIs32Bit)
                            continue;
                    }
                }

                result.Add(process);
                processIcons[process] = GetProcessIcon(process);
            }

            return result.ToArray();
        }
Exemplo n.º 47
0
		internal void FindEv3()
		{
			int index = 0;
			bool found = false;
			Guid guid;

			// get the GUID of the HID class
			HidImports.HidD_GetHidGuid(out guid);

			// get a handle to all devices that are part of the HID class
			IntPtr hDevInfo = HidImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HidImports.DIGCF_DEVICEINTERFACE | HidImports.DIGCF_PRESENT);

			// create a new interface data struct and initialize its size
			HidImports.SP_DEVICE_INTERFACE_DATA diData = new HidImports.SP_DEVICE_INTERFACE_DATA();
			diData.cbSize = Marshal.SizeOf(diData);

			// get a device interface to a single device (enumerate all devices)
			while(HidImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
			{
				UInt32 size;

				// get the buffer size for this device detail instance (returned in the size parameter)
				HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

				// create a detail struct and set its size
				HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

				// yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
				// someday I should figure this out.  Thanks to Paul Miller on this...
				diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

				// actually get the detail struct
				if(HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
				{
					Debug.WriteLine("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error());

					// open a read/write handle to our device using the DevicePath returned
					_handle = HidImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HidImports.EFileAttributes.Overlapped, IntPtr.Zero);

					// create an attributes struct and initialize the size
					HidImports.HIDD_ATTRIBUTES attrib = new HidImports.HIDD_ATTRIBUTES();
					attrib.Size = Marshal.SizeOf(attrib);

					// get the attributes of the current device
					if(HidImports.HidD_GetAttributes(_handle.DangerousGetHandle(), ref attrib))
					{
						// if the vendor and product IDs match up
						if(attrib.VendorID == VID && attrib.ProductID == PID)
						{
							// it's a Ev3
							Debug.WriteLine("Found one!");
							found = true;

							IntPtr preparsedData;
							if(!HidImports.HidD_GetPreparsedData(_handle.DangerousGetHandle(), out preparsedData))
								throw new Exception("Could not get preparsed data for HID device");

							HidImports.HIDP_CAPS caps;
							if(HidImports.HidP_GetCaps(preparsedData, out caps) != HidImports.HIDP_STATUS_SUCCESS)
								throw new Exception("Could not get CAPS for HID device");

							HidImports.HidD_FreePreparsedData(ref preparsedData);

							_inputReport = new byte[caps.InputReportByteLength];
							_outputReport = new byte[caps.OutputReportByteLength];

							// create a nice .NET FileStream wrapping the handle above
							_stream = new FileStream(_handle, FileAccess.ReadWrite, _inputReport.Length, true);

							break;
						}

						_handle.Close();
					}
				}
				else
				{
					// failed to get the detail struct
					throw new Exception("SetupDiGetDeviceInterfaceDetail failed on index " + index);
				}

				// move to the next device
				index++;
			}

			// clean up our list
			HidImports.SetupDiDestroyDeviceInfoList(hDevInfo);

			// if we didn't find a EV3, throw an exception
			if(!found)
				throw new Exception("No LEGO EV3s found in HID device list.");
		}
Exemplo n.º 48
0
        private static string WinInternalGetTarget(SafeFileHandle handle)
        {
            int outBufferSize = ClrFacade.SizeOf<REPARSE_DATA_BUFFER_SYMBOLICLINK>();

            IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize);
            bool success = false;

            try
            {
                int bytesReturned;

                //OACR warning 62001 about using DeviceIOControl has been disabled. 
                // According to MSDN guidance DangerousAddRef() and DangerousRelease() have been used.

                handle.DangerousAddRef(ref success);

                bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT,
                    IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);

                if (!result)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    if (lastError == ERROR_NOT_A_REPARSE_POINT)
                        return null;

                    throw new Win32Exception(lastError);
                }

                //Unmarshal to symbolic link to look for tags. 
                REPARSE_DATA_BUFFER_SYMBOLICLINK reparseDataBuffer = ClrFacade.PtrToStructure<REPARSE_DATA_BUFFER_SYMBOLICLINK>(outBuffer);

                if (reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_SYMLINK && reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT)
                    return null;

                string targetDir = null;

                if (reparseDataBuffer.ReparseTag == IO_REPARSE_TAG_SYMLINK)
                {
                    targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer, reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength);
                }

                if (reparseDataBuffer.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
                {
                    //Since this is a junction we need to unmarshal to the correct structure.
                    REPARSE_DATA_BUFFER_MOUNTPOINT reparseDataBufferMountPoint = ClrFacade.PtrToStructure<REPARSE_DATA_BUFFER_MOUNTPOINT>(outBuffer);

                    targetDir = Encoding.Unicode.GetString(reparseDataBufferMountPoint.PathBuffer, reparseDataBufferMountPoint.SubstituteNameOffset, reparseDataBufferMountPoint.SubstituteNameLength);
                }

                if (targetDir.StartsWith(NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase))
                    targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length);

                return targetDir;
            }
            finally
            {
                if (success)
                {
                    handle.DangerousRelease();
                }

                Marshal.FreeHGlobal(outBuffer);
            }
        }
Exemplo n.º 49
0
        /// <summary>
        /// Connect to a Wiimote paired to the PC via Bluetooth
        /// </summary>
        public void Connect()
        {
            int index = 0;
            bool found = false;
            Guid guid;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while(HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                // actually get the detail struct
                if(HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(index + " " + diDetail.DevicePath + " " + Marshal.GetLastWin32Error());

                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if(attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            Debug.WriteLine("Found it!");
                            found = true;

                            // create a nice .NET FileStream wrapping the handle above
                            mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                            // start an async read operation on it
                            BeginAsyncRead();

                            // read the calibration info from the controller
                            try
                            {
                                ReadCalibration();
                            }
                            catch
                            {
                                // if we fail above, try the alternate HID writes
                                mAltWriteMethod = true;
                                ReadCalibration();
                            }

                            // force a status check to get the state of any extensions plugged in at startup
                            GetStatus();

                            break;
                        }
                        else
                        {
                            // otherwise this isn't the controller, so close up the file handle
                            mHandle.Close();
                        }
                    }
                }
                else
                {
                    // failed to get the detail struct
                    throw new WiimoteException("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a Wiimote, throw an exception
            if(!found)
                throw new WiimoteException("Wiimote not found in HID device list.");
        }
        private static string InternalGetTarget(SafeFileHandle handle)
        {
            int outBufferSize = Marshal.SizeOf(typeof(REPARSE_DATA_BUFFER));
            IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize);

            try
            {
                int bytesReturned;
                bool result = DeviceIoControl(handle.DangerousGetHandle(), FsctlGetReparsePoint, IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);

                if (!result)
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error == ErrorNotAReparsePoint)
                    {
                        return null;
                    }

                    ThrowLastWin32Error(Strings.UnableToGetJunctionInformation);
                }

                REPARSE_DATA_BUFFER reparseDataBuffer = (REPARSE_DATA_BUFFER)
                    Marshal.PtrToStructure(outBuffer, typeof(REPARSE_DATA_BUFFER));

                if (reparseDataBuffer.ReparseTag != IoReparseTagMountPoint)
                {
                    return null;
                }

                string targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer, reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength);

                if (targetDir.StartsWith(NonInterpretedPathPrefix, StringComparison.Ordinal))
                {
                    targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length);
                }

                return targetDir;
            }
            finally
            {
                Marshal.FreeHGlobal(outBuffer);
            }
        }
Exemplo n.º 51
0
        private static HidDeviceCapabilities GetDeviceCapabilities(SafeFileHandle hidHandle)
        {
            var capabilities = default(NativeMethods.HIDP_CAPS);
            var preparsedDataPointer = default(IntPtr);

            if (NativeMethods.HidD_GetPreparsedData(hidHandle.DangerousGetHandle(), ref preparsedDataPointer))
            {
                NativeMethods.HidP_GetCaps(preparsedDataPointer, ref capabilities);
                NativeMethods.HidD_FreePreparsedData(preparsedDataPointer);
            }
            return new HidDeviceCapabilities(capabilities);
        }
Exemplo n.º 52
0
        public static void Write(SafeFileHandle handle, byte* buffer, uint count, ref int written)
        {
#if !__MonoCS__ && !USE_UNIX_IO
            if (!WinNative.WriteFile(handle, buffer, count, ref written, IntPtr.Zero))
            {
                throw new Win32Exception();
            }
#else
            int ret = 0;
                do {
                ret = (int) Syscall.write (handle.DangerousGetHandle().ToInt32(), buffer ,count);
            } while (Mono.Unix.UnixMarshal.ShouldRetrySyscall ((int) ret));
            if(ret == -1)
                Mono.Unix.UnixMarshal.ThrowExceptionForLastErrorIf ((int) ret);
            written = (int) count;
#endif
        }
Exemplo n.º 53
0
        public static int Read(SafeFileHandle handle, byte* buffer, int offset, int count)
        {
#if !__MonoCS__ && !USE_UNIX_IO
            var read = 0;

            if (!WinNative.ReadFile(handle, buffer, count, ref read, 0))
            {
                throw new Win32Exception();
            }
            return read;
#else
            int r;
            do {
                r = (int) Syscall.read (handle.DangerousGetHandle().ToInt32(), buffer, (ulong) count);
            } while (UnixMarshal.ShouldRetrySyscall ((int) r));
            if (r == -1)
                UnixMarshal.ThrowExceptionForLastError ();
            return count;
#endif
        }
Exemplo n.º 54
0
        private void Search_For_Wiimotes()
        {
            // 1. Get the GUID of the HID class
            HIDImports2.HidD_GetHidGuid(out guid);

            // 2. get a handle to all devices that are part of the HID class
            IntPtr hDevInfo = HIDImports2.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports2.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports2.SP_DEVICE_INTERFACE_DATA diData = new HIDImports2.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // 3. get a device interface to a single device (enumerate all devices)
            while (HIDImports2.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                // create a detail struct and set its size
                HIDImports2.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports2.SP_DEVICE_INTERFACE_DETAIL_DATA();
                diDetail.cbSize = 5; //should be: (uint)Marshal.SizeOf(diDetail);, but that's the wrong size

                UInt32 size = 0;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports2.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // actually get the detail struct
                if (HIDImports2.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports2.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports2.EFileAttributes.Overlapped, IntPtr.Zero);

                    // 4. create an attributes struct and initialize the size
                    HIDImports2.HIDD_ATTRIBUTES attrib = new HIDImports2.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if (HIDImports2.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if ((attrib.VendorID == VID_old && attrib.ProductID == PID_old) || (attrib.VendorID == VID_new && attrib.ProductID == PID_new))
                        {
                            // 5. create a nice .NET FileStream wrapping the handle above
                            mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);
                            Console.WriteLine("Wii remote found");
                        }
                        else
                            mHandle.Close();
                    }
                }

                // move to the next device
                index++;
            }

            // 6. clean up our list
            HIDImports2.SetupDiDestroyDeviceInfoList(hDevInfo);
        }
Exemplo n.º 55
0
        private static string InternalGetTarget(SafeFileHandle handle)
        {
            int outBufferSize = Marshal.SizeOf(typeof(REPARSE_DATA_BUFFER));
            IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize);

            try
            {
                int bytesReturned;
                bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT,
                    IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);

                if (!result)
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error == ERROR_NOT_A_REPARSE_POINT)
                        return null;

                    ThrowLastWin32Error("Unable to get information about junction point.");
                }

                REPARSE_DATA_BUFFER reparseDataBuffer = (REPARSE_DATA_BUFFER)
                    Marshal.PtrToStructure(outBuffer, typeof(REPARSE_DATA_BUFFER));

                if (reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT)
                    return null;

                string targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer,
                    reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength);

                if (targetDir.StartsWith(NonInterpretedPathPrefix))
                    targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length);

                return targetDir;
            }
            finally
            {
                Marshal.FreeHGlobal(outBuffer);
            }
        }
Exemplo n.º 56
0
        public static long GetFileSize(SafeFileHandle handle)
        {
#if !__MonoCS__ && !USE_UNIX_IO
            long size = 0;
            if (!WinNative.GetFileSizeEx(handle, out size))
            {
                throw new Win32Exception();
            }
            return size;
#else
            Stat s;
            int r;
            do {
              r = (int) Syscall.fstat(handle.DangerousGetHandle().ToInt32(), out s);
            } while (UnixMarshal.ShouldRetrySyscall(r));
            UnixMarshal.ThrowExceptionForLastErrorIf (r);
            return s.st_size;
#endif
        }
Exemplo n.º 57
0
        private void OpenWiimoteDeviceHandle(string devicePath)
        {
            // open a read/write handle to our device using the DevicePath returned
            mHandle = HIDImports.CreateFile(devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

            // create an attributes struct and initialize the size
            HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
            attrib.Size = Marshal.SizeOf(attrib);

            // get the attributes of the current device
            if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
            {
                // if the vendor and product IDs match up
                if(attrib.VendorID == VID && attrib.ProductID == PID)
                {
                    // create a nice .NET FileStream wrapping the handle above
                    mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                    // start an async read operation on it
                    BeginAsyncRead();

                    // read the calibration info from the controller
                    try
                    {
                        ReadWiimoteCalibration();
                    }
                    catch
                    {
                        // if we fail above, try the alternate HID writes
                        mAltWriteMethod = true;
                        ReadWiimoteCalibration();
                    }

                    // force a status check to get the state of any extensions plugged in at startup
                    GetStatus();
                }
                else
                {
                    // otherwise this isn't the controller, so close up the file handle
                    mHandle.Close();
                    throw new WiimoteException("Attempted to open a non-Wiimote device.");
                }
            }
        }
Exemplo n.º 58
0
        public static void TurnOffMacCaching(SafeFileHandle handle)
        {

            if (OS.OsFlavor != OsFlavor.MacOS) return;
#if __MonoCS__ || USE_UNIX_IO
            long r = 0;
            do {
                r = fcntl (handle.DangerousGetHandle().ToInt32(), MAC_F_NOCACHE, 1);
            } while (UnixMarshal.ShouldRetrySyscall ((int) r));
            if (r == -1)
                UnixMarshal.ThrowExceptionForLastError ();
#endif

        }
Exemplo n.º 59
0
        /// <summary>
        /// Registers to be notified when the volume is about to be removed
        /// This is requierd if you want to get the QUERY REMOVE messages
        /// </summary>
        /// <param name="register">true to register, false to unregister</param>
        /// <param name="fileHandle">handle of a file opened on the removable drive</param>
        private void RegisterForDeviceChange(bool register, SafeFileHandle fileHandle)
        {
            if (register)
            {
                // Register for handle
                DEV_BROADCAST_HANDLE data = new DEV_BROADCAST_HANDLE();
                data.dbch_devicetype = DBT_DEVTYP_HANDLE;
                data.dbch_reserved = 0;
                data.dbch_nameoffset = 0;
                //data.dbch_data = null;
                //data.dbch_eventguid = 0;
                data.dbch_handle = fileHandle.DangerousGetHandle(); //Marshal. fileHandle;
                data.dbch_hdevnotify = (IntPtr)0;
                int size = Marshal.SizeOf(data);
                data.dbch_size = size;
                IntPtr buffer = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(data, buffer, true);

                mDeviceNotifyHandle = Native.RegisterDeviceNotification(mRecipientHandle, buffer, 0);
            }
            else
            {
                // close the directory handle
                if (mDirHandle != IntPtr.Zero)
                {
                    Native.CloseDirectoryHandle(mDirHandle);
                    //    string er = Marshal.GetLastWin32Error().ToString();
                }

                // unregister
                if (mDeviceNotifyHandle != IntPtr.Zero)
                {
                    Native.UnregisterDeviceNotification(mDeviceNotifyHandle);
                }

                mDeviceNotifyHandle = IntPtr.Zero;
                mDirHandle = IntPtr.Zero;

                mCurrentDrive = "";
                if (mFileOnFlash != null)
                {
                    mFileOnFlash.Close();
                    mFileOnFlash = null;
                }
            }
        }
Exemplo n.º 60
0
        public static void Seek(SafeFileHandle handle, long position, SeekOrigin origin)
        {
#if !__MonoCS__ && !USE_UNIX_IO
            var low = (int)(position & 0xffffffff);
            var high = (int)(position >> 32);
            var f = WinNative.SetFilePointer(handle, low, out high, WinNative.EMoveMethod.Begin);
            if (f == WinNative.INVALID_SET_FILE_POINTER)
            {
                throw new Win32Exception();
            }
#else
            int r = 0;
            do {
                r = (int) Syscall.lseek(handle.DangerousGetHandle().ToInt32(), position, SeekFlags.SEEK_SET);
            } while (UnixMarshal.ShouldRetrySyscall (r));
            UnixMarshal.ThrowExceptionForLastErrorIf (r);
#endif
        }