void EnsureRecordBuffer(uint bytes)
        {
            if (bytes <= currentBufferSize)
            {
                return;
            }

            bufferHandle.Close();
            currentBufferSize = bytes;
            bufferHandle      = SafeHGlobalHandleCritical.AllocHGlobal(currentBufferSize);

            record.pbMDData    = bufferHandle.DangerousGetHandle();
            record.dwMDDataLen = currentBufferSize;
        }
Exemplo n.º 2
0
 internal unsafe VBoxUSB(USBRegistry devreg)
 {
     this.Registry = devreg;
     hDev          = Kernel32.CreateFile(devreg.DevicePath, Kernel32.GENERIC_READ | Kernel32.GENERIC_WRITE, Kernel32.FILE_SHARE_WRITE | Kernel32.FILE_SHARE_READ, IntPtr.Zero, Kernel32.OPEN_EXISTING, Kernel32.FILE_ATTRIBUTE_SYSTEM | Kernel32.FILE_FLAG_OVERLAPPED, IntPtr.Zero);
     if (hDev.IsInvalid)
     {
         throw new Win32Exception();
     }
     try {
         USBSUP_VERSION version = new USBSUP_VERSION();
         SyncIoControl(hDev, SUPUSB_IOCTL_GET_VERSION, null, 0, &version, sizeof(USBSUP_VERSION));
         if (version.u32Major != USBDRV_MAJOR_VERSION || version.u32Minor < USBDRV_MINOR_VERSION)
         {
             throw new InvalidOperationException("Unsupported USBDRV version");
         }
         USBSUP_CLAIMDEV claim = new USBSUP_CLAIMDEV()
         {
             bInterfaceNumber = 0
         };
         SyncIoControl(hDev, SUPUSB_IOCTL_USB_CLAIM_DEVICE, &claim, sizeof(USBSUP_CLAIMDEV), &claim, sizeof(USBSUP_CLAIMDEV));
         if (claim.fClaimed == 0)
         {
             throw new InvalidOperationException("Claim failed");
         }
     } catch {
         hDev.Close();
         throw;
     }
 }
Exemplo n.º 3
0
        static public string[] GetVolumes()
        {
            StringBuilder sb = new StringBuilder(NativeMethods.MAX_PATH);

            SafeHandle h = NativeMethods.FindFirstVolumeW(sb, sb.Capacity);

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

            List <string> volumes = new List <string>();

            volumes.Add(sb.ToString());

            while (NativeMethods.FindNextVolumeW(h, sb, sb.Capacity))
            {
                volumes.Add(sb.ToString());
            }

            int result = Marshal.GetLastWin32Error();

            h.Close();

            if (result != Win32Errors.ERROR_NO_MORE_FILES)
            {
                throw new Win32Exception(result);
            }

            return(volumes.ToArray());
        }
Exemplo n.º 4
0
        /// <summary>
        /// Queries the security context for the target name (SPN for kerb)
        /// </summary>
        /// <param name="securityContext">security context to query</param>
        /// <param name="specifiedTarget">output parameter for the name</param>
        /// <returns>the status code returned from querying the context</returns>
        public static unsafe int QuerySpecifiedTarget(SafeDeleteContext securityContext, out string specifiedTarget)
        {
            int        nativeBlockSize = IntPtr.Size;
            Type       handleType      = typeof(SafeFreeContextBuffer);
            SafeHandle sspiHandle      = null;
            int        errorCode;

            specifiedTarget = null;
            try
            {
                byte[] nativeBuffer = new byte[nativeBlockSize];
                errorCode = QueryContextAttributes(securityContext, ContextAttribute.SpecifiedTarget, nativeBuffer, handleType, out sspiHandle);
                if (errorCode != (int)SecurityStatus.OK)
                {
                    return(errorCode);
                }

                specifiedTarget = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle()) as string;
            }
            finally
            {
                if (sspiHandle != null)
                {
                    sspiHandle.Close();
                }
            }
            return(errorCode);
        }
        public static int QuerySpecifiedTarget(SafeDeleteContext securityContext, out string specifiedTarget)
        {
            int        num2;
            int        size       = IntPtr.Size;
            Type       handleType = typeof(SafeFreeContextBuffer);
            SafeHandle refHandle  = null;

            specifiedTarget = null;
            try
            {
                byte[] buffer = new byte[size];
                num2 = QueryContextAttributes(securityContext, ContextAttribute.SpecifiedTarget, buffer, handleType, out refHandle);
                if (num2 != 0)
                {
                    return(num2);
                }
                specifiedTarget = Marshal.PtrToStringUni(refHandle.DangerousGetHandle());
            }
            finally
            {
                if (refHandle != null)
                {
                    refHandle.Close();
                }
            }
            return(num2);
        }
Exemplo n.º 6
0
Arquivo: CFile.cs Projeto: tdav/Quote
        public static bool IsFileInUse(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return(false);
            }

            SafeHandle handleValue = null;

            try
            {
                handleValue = CreateFile(filePath, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

                bool inUse = handleValue.IsInvalid;

                return(inUse);
            }
            finally
            {
                if (handleValue != null)
                {
                    handleValue.Close();

                    handleValue.Dispose();

                    handleValue = null;
                }
            }
        }
Exemplo n.º 7
0
 public void Close()
 {
     if (Handle != null)
     {
         Handle.Close();
     }
 }
Exemplo n.º 8
0
 internal static void CloseSafeHandle(SafeHandle handle)
 {
     if (null != handle && !handle.IsClosed)
     {
         handle.Close();
     }
 }
Exemplo n.º 9
0
 protected virtual void DisposeManagedResources()
 {
     if (handle != null)
     {
         handle.Close();
     }
 }
Exemplo n.º 10
0
        public static void Inject(string inputPid)
        {
            // if injecting reflectively need to potentially bootstrap the .NET run time and then figure out reflective injection
            // https://web.archive.org/web/20101224064236/http://codingthewheel.com/archives/how-to-inject-a-managed-assembly-dll

            int        pid           = Convert.ToInt32(inputPid);
            Process    p             = Process.GetProcessById(pid);
            SafeHandle processHandle = OpenProcess(0x1FFFFF /* PROCESS_ALL_ACCESS */, false, pid);
            string     dllName       = AssemblyPath;

            if (processHandle.IsInvalid)
            {
                Debug.WriteLine(String.Format("OpenProcess failed with error {0}", Marshal.GetLastWin32Error()));
                return;
            }

            IntPtr lpBaseAddress = VirtualAllocEx(processHandle, IntPtr.Zero, new IntPtr((dllName.Length + 1) * 2), MEM_COMMIT, 0x04);

            if (lpBaseAddress == IntPtr.Zero)
            {
                Debug.WriteLine(String.Format("VirtualAllocEx failed with error {0}", Marshal.GetLastWin32Error()));
                processHandle.Close();
                return;
            }

            IntPtr _LoadLibrary = GetProcAddress(GetModuleHandleW("kernel32"), "LoadLibraryW");
            IntPtr numBytes;

            if (!WriteProcessMemory(processHandle, lpBaseAddress, System.Text.Encoding.Unicode.GetBytes(dllName), new IntPtr(dllName.Length * 2), out numBytes))
            {
                Debug.WriteLine(String.Format("WriteProcessMemory failed with error {0}", Marshal.GetLastWin32Error()));
                processHandle.Close();
                return;
            }

            Int32 dwThreadId;

            if (CreateRemoteThread(processHandle, IntPtr.Zero, IntPtr.Zero, _LoadLibrary, lpBaseAddress, 0, out dwThreadId) == IntPtr.Zero)
            {
                Debug.WriteLine(String.Format("CreateRemoteThread failed with error {0}", Marshal.GetLastWin32Error()));
                processHandle.Close();
                return;
            }

            Debug.WriteLine("Successfully injected into process!");
        }
Exemplo n.º 11
0
 public void Close()
 {
     if (IsOpen())
     {
         hidHideHandle.Close();
         hidHideHandle.Dispose();
         hidHideHandle = null;
     }
 }
Exemplo n.º 12
0
        protected override void Dispose(bool disposing)
        {
            // Nothing will be done differently based on whether we are disposing vs. finalizing.
            lock (this)
            {
                if (m_handle != null && !m_handle.IsInvalid)
                {
                    if (disposing)
                    {
                        CancelPendingIO();
                    }

                    m_handle.Close();
                    m_handle.SetHandleAsInvalid();
                }
            }

            base.Dispose(disposing);
        }
Exemplo n.º 13
0
        internal void UnregisterDeviceArrival()
        {
            if (_handleDeviceArrival.IsInvalid)
            {
                return;
            }

            UnregisterDeviceNotification(_handleDeviceArrival);
            _handleDeviceArrival.Close();
        }
Exemplo n.º 14
0
        public void Reset()
        {
            if (_findHandle.IsInvalid)
            {
                return;
            }

            _findHandle.Close();
            _findHandle.SetHandleAsInvalid();
        }
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (!_handle.IsClosed)
         {
             _handle.Close();
         }
     }
 }
 /// <summary>
 /// Releases resources.
 /// </summary>
 public void Dispose()
 {
     if (!object.ReferenceEquals(null, _fileHandle))
     {
         if (!_fileHandle.IsClosed)
         {
             _fileHandle.Close();
         }
     }
 }
Exemplo n.º 17
0
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }
            _wicBitmapBuffer = null;
            SafeHandle safeHandle = (SafeHandle)_wicBitmapLockSafeHandle;

            safeHandle.Close();
            safeHandle.Dispose();
        }
Exemplo n.º 18
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (_handle != null)
                {
                    _handle.Close();
                    _handle = null;
                }

                disposedValue = true;
            }
        }
Exemplo n.º 19
0
 void UnhookDnDebuggerEventsAndCloseProcessHandle()
 {
     if (dnDebugger != null)
     {
         dnDebugger.DebugCallbackEvent    -= DnDebugger_DebugCallbackEvent;
         dnDebugger.OnProcessStateChanged -= DnDebugger_OnProcessStateChanged;
         dnDebugger.OnNameChanged         -= DnDebugger_OnNameChanged;
         dnDebugger.OnThreadAdded         -= DnDebugger_OnThreadAdded;
         dnDebugger.OnAppDomainAdded      -= DnDebugger_OnAppDomainAdded;
         dnDebugger.OnModuleAdded         -= DnDebugger_OnModuleAdded;
     }
     hProcess_debuggee?.Close();
 }
Exemplo n.º 20
0
Arquivo: marshal.cs Projeto: rdp/vlc-1
 /**
  * Releases unmanaged resources associated with the object.
  * @param disposing true if the disposing the object explicitly,
  *                  false if finalizing the object inside the GC.
  */
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         ex.Dispose();
         if (handle != null)
         {
             handle.Close();
         }
     }
     ex     = null;
     handle = null;
 }
Exemplo n.º 21
0
        /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
        /// <param name="handle">The current handle to check.</param>
        /// <returns><see langword="true"/> on success, <see langword="false"/> otherwise.</returns>
        /// <exception cref="ArgumentException"/>
        public static bool IsValid(SafeHandle handle)
        {
            if (handle == null || handle.IsClosed || handle.IsInvalid)
            {
                if (handle != null)
                {
                    handle.Close();
                }

                return(false);
            }

            return(true);
        }
Exemplo n.º 22
0
 /// <summary>
 /// Виртуальный метод, который должен разобраться кто инициировал диспоуз - пользовательский код или финализатор.
 /// Вызывается ид диспоуз и финализатора с разным значением аргумента.
 /// </summary>
 protected virtual void Dispose(bool disposing)
 {
     // безусловно освобождаем неуправляемые ресурсы (имитация).
     Marshal.Release(unmanagedResource);
     if (disposing)
     {
         // если это пользовательский вызов, то GC ещё не уничтожил управляемые ресурсы,
         // и мы можем их освободить не опасаясь, что они уже освобождены.
         if (handle != null)
         {
             handle.Close();
         }
     }
 }
Exemplo n.º 23
0
        private void Dispose(bool isDisposing)
        {
            if (_isDisposed)
            {
                return;
            }
            if (isDisposing)
            {
                // No managed instances to dispose
            }
            SafeHandle safeHandle = (SafeHandle)_wicBitmap;

            safeHandle.Close();
            safeHandle.Dispose();
        }
Exemplo n.º 24
0
        private void GetDeviceInformation()
        {
            if (m_VolumeData.VolumeDevicePath == null && IsDriveLetter(m_VolumeData.VolumeDrive))
            {
                string drive = string.Format("{0}{1}",
                                             m_VolumeData.VolumeDrive.TrimEnd(new[] { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar }),
                                             System.IO.Path.DirectorySeparatorChar);
                m_VolumeData.DriveType = m_OS.GetDriveType(drive);
                return;
            }

            m_VolumeData.DriveType   = m_OS.GetDriveType(m_VolumeData.VolumeDevicePathSlash);
            m_VolumeData.VolumeQuery = m_OS.GetVolumeInformation(m_VolumeData.VolumeDevicePathSlash);
            m_VolumeData.FreeSpace   = m_OS.GetDiskFreeSpace(m_VolumeData.VolumeDevicePathSlash);

            // For floppy drives, m_OS.GetMediaPresent is false, even if media is present. Looking into the sources from
            // .NET, the DriveInfo class checks if the file attribute directory bit is set instead. So use that first,
            // and only if it fails, then use the IOCTL later.
            System.IO.FileAttributes attr = m_OS.GetFileAttributes(m_VolumeData.VolumeDevicePathSlash);
            if ((int)attr != -1)
            {
                m_VolumeData.MediaPresent = (attr & System.IO.FileAttributes.Directory) != 0;
            }

            SafeHandle hDevice = m_OS.CreateFileFromDevice(m_VolumeData.VolumeDevicePath);

            try {
                m_OS.RefreshVolume(hDevice);
                m_VolumeData.Extents     = m_OS.GetDiskExtents(hDevice);
                m_VolumeData.DeviceQuery = m_OS.GetStorageDeviceProperty(hDevice);
                if ((int)attr == -1)
                {
                    m_VolumeData.MediaPresent = m_OS.GetMediaPresent(hDevice);
                }
                m_VolumeData.HasSeekPenalty = m_OS.IncursSeekPenalty(hDevice);
                m_VolumeData.DeviceNumber   = m_OS.GetDeviceNumberEx(hDevice);
                if (m_VolumeData.DeviceNumber == null)
                {
                    m_VolumeData.DeviceNumber = m_OS.GetDeviceNumber(hDevice);
                }
                m_VolumeData.PartitionInfo = m_OS.GetPartitionInfo(hDevice);
                m_VolumeData.DiskGeometry  = m_OS.GetDiskGeometry(hDevice);
                m_VolumeData.Alignment     = m_OS.GetAlignment(hDevice);
                m_VolumeData.DiskReadOnly  = m_OS.IsReadOnly(hDevice);
            } finally {
                hDevice.Close();
            }
        }
Exemplo n.º 25
0
 protected unsafe override void Dispose(Boolean disposing)
 {
     if (!disposing)
     {
         return;
     }
     if (!hDev.IsInvalid && !hDev.IsClosed)
     {
         USBSUP_CLAIMDEV release = new USBSUP_CLAIMDEV()
         {
             bInterfaceNumber = bInterfaceNumber
         };
         SyncIoControl(hDev, SUPUSB_IOCTL_USB_RELEASE_DEVICE, &release, sizeof(USBSUP_CLAIMDEV), null, 0, false);
     }
     hDev.Close();
 }
Exemplo n.º 26
0
        protected void Dispose(bool disposing)
        {
            if (isDisposed)
            {
                return;
            }

            if (disposing)
            {
                ReleaseResources();
            }
            safeHandle.Close();
            safeHandle.Dispose();

            isDisposed = true;
        }
Exemplo n.º 27
0
        public static SafeHandle IdentifyDevice(StorageInfo storageInfo)
        {
            SafeHandle handle = Kernel32.OpenDevice(storageInfo.Scsi);

            if (handle == null || handle.IsInvalid)
            {
                return(null);
            }


            Kernel32.NVME_PASS_THROUGH_IOCTL passThrough = Kernel32.CreateStruct <Kernel32.NVME_PASS_THROUGH_IOCTL>();
            passThrough.srb.HeaderLenght = (uint)Marshal.SizeOf <Kernel32.SRB_IO_CONTROL>();
            passThrough.srb.Signature    = Encoding.ASCII.GetBytes(Kernel32.IntelNVMeMiniPortSignature1);
            passThrough.srb.Timeout      = 10;
            passThrough.srb.ControlCode  = Kernel32.NVME_PASS_THROUGH_SRB_IO_CODE;
            passThrough.srb.ReturnCode   = 0;
            passThrough.srb.Length       = (uint)Marshal.SizeOf <Kernel32.NVME_PASS_THROUGH_IOCTL>() - (uint)Marshal.SizeOf <Kernel32.SRB_IO_CONTROL>();
            passThrough.NVMeCmd          = new uint[16];
            passThrough.NVMeCmd[0]       = 6; //identify
            passThrough.NVMeCmd[10]      = 1; //return to host
            passThrough.Direction        = Kernel32.NVME_DIRECTION.NVME_FROM_DEV_TO_HOST;
            passThrough.QueueId          = 0;
            passThrough.DataBufferLen    = (uint)passThrough.DataBuffer.Length;
            passThrough.MetaDataLen      = 0;
            passThrough.ReturnBufferLen  = (uint)Marshal.SizeOf <Kernel32.NVME_PASS_THROUGH_IOCTL>();

            int    length = Marshal.SizeOf <Kernel32.NVME_PASS_THROUGH_IOCTL>();
            IntPtr buffer = Marshal.AllocHGlobal(length);

            Marshal.StructureToPtr(passThrough, buffer, false);

            bool validTransfer = Kernel32.DeviceIoControl(handle, Kernel32.IOCTL.IOCTL_SCSI_MINIPORT, buffer, length, buffer, length, out _, IntPtr.Zero);

            Marshal.FreeHGlobal(buffer);

            if (validTransfer)
            {
            }
            else
            {
                handle.Close();
                handle = null;
            }
            return(handle);
        }
        /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
        /// <param name="handle">The current handle to check.</param>
        /// <param name="lastError">The result of Marshal.GetLastWin32Error()</param>
        /// <param name="throwException"><see langword="true"/> will throw an <exception cref="Resources.Handle_Is_Invalid_Win32Error"/>, <see langword="false"/> will not raise this exception..</param>
        /// <returns><see langword="true"/> on success, <see langword="false"/> otherwise.</returns>
        /// <exception cref="ArgumentException"/>
        internal static bool IsValidHandle(SafeHandle handle, int lastError, bool throwException = true)
        {
            if (handle == null || handle.IsClosed || handle.IsInvalid)
            {
                if (handle != null)
                {
                    handle.Close();
                }

                if (throwException)
                {
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.Handle_Is_Invalid_Win32Error, lastError));
                }

                return(false);
            }

            return(true);
        }
        /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
        /// <param name="handle">The current handle to check.</param>
        /// <param name="throwException"><see langword="true"/> will throw an <exception cref="Resources.Handle_Is_Invalid"/>, <see langword="false"/> will not raise this exception..</param>
        /// <returns><see langword="true"/> on success, <see langword="false"/> otherwise.</returns>
        /// <exception cref="ArgumentException"/>
        internal static bool IsValidHandle(SafeHandle handle, bool throwException = true)
        {
            if (handle == null || handle.IsClosed || handle.IsInvalid)
            {
                if (handle != null)
                {
                    handle.Close();
                }

                if (throwException)
                {
                    throw new ArgumentException(Resources.Handle_Is_Invalid);
                }

                return(false);
            }

            return(true);
        }
Exemplo n.º 30
0
        /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
        /// <param name="handle">The current handle to check.</param>
        /// <param name="lastError">The result of Marshal.GetLastWin32Error()</param>
        /// <param name="path">The path on which the Exception occurred.</param>
        /// <param name="throwException"><c>true</c> will throw an <exception cref="Resources.Handle_Is_Invalid_Win32Error"/>, <c>false</c> will not raise this exception..</param>
        /// <returns><c>true</c> on success, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentException"/>
        /// <exception cref="Exception"/>
        internal static bool IsValidHandle(SafeHandle handle, int lastError, string path, bool throwException = true)
        {
            if (null == handle || handle.IsClosed || handle.IsInvalid)
            {
                if (null != handle)
                {
                    handle.Close();
                }

                if (throwException)
                {
                    NativeError.ThrowException(lastError, path);
                }

                return(false);
            }

            return(true);
        }