private static bool GetFileNameFromHandle(IntPtr handle, int processId, out string fileName)
        {
            IntPtr            currentProcess = GetCurrentProcess();
            bool              remote         = processId != GetProcessId(currentProcess);
            SafeProcessHandle processHandle  = null;
            SafeObjectHandle  objectHandle   = null;

            try
            {
                if (remote)
                {
                    processHandle = OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, true, processId);
                    if (DuplicateHandle(processHandle.DangerousGetHandle(), handle, currentProcess, out objectHandle, 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS))
                    {
                        handle = objectHandle.DangerousGetHandle();
                    }
                }
                return(GetFileNameFromHandle(handle, out fileName, 200));
            }
            finally
            {
                if (remote)
                {
                    if (processHandle != null)
                    {
                        processHandle.Close();
                    }
                    if (objectHandle != null)
                    {
                        objectHandle.Close();
                    }
                }
            }
        }
        private static bool ExtractFileNameFromHandle(SYSTEM_HANDLE_ENTRY handleEntry, SafeHandle processHandle, out string fileName)
        {
            var handle = (IntPtr)handleEntry.HandleValue;

            SafeObjectHandle duplicatedHandle = null;

            try
            {
                if (!DuplicateHandle(handle, processHandle, out duplicatedHandle))
                {
                    fileName = null;
                    return(false);
                }

                handle = duplicatedHandle.DangerousGetHandle();

                if (GetHandleType(handle, out var handleType) && handleType == SystemHandleType.OB_TYPE_FILE)
                {
                    if (GetFileNameFromHandle(handle, out var devicePath))
                    {
                        return(ConvertDevicePathToDosPath(devicePath, out fileName));
                    }
                }
            }
            finally
            {
                duplicatedHandle?.Close();
            }

            fileName = null;
            return(false);
        }
Example #3
0
        static unsafe void FinishOverlappedAsynchronously(SafeObjectHandle handle, PinnedStruct <OVERLAPPED> overlapped,
                                                          ManualResetEvent finishedEvent, TaskCompletionSource <int> completionSource, CancellationToken cancellationToken)
        {
            var alreadyFinished          = false;
            var lockObject               = new object();
            WaitOrTimerCallback callback = (state, timedOut) =>
            {
                var overlappedState = (OverlappedState)state;
                lock (lockObject)
                {
                    if (alreadyFinished)
                    {
                        return;
                    }

                    overlappedState.Unregister();

                    if (overlappedState.IsCancellation || cancellationToken.IsCancellationRequested)
                    {
                        CancelIoEx(handle, (OVERLAPPED *)overlapped.Pointer);
                        completionSource.SetCanceled();
                    }
                    else
                    {
                        int bytesReturned;
                        var overlappedResult = GetOverlappedResult(handle, (OVERLAPPED *)overlapped.Pointer,
                                                                   out bytesReturned, false);

                        overlapped.Dispose();
                        finishedEvent.Dispose();

                        if (overlappedResult)
                        {
                            completionSource.SetResult(bytesReturned);
                        }
                        else
                        {
                            SetFromLastWin32Exception(completionSource);
                        }
                    }

                    alreadyFinished = true;
                }
            };

            lock (lockObject)
            {
                var finishedState  = new OverlappedState(false);
                var cancelledState = new OverlappedState(true);
                var finishedWait   = ThreadPool.RegisterWaitForSingleObject(finishedEvent, callback, finishedState, -1, true);
                cancelledState.OtherRegistration = finishedWait;
                if (cancellationToken != CancellationToken.None)
                {
                    var cancelledWait = ThreadPool.RegisterWaitForSingleObject(cancellationToken.WaitHandle,
                                                                               callback,
                                                                               cancelledState, -1, true);
                    finishedState.OtherRegistration = cancelledWait;
                }
            }
        }
Example #4
0
 public static unsafe bool GetOverlappedResult(
     SafeObjectHandle hFile,
     NativeOverlapped *lpOverlapped,
     out int lpNumberOfBytesTransferred,
     bool bWait)
 {
     return(GetOverlappedResult(hFile, (OVERLAPPED *)lpOverlapped, out lpNumberOfBytesTransferred, bWait));
 }
Example #5
0
 public static unsafe Task <int> ReadFileAsync(SafeObjectHandle handle, IntPtr buffer, int numberOfBytesToRead,
                                               CancellationToken cancellationToken = default(CancellationToken))
 {
     return(OverlappedAsync(handle, lpOverlapped =>
     {
         return ReadFile(handle, buffer.ToPointer(), numberOfBytesToRead, null, lpOverlapped);
     }, cancellationToken));
 }
Example #6
0
 public static async Task <int> WriteFileAsync <T>(SafeObjectHandle handle, ArraySegment <T> arraySegment,
                                                   CancellationToken cancellationToken = default(CancellationToken))
     where T : struct
 {
     using (var asFixed = new FixedArraySegment <T>(arraySegment))
     {
         return(await WriteFileAsync(handle, asFixed.Pointer, asFixed.SizeInBytes, cancellationToken));
     }
 }
Example #7
0
 public static unsafe bool WriteFile(
     SafeObjectHandle hFile,
     void *lpBuffer,
     int nNumberOfBytesToWrite,
     int *lpNumberOfBytesWritten,
     NativeOverlapped *lpOverlapped)
 {
     return(WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, (OVERLAPPED *)lpOverlapped));
 }
Example #8
0
 public static unsafe bool ReadFile(
     SafeObjectHandle hFile,
     void *lpBuffer,
     int nNumberOfBytesToRead,
     int *lpNumberOfBytesRead,
     NativeOverlapped *lpOverlapped)
 {
     return(ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, (OVERLAPPED *)lpOverlapped));
 }
 public static extern unsafe bool DeviceIoControl(
     SafeObjectHandle hDevice,
     uint dwIoControlCode,
     IntPtr inBuffer,
     int nInBufferSize,
     IntPtr outBuffer,
     int nOutBufferSize,
     out int pBytesReturned,
     OVERLAPPED* lpOverlapped);
Example #10
0
        public static string HidD_GetManufacturerString(SafeObjectHandle hidDeviceObject)
        {
            string result;
            if (!HidD_GetManufacturerString(hidDeviceObject, out result))
            {
                throw new Win32Exception();
            }

            return result;
        }
Example #11
0
        public static bool IsWow64Process(SafeObjectHandle hProcess)
        {
            bool result;
            if (!IsWow64Process(hProcess, out result))
            {
                throw new Win32Exception();
            }

            return result;
        }
Example #12
0
        public static HiddAttributes HidD_GetAttributes(SafeObjectHandle hFile)
        {
            var result = HiddAttributes.Create();
            if (!HidD_GetAttributes(hFile, ref result))
            {
                throw new Win32Exception();
            }

            return result;
        }
Example #13
0
        public static SafePreparsedDataHandle HidD_GetPreparsedData(SafeObjectHandle hDevice)
        {
            SafePreparsedDataHandle preparsedDataHandle;
            if (!HidD_GetPreparsedData(hDevice, out preparsedDataHandle))
            {
                throw new Win32Exception();
            }

            return preparsedDataHandle;
        }
Example #14
0
 public static bool DeviceIoControl(
     SafeObjectHandle hDevice,
     uint dwIoControlCode,
     IntPtr inBuffer,
     int nInBufferSize,
     IntPtr outBuffer,
     int nOutBufferSize,
     out int pBytesReturned)
 {
     return(DeviceIoControlCore(hDevice, dwIoControlCode, inBuffer, nInBufferSize, outBuffer, nOutBufferSize,
                                out pBytesReturned, null));
 }
Example #15
0
 public static unsafe bool DeviceIoControl(
     SafeObjectHandle hDevice,
     int dwIoControlCode,
     void *inBuffer,
     int nInBufferSize,
     void *outBuffer,
     int nOutBufferSize,
     out int pBytesReturned,
     NativeOverlapped *lpOverlapped)
 {
     return(DeviceIoControl(hDevice, dwIoControlCode, inBuffer, nInBufferSize, outBuffer, nOutBufferSize, out pBytesReturned, (OVERLAPPED *)lpOverlapped));
 }
Example #16
0
        public static bool DeviceIoControl(
            SafeObjectHandle hDevice,
            uint dwIoControlCode,
            IntPtr inBuffer,
            int nInBufferSize,
            IntPtr outBuffer,
            int nOutBufferSize,
            OVERLAPPED lpOverlapped)
        {
            int pBytesReturned;

            return(DeviceIoControlCore(hDevice, dwIoControlCode, inBuffer, nInBufferSize, outBuffer, nOutBufferSize,
                                       out pBytesReturned, lpOverlapped));
        }
Example #17
0
 /// <inheritdoc cref="CreateFile(char*, ACCESS_MASK, FileShare, SECURITY_ATTRIBUTES*, CreationDisposition, CreateFileFlags, SafeObjectHandle)"/>
 /// <devremarks>
 /// This should be removed as part of delivering <see href="https://github.com/dotnet/pinvoke/issues/286">the string-overload codegen feature</see>.
 /// </devremarks>
 public static unsafe SafeObjectHandle CreateFile(
     string filename,
     ACCESS_MASK access,
     FileShare share,
     [Friendly(FriendlyFlags.In | FriendlyFlags.Optional)] SECURITY_ATTRIBUTES *securityAttributes,
     CreationDisposition creationDisposition,
     CreateFileFlags flagsAndAttributes,
     SafeObjectHandle templateFile)
 {
     fixed(char *pFileName = filename)
     {
         return(CreateFile(pFileName, access, share, securityAttributes, creationDisposition, flagsAndAttributes, templateFile));
     }
 }
Example #18
0
        /// <summary>Writes data synchronously to the specified file or input/output (I/O) device.</summary>
        /// <param name="hFile">
        ///     A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape
        ///     drive, socket, communications resource, mailslot, or pipe).
        ///     <para>
        ///         The hFile parameter must have been created with the write access. For more information, see Generic Access
        ///         Rights and File Security and Access Rights.
        ///     </para>
        /// </param>
        /// <param name="lpBuffer">A pointer to the buffer containing the data to be written to the file or device.</param>
        /// <param name="nNumberOfBytesToWrite">
        ///     The number of bytes to be written to the file or device.
        ///     <para>
        ///         A value of zero specifies a null write operation. The behavior of a null write operation depends on the
        ///         underlying file system or communications technology.
        ///     </para>
        /// </param>
        /// <returns>The number of bytes written.</returns>
        /// <exception cref="Win32Exception">Thrown if the native method return false (Write failed).</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="hFile" /> is <see langword="null" />.</exception>
        public static unsafe int WriteFile(SafeObjectHandle hFile, void* lpBuffer, int nNumberOfBytesToWrite)
        {
            if (hFile == null)
            {
                throw new ArgumentNullException(nameof(hFile));
            }

            var bytesWritten = (NullableUInt32)0;
            if (!WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, bytesWritten, null))
            {
                throw new Win32Exception();
            }

            return (int)bytesWritten.Value;
        }
Example #19
0
        /// <summary>Reads data synchronously from the specified file or input/output (I/O) device.</summary>
        /// <param name="hFile">
        ///     A handle to the device (for example, a file, file stream, physical disk, volume, console buffer,
        ///     tape drive, socket, communications resource, mailslot, or pipe).
        ///     <para>The hFile parameter must have been created with read access.</para>
        /// </param>
        /// <param name="lpBuffer">A pointer to the buffer that receives the data read from a file or device.</param>
        /// <param name="nNumberOfBytesToRead">The maximum number of bytes to be read.</param>
        /// <returns>The number of bytes read.</returns>
        /// <exception cref="Win32Exception">Thrown if the native method return false (Read failed).</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="hFile" /> is <see langword="null" />.</exception>
        public static unsafe uint ReadFile(SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead)
        {
            if (hFile == null)
            {
                throw new ArgumentNullException(nameof(hFile));
            }

            var bytesRead = (NullableUInt32)0;
            if (!ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, bytesRead, null))
            {
                throw new Win32Exception();
            }

            return (uint)bytesRead;
        }
Example #20
0
        /// <summary>Retrieves information about next process encountered in a system snapshot.</summary>
        /// <param name="hSnapshot">
        ///     A handle to the snapshot returned from a previous call to the
        ///     <see cref="CreateToolhelp32Snapshot" /> function.
        /// </param>
        /// <returns>
        ///     An enumeration of all the <see cref="PROCESSENTRY32" /> present in the snapshot.
        /// </returns>
        /// <exception cref="Win32Exception">Thrown if any error occurs.</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="hSnapshot" /> is <see langword="null" />.</exception>
        public static IEnumerable<PROCESSENTRY32> Process32Enumerate(SafeObjectHandle hSnapshot)
        {
            if (hSnapshot == null)
            {
                throw new ArgumentNullException(nameof(hSnapshot));
            }

            var entry = Process32First(hSnapshot);

            while (entry != null)
            {
                yield return entry;
                entry = Process32Next(hSnapshot);
            }
        }
Example #21
0
        /// <summary>Retrieves information about the next process encountered in a system snapshot.</summary>
        /// <param name="hSnapshot">
        ///     A handle to the snapshot returned from a previous call to the
        ///     <see cref="CreateToolhelp32Snapshot" /> function.
        /// </param>
        /// <returns>
        ///     The next <see cref="PROCESSENTRY32" /> if there was any or <see langword="null" /> otherwise (No more values
        ///     in the snapshot).
        /// </returns>
        /// <exception cref="Win32Exception">Thrown if any error occurs.</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="hSnapshot" /> is <see langword="null" />.</exception>
        public static PROCESSENTRY32 Process32Next(SafeObjectHandle hSnapshot)
        {
            if (hSnapshot == null)
            {
                throw new ArgumentNullException(nameof(hSnapshot));
            }

            var entry = new PROCESSENTRY32();
            if (Process32Next(hSnapshot, entry))
            {
                return entry;
            }

            var lastError = GetLastError();
            if (lastError != Win32ErrorCode.ERROR_NO_MORE_FILES)
            {
                throw new Win32Exception(lastError);
            }

            return null;
        }
Example #22
0
 public static extern unsafe bool ConnectNamedPipe(
     SafeObjectHandle hNamedPipe,
     OVERLAPPED* lpOverlapped);
Example #23
0
        /// <summary>Writes data synchronously to the specified file or input/output (I/O) device.</summary>
        /// <param name="hFile">
        ///     A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape
        ///     drive, socket, communications resource, mailslot, or pipe).
        ///     <para>
        ///         The hFile parameter must have been created with the write access. For more information, see Generic Access
        ///         Rights and File Security and Access Rights.
        ///     </para>
        /// </param>
        /// <param name="lpBuffer">The buffer containing the data to be written to the file or device.</param>
        /// <returns>The number of bytes written.</returns>
        /// <exception cref="Win32Exception">Thrown if the native method return false (Write failed).</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="hFile" /> is <see langword="null" />.</exception>
        public static int WriteFile(SafeObjectHandle hFile, ArraySegment<byte> lpBuffer)
        {
            if (hFile == null)
            {
                throw new ArgumentNullException(nameof(hFile));
            }

            unsafe
            {
                fixed (byte* pBuffer = lpBuffer.Array)
                {
                    var pStart = pBuffer + lpBuffer.Offset;
                    return WriteFile(hFile, pStart, lpBuffer.Count);
                }
            }
        }
Example #24
0
 public static extern bool CreatePipe(
     out SafeObjectHandle hReadPipe,
     out SafeObjectHandle hWritePipe,
     SECURITY_ATTRIBUTES lpPipeAttributes,
     int nSize);
Example #25
0
 public static extern bool K32EmptyWorkingSet(SafeObjectHandle hProcess);
Example #26
0
 public static extern bool GetNamedPipeServerSessionId(
     SafeObjectHandle Pipe,
     out int ServerSessionId);
Example #27
0
 public static extern bool IsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process);
Example #28
0
 public static extern bool QueryFullProcessImageName(
     SafeObjectHandle hProcess,
     QueryFullProcessImageNameFlags dwFlags,
     StringBuilder lpExeName,
     ref int lpdwSize);
Example #29
0
        /// <summary>Reads data synchronously from the specified file or input/output (I/O) device.</summary>
        /// <param name="hFile">
        ///     A handle to the device (for example, a file, file stream, physical disk, volume, console buffer,
        ///     tape drive, socket, communications resource, mailslot, or pipe).
        ///     <para>The hFile parameter must have been created with read access.</para>
        /// </param>
        /// <param name="nNumberOfBytesToRead">The maximum number of bytes to be read.</param>
        /// <returns>
        ///     The data that has been read. The segment returned might have a size smaller than
        ///     <paramref name="nNumberOfBytesToRead" /> if less bytes than requested have been read.
        /// </returns>
        /// <exception cref="Win32Exception">Thrown if the native method return false (Read failed).</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="hFile" /> is <see langword="null" />.</exception>
        public static ArraySegment<byte> ReadFile(SafeObjectHandle hFile, int nNumberOfBytesToRead)
        {
            var buffer = new byte[nNumberOfBytesToRead];
            var segment = new ArraySegment<byte>(buffer);

            var bytesRead = ReadFile(hFile, segment);
            return new ArraySegment<byte>(buffer, 0, bytesRead);
        }
Example #30
0
 public static extern SafeObjectHandle CreateFile(
     string filename,
     FileAccess access,
     FileShare share,
     SECURITY_ATTRIBUTES securityAttributes,
     CreationDisposition creationDisposition,
     CreateFileFlags flagsAndAttributes,
     SafeObjectHandle templateFile);
Example #31
0
 public static extern bool Process32Next(
     SafeObjectHandle hSnapshot,
     [In, Out] PROCESSENTRY32 lppe);
Example #32
0
 public static extern unsafe bool TransactNamedPipe(
     SafeObjectHandle hNamedPipe,
     void* lpInBuffer,
     int nInBufferSize,
     void* lpOutBuffer,
     int nOutBufferSize,
     out int lpBytesRead,
     OVERLAPPED* lpOverlapped);
Example #33
0
 public static extern bool SetNamedPipeHandleState(
     SafeObjectHandle hNamedPipe,
     NullablePipeMode lpMode,
     NullableUInt32 lpMaxCollectionCount,
     NullableUInt32 lpCollectDataTimeout);
Example #34
0
 public static extern unsafe bool PeekNamedPipe(
     SafeObjectHandle hNamedPipe,
     void* lpBuffer,
     int nBufferSize,
     out int lpBytesRead,
     out int lpTotalBytesAvail,
     out int lpBytesLeftThisMessage);
Example #35
0
        /// <summary>Reads data synchronously from the specified file or input/output (I/O) device.</summary>
        /// <param name="hFile">
        ///     A handle to the device (for example, a file, file stream, physical disk, volume, console buffer,
        ///     tape drive, socket, communications resource, mailslot, or pipe).
        ///     <para>The hFile parameter must have been created with read access.</para>
        /// </param>
        /// <param name="lpBuffer">A pointer to the buffer that receives the data read from a file or device.</param>
        /// <param name="nNumberOfBytesToRead">The maximum number of bytes to be read.</param>
        /// <returns>The number of bytes read.</returns>
        /// <exception cref="Win32Exception">Thrown if the native method return false (Read failed).</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="hFile" /> is <see langword="null" />.</exception>
        public static unsafe int ReadFile(SafeObjectHandle hFile, void* lpBuffer, int nNumberOfBytesToRead)
        {
            if (hFile == null)
            {
                throw new ArgumentNullException(nameof(hFile));
            }

            var bytesRead = (int?)0;
            if (!ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, ref bytesRead, null))
            {
                throw new Win32Exception();
            }

            return bytesRead.Value;
        }
Example #36
0
 public static extern unsafe bool GetOverlappedResult(
     SafeObjectHandle hFile,
     OVERLAPPED* lpOverlapped,
     out int lpNumberOfBytesTransferred,
     bool bWait);
Example #37
0
 /// <summary>Reads data synchronously from the specified file or input/output (I/O) device.</summary>
 /// <param name="hFile">
 ///     A handle to the device (for example, a file, file stream, physical disk, volume, console buffer,
 ///     tape drive, socket, communications resource, mailslot, or pipe).
 ///     <para>The hFile parameter must have been created with read access.</para>
 /// </param>
 /// <param name="lpBuffer">A buffer that receives the data read from a file or device.</param>
 /// <returns>The number of bytes read.</returns>
 /// <exception cref="Win32Exception">Thrown if the native method return false (Read failed).</exception>
 /// <exception cref="ArgumentNullException">If <paramref name="hFile" /> is <see langword="null" />.</exception>
 public static int ReadFile(SafeObjectHandle hFile, ArraySegment<byte> lpBuffer)
 {
     unsafe
     {
         fixed (byte* pBuffer = lpBuffer.Array)
         {
             var pStart = pBuffer + lpBuffer.Offset;
             return ReadFile(hFile, pStart, lpBuffer.Count);
         }
     }
 }
Example #38
0
 public static extern bool CancelIo(SafeObjectHandle hFile);
Example #39
0
        /// <summary>Get the elevation type of a token via <see cref="GetTokenInformation(SafeObjectHandle, TOKEN_INFORMATION_CLASS, void*, int, out int)" />.</summary>
        /// <param name="TokenHandle">
        ///     A handle to an access token from which information is retrieved. The handle must have
        ///     TOKEN_QUERY access.
        /// </param>
        /// <returns>The token elevation type</returns>
        /// <exception cref="ArgumentNullException"><paramref name="TokenHandle" /> is NULL.</exception>
        /// <exception cref="Win32Exception">If the call to <see cref="GetTokenInformation(SafeObjectHandle, TOKEN_INFORMATION_CLASS, void*, int, out int)" /> fails.</exception>
        public static TOKEN_ELEVATION_TYPE GetTokenElevationType(SafeObjectHandle TokenHandle)
        {
            if (TokenHandle == null)
            {
                throw new ArgumentNullException(nameof(TokenHandle));
            }

            var elevationType = default(TOKEN_ELEVATION_TYPE);

            bool success;
            unsafe
            {
                int returnLength;
                success = GetTokenInformation(
                    TokenHandle,
                    TOKEN_INFORMATION_CLASS.TokenElevationType,
                    &elevationType,
                    sizeof(TOKEN_ELEVATION_TYPE),
                    out returnLength);
            }

            if (!success)
            {
                throw new Win32Exception();
            }

            return elevationType;
        }
Example #40
0
 public static extern bool OpenProcessToken(
     IntPtr processHandle,
     TokenAccessRights desiredAccess,
     out SafeObjectHandle tokenHandle);
Example #41
0
 public static extern unsafe bool GetTokenInformation(
     SafeObjectHandle TokenHandle,
     TOKEN_INFORMATION_CLASS TokenInformationClass,
     void* TokenInformation,
     int TokenInformationLength,
     out int ReturnLength);
Example #42
0
 public static extern bool GetNamedPipeInfo(
     SafeObjectHandle hNamedPipe,
     out NamedPipeInfoFlags lpFlags,
     out int lpOutBufferSize,
     out int lpInBufferSize,
     out int lpMaxInstances);