internal SafeProcessHandle Invoke(int processId) { // Initialise a buffer to store the returned process handle var processHandleBuffer = LocalMemoryTools.AllocateMemoryForBuffer(IntPtr.Size); // Store an empty object attributes structure in a buffer var objectAttributesBuffer = LocalMemoryTools.StoreStructureInBuffer(new Structures.ObjectAttributes()); // Store a client id structure in a buffer var clientId = new Structures.ClientId { UniqueProcess = new IntPtr(processId), UniqueThread = IntPtr.Zero }; var clientIdBuffer = LocalMemoryTools.StoreStructureInBuffer(clientId); // Perform the syscall var syscallResult = _ntOpenProcessDelegate(processHandleBuffer, Enumerations.ProcessAccessMask.AllAccess, objectAttributesBuffer, clientIdBuffer); if (syscallResult != Enumerations.NtStatus.Success) { ExceptionHandler.ThrowWin32Exception("Failed to open a handle to the target process", syscallResult); } try { return(new SafeProcessHandle(Marshal.PtrToStructure <IntPtr>(processHandleBuffer), true)); } finally { LocalMemoryTools.FreeMemoryForBuffer(processHandleBuffer); LocalMemoryTools.FreeMemoryForBuffer(objectAttributesBuffer); LocalMemoryTools.FreeMemoryForBuffer(clientIdBuffer); } }
internal SafeThreadHandle Invoke(int threadId) { // Initialise a buffer to store the returned thread handle var threadHandleBuffer = MemoryTools.AllocateMemoryForBuffer(IntPtr.Size); // Store an empty object attributes structure in a buffer var objectAttributesBuffer = MemoryTools.StoreStructureInBuffer(new Structures.ObjectAttributes()); // Store a client id structure in a buffer var clientId = new Structures.ClientId { UniqueThread = new IntPtr(threadId) }; var clientIdBuffer = MemoryTools.StoreStructureInBuffer(clientId); // Perform the syscall var syscallResult = _ntOpenThreadDelegate(threadHandleBuffer, Enumerations.ThreadAccessMask.AllAccess, objectAttributesBuffer, clientIdBuffer); if (syscallResult != Enumerations.NtStatus.Success) { ExceptionHandler.ThrowWin32Exception("Failed to open a handle to a thread in the target process", syscallResult); } // Marshal the returned thread handle from the buffer var threadHandle = new SafeThreadHandle(Marshal.PtrToStructure <IntPtr>(threadHandleBuffer), true); MemoryTools.FreeMemoryForBuffer(threadHandleBuffer); MemoryTools.FreeMemoryForBuffer(objectAttributesBuffer); MemoryTools.FreeMemoryForBuffer(clientIdBuffer); return(threadHandle); }