in src/Microsoft.Diagnostics.Runtime/DataReaders/Windows/WindowsProcessDataReader.cs [30:74]
public WindowsProcessDataReader(int processId, WindowsProcessDataReaderMode mode)
{
if (mode == WindowsProcessDataReaderMode.Snapshot)
{
_originalPid = processId;
// Throws InvalidOperationException, which is similar to how Process.Start fails if it can't start the process.
Process process = Process.GetProcessById(processId);
int hr = PssCaptureSnapshot(process.Handle, PSS_CAPTURE_FLAGS.PSS_CAPTURE_VA_CLONE, IntPtr.Size == 8 ? 0x0010001F : 0x0001003F, out _snapshotHandle);
if (hr != 0)
throw new InvalidOperationException($"Could not create snapshot to process. Error {hr}.");
hr = PssQuerySnapshot(_snapshotHandle, PSS_QUERY_INFORMATION_CLASS.PSS_QUERY_VA_CLONE_INFORMATION, out _cloneHandle, IntPtr.Size);
if (hr != 0)
throw new InvalidOperationException($"Could not create snapshot to process. Error {hr}.");
ProcessId = GetProcessId(_cloneHandle);
}
else
{
ProcessId = processId;
}
_process = WindowsFunctions.NativeMethods.OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, ProcessId);
if (_process == IntPtr.Zero)
{
if (!WindowsFunctions.IsProcessRunning(ProcessId))
throw new ArgumentException($"Process {processId} is not running.");
int hr = Marshal.GetLastWin32Error();
throw new ArgumentException($"Could not attach to process {processId}, error: {hr:x}");
}
using Process p = Process.GetCurrentProcess();
if (DataTarget.PlatformFunctions.TryGetWow64(p.Handle, out bool wow64)
&& DataTarget.PlatformFunctions.TryGetWow64(_process, out bool targetWow64)
&& wow64 != targetWow64)
{
throw new InvalidOperationException("Mismatched architecture between this process and the target process.");
}
if (mode == WindowsProcessDataReaderMode.Suspend)
_suspension = new WindowsThreadSuspender(ProcessId);
}