using System.Diagnostics; using System.Runtime.InteropServices; namespace ZB.MOM.WW.MxGateway.Server.Workers; /// /// backed by . /// public sealed class SystemRunningProcessInspector : IRunningProcessInspector { // PROCESS_QUERY_LIMITED_INFORMATION: the least access that reads the image path, the command // line and the start time, and the one granted across WOW64 (x64 gateway, x86 worker). private const uint ProcessQueryLimitedInformation = 0x1000; // PROCESSINFOCLASS.ProcessCommandLineInformation (Windows 8.1+). Returns a UNICODE_STRING // followed by its buffer, and works across bitness, unlike reading the target's PEB. private const int ProcessCommandLineInformation = 60; /// public IReadOnlyList GetProcessesByName(string processName) { List results = []; Process[] processes = Process.GetProcessesByName(processName); try { foreach (Process process in processes) { results.Add(new RunningProcessInfo( process.Id, TryGetExecutablePath(process), TryGetCommandLine(process.Id), TryGetStartTime(process))); } } finally { foreach (Process process in processes) { process.Dispose(); } } return results; } /// public void Kill(int processId) { using Process process = Process.GetProcessById(processId); process.Kill(entireProcessTree: true); } /// public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt) { startedAt = null; Process process; try { process = Process.GetProcessById(processId); } catch (ArgumentException) { // Not running. return false; } catch (InvalidOperationException) { return false; } using (process) { try { if (process.HasExited) { return false; } } catch (Exception exception) when (exception is InvalidOperationException or System.ComponentModel.Win32Exception or NotSupportedException) { // Cannot open it to ask, but GetProcessById found it: treat it as running. } startedAt = TryGetStartTime(process); return true; } } /// /// Reads another process's command line. Windows only; elsewhere or /// when it cannot be read (access denied, the process exited). /// /// The process to read. /// The command line, or . internal static string? TryGetCommandLine(int processId) { if (!OperatingSystem.IsWindows()) { return null; } IntPtr handle = OpenProcess(ProcessQueryLimitedInformation, inheritHandle: false, processId); if (handle == IntPtr.Zero) { return null; } try { // The sizing call fails with STATUS_INFO_LENGTH_MISMATCH and reports the size needed. _ = NtQueryInformationProcess(handle, ProcessCommandLineInformation, IntPtr.Zero, 0, out int length); if (length <= 0 || length > 1024 * 1024) { return null; } IntPtr buffer = Marshal.AllocHGlobal(length); try { int status = NtQueryInformationProcess(handle, ProcessCommandLineInformation, buffer, length, out _); if (status != 0) { return null; } // UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } — the // pointer is naturally aligned, so it sits at offset IntPtr.Size. int byteLength = (ushort)Marshal.ReadInt16(buffer); IntPtr text = Marshal.ReadIntPtr(buffer, IntPtr.Size); return byteLength == 0 || text == IntPtr.Zero ? string.Empty : Marshal.PtrToStringUni(text, byteLength / 2); } finally { Marshal.FreeHGlobal(buffer); } } finally { _ = CloseHandle(handle); } } private static string? TryGetExecutablePath(Process process) { try { return process.MainModule?.FileName; } catch (Exception exception) when (exception is InvalidOperationException or System.ComponentModel.Win32Exception or NotSupportedException) { // Access to the main module can be denied (e.g. a 64-bit gateway // querying a 32-bit worker, or a process owned by another user). return null; } } private static DateTimeOffset? TryGetStartTime(Process process) { try { return new DateTimeOffset(process.StartTime.ToUniversalTime(), TimeSpan.Zero); } catch (Exception exception) when (exception is InvalidOperationException or System.ComponentModel.Win32Exception or NotSupportedException) { return null; } } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr OpenProcess(uint desiredAccess, bool inheritHandle, int processId); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr handle); [DllImport("ntdll.dll")] private static extern int NtQueryInformationProcess( IntPtr processHandle, int processInformationClass, IntPtr processInformation, int processInformationLength, out int returnLength); }