|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.ComponentModel; |
| 7 | +using System.Diagnostics; |
| 8 | +using System.Runtime.InteropServices; |
| 9 | +using System.Runtime.InteropServices.Marshalling; |
| 10 | + |
| 11 | +#pragma warning disable CA1823 // analyzer incorrectly flags fixed buffer length const (https://github.com/dotnet/roslyn/issues/37593) |
| 12 | + |
| 13 | +internal static partial class Interop |
| 14 | +{ |
| 15 | + internal static partial class Process |
| 16 | + { |
| 17 | + private const ulong SecondsToNanoseconds = 1000000000; |
| 18 | + private const ulong MicroSecondsToNanoSeconds = 1000; |
| 19 | + |
| 20 | + internal struct proc_stats |
| 21 | + { |
| 22 | + internal long startTime; |
| 23 | + internal int nice; |
| 24 | + internal ulong userTime; /* in ticks */ |
| 25 | + internal ulong systemTime; /* in ticks */ |
| 26 | + } |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Queries the OS for the list of all running processes and returns the PID for each |
| 30 | + /// </summary> |
| 31 | + /// <returns>Returns a list of PIDs corresponding to all running processes</returns> |
| 32 | + internal static unsafe int[] ListAllPids() |
| 33 | + { |
| 34 | + kinfo_proc* entries = GetProcInfo(0, false, out int numProcesses); |
| 35 | + try |
| 36 | + { |
| 37 | + if (numProcesses <= 0) |
| 38 | + { |
| 39 | + throw new Win32Exception(SR.CantGetAllPids); |
| 40 | + } |
| 41 | + |
| 42 | + var list = new ReadOnlySpan<kinfo_proc>(entries, numProcesses); |
| 43 | + var pids = new int[numProcesses]; |
| 44 | + |
| 45 | + // walk through process list and skip kernel threads |
| 46 | + int idx = 0; |
| 47 | + for (int i = 0; i < list.Length; i++) |
| 48 | + { |
| 49 | + if (list[i].p_ppid == 0) |
| 50 | + { |
| 51 | + // skip kernel threads |
| 52 | + numProcesses -= 1; |
| 53 | + } |
| 54 | + else |
| 55 | + { |
| 56 | + pids[idx] = list[i].p_pid; |
| 57 | + idx += 1; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // Remove extra elements |
| 62 | + Array.Resize<int>(ref pids, numProcesses); |
| 63 | + return pids; |
| 64 | + } |
| 65 | + finally |
| 66 | + { |
| 67 | + NativeMemory.Free(entries); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + /// <summary> |
| 72 | + /// Gets executable name for process given it's PID |
| 73 | + /// </summary> |
| 74 | + /// <param name="pid">The PID of the process</param> |
| 75 | + public static unsafe string GetProcPath(int pid) |
| 76 | + { |
| 77 | + // OpenBSD has no KERN_PROC_PATHNAME. The closest available information is the |
| 78 | + // process argv, whose first entry is the path the process was executed with. |
| 79 | + ReadOnlySpan<int> sysctlName = [CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_ARGV]; |
| 80 | + |
| 81 | + byte* pBuffer = null; |
| 82 | + uint bytesLength = 0; |
| 83 | + try |
| 84 | + { |
| 85 | + Interop.Sys.Sysctl(sysctlName, ref pBuffer, ref bytesLength); |
| 86 | + |
| 87 | + if (pBuffer == null || bytesLength < (uint)sizeof(byte*)) |
| 88 | + { |
| 89 | + return string.Empty; |
| 90 | + } |
| 91 | + |
| 92 | + // The kernel relocates the argv pointer array to point within the returned buffer. |
| 93 | + byte* argv0 = ((byte**)pBuffer)[0]; |
| 94 | + return argv0 is null ? string.Empty : Utf8StringMarshaller.ConvertToManaged(argv0) ?? string.Empty; |
| 95 | + } |
| 96 | + finally |
| 97 | + { |
| 98 | + NativeMemory.Free(pBuffer); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + /// <summary> |
| 103 | + /// Attempts to recover a process name that was truncated in kinfo_proc.p_comm by reading |
| 104 | + /// the full name from the process argv. |
| 105 | + /// </summary> |
| 106 | + /// <param name="pid">The PID of the process.</param> |
| 107 | + /// <param name="prefix">The (possibly truncated) p_comm value used to validate the recovered name.</param> |
| 108 | + /// <returns>The full process name, or null if it could not be recovered.</returns> |
| 109 | + private static unsafe string? GetUntruncatedProcessName(int pid, string prefix) |
| 110 | + { |
| 111 | + ReadOnlySpan<int> sysctlName = [CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_ARGV]; |
| 112 | + |
| 113 | + byte* pBuffer = null; |
| 114 | + uint bytesLength = 0; |
| 115 | + try |
| 116 | + { |
| 117 | + Interop.Sys.Sysctl(sysctlName, ref pBuffer, ref bytesLength); |
| 118 | + |
| 119 | + if (pBuffer == null || bytesLength < (uint)sizeof(byte*)) |
| 120 | + { |
| 121 | + return null; |
| 122 | + } |
| 123 | + |
| 124 | + // The kernel relocates the argv pointer array to point within the returned buffer. |
| 125 | + // For native executables the name is argv[0]; for scripts argv[0] is the interpreter |
| 126 | + // and argv[1] is the script, so check the first two NULL-terminated arguments. |
| 127 | + byte** argv = (byte**)pBuffer; |
| 128 | + for (int i = 0; i < 2 && argv[i] is not null; i++) |
| 129 | + { |
| 130 | + string arg = Utf8StringMarshaller.ConvertToManaged(argv[i]) ?? string.Empty; |
| 131 | + |
| 132 | + // Strip directory names. |
| 133 | + int nameStart = arg.LastIndexOf('/') + 1; |
| 134 | + string name = nameStart == 0 ? arg : arg.Substring(nameStart); |
| 135 | + |
| 136 | + if (name.StartsWith(prefix, StringComparison.Ordinal)) |
| 137 | + { |
| 138 | + return name; |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + return null; |
| 143 | + } |
| 144 | + finally |
| 145 | + { |
| 146 | + NativeMemory.Free(pBuffer); |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + /// <summary> |
| 151 | + /// Gets the process information for a given process |
| 152 | + /// </summary> |
| 153 | + /// <param name="pid">The PID (process ID) of the process</param> |
| 154 | + /// <returns> |
| 155 | + /// Returns a valid ProcessInfo struct for valid processes that the caller |
| 156 | + /// has permission to access; otherwise, returns null |
| 157 | + /// </returns> |
| 158 | + public static unsafe ProcessInfo? GetProcessInfoById(int pid) |
| 159 | + { |
| 160 | + // Negative PIDs are invalid |
| 161 | + ArgumentOutOfRangeException.ThrowIfNegative(pid); |
| 162 | + |
| 163 | + ProcessInfo info; |
| 164 | + |
| 165 | + kinfo_proc* kinfo = GetProcInfo(pid, true, out int count); |
| 166 | + try |
| 167 | + { |
| 168 | + // The process may have exited between the time its PID was enumerated and now, |
| 169 | + // in which case no entries are returned. Report it as not found rather than failing. |
| 170 | + if (count < 1) |
| 171 | + { |
| 172 | + return null; |
| 173 | + } |
| 174 | + |
| 175 | + var process = new ReadOnlySpan<kinfo_proc>(kinfo, count); |
| 176 | + |
| 177 | + // Get the process information for the specified pid |
| 178 | + info = new ProcessInfo(); |
| 179 | + |
| 180 | + info.ProcessName = Utf8StringMarshaller.ConvertToManaged(kinfo->p_comm)!; |
| 181 | + |
| 182 | + // p_comm is limited to KI_MAXCOMLEN - 1 characters. When the name is at that |
| 183 | + // limit it may be truncated, so try to recover the full name from the process argv. |
| 184 | + if (info.ProcessName.Length >= KI_MAXCOMLEN - 1) |
| 185 | + { |
| 186 | + info.ProcessName = GetUntruncatedProcessName(pid, info.ProcessName) ?? info.ProcessName; |
| 187 | + } |
| 188 | + |
| 189 | + info.BasePriority = kinfo->p_nice; |
| 190 | + |
| 191 | + // OpenBSD's KERN_PROC sysctl always reports p_vm_map_size as 0, so derive the |
| 192 | + // virtual size from the text, data, and stack segment sizes instead. |
| 193 | + long pageSize = Environment.SystemPageSize; |
| 194 | + info.VirtualBytes = ((long)kinfo->p_vm_tsize + kinfo->p_vm_dsize + kinfo->p_vm_ssize) * pageSize; |
| 195 | + // OpenBSD does not track a separate peak virtual size; report the current size. |
| 196 | + info.VirtualBytesPeak = info.VirtualBytes; |
| 197 | + info.WorkingSet = kinfo->p_vm_rssize; |
| 198 | + // p_uru_maxrss is the peak resident set size, reported in kilobytes. |
| 199 | + info.WorkingSetPeak = (long)kinfo->p_uru_maxrss * 1024; |
| 200 | + // OpenBSD does not expose a private byte count; approximate it with the |
| 201 | + // anonymous (data + stack) segment sizes. |
| 202 | + info.PrivateBytes = ((long)kinfo->p_vm_dsize + kinfo->p_vm_ssize) * pageSize; |
| 203 | + info.SessionId = kinfo->p_sid; |
| 204 | + |
| 205 | + for (int i = 0; i < process.Length; i++) |
| 206 | + { |
| 207 | + // KERN_PROC_SHOW_THREADS returns a process-summary entry with p_tid == -1 |
| 208 | + // ahead of the real per-thread entries. Skip it so only actual threads are reported. |
| 209 | + if (process[i].p_tid < 0) |
| 210 | + { |
| 211 | + continue; |
| 212 | + } |
| 213 | + |
| 214 | + var ti = new ThreadInfo() |
| 215 | + { |
| 216 | + _processId = pid, |
| 217 | + _threadId = (ulong)process[i].p_tid, |
| 218 | + _basePriority = process[i].p_nice, |
| 219 | + _startAddress = null // OpenBSD's kinfo_proc does not expose a thread start address. |
| 220 | + }; |
| 221 | + info._threadInfoList.Add(ti); |
| 222 | + } |
| 223 | + } |
| 224 | + finally |
| 225 | + { |
| 226 | + NativeMemory.Free(kinfo); |
| 227 | + } |
| 228 | + |
| 229 | + return info; |
| 230 | + } |
| 231 | + |
| 232 | + /// <summary> |
| 233 | + /// Gets the process information for a given process |
| 234 | + /// </summary> |
| 235 | + /// <param name="pid">The PID (process ID) of the process</param> |
| 236 | + /// <param name="tid">The TID (thread ID) of the process</param> |
| 237 | + /// <returns> |
| 238 | + /// Returns basic info about thread. If tid is 0, it will return |
| 239 | + /// info for process e.g. main thread. |
| 240 | + /// </returns> |
| 241 | + public static unsafe proc_stats GetThreadInfo(int pid, int tid) |
| 242 | + { |
| 243 | + proc_stats ret = default; |
| 244 | + int count; |
| 245 | + |
| 246 | + kinfo_proc* info = GetProcInfo(pid, (tid != 0), out count); |
| 247 | + try |
| 248 | + { |
| 249 | + if (info != null && count >= 1) |
| 250 | + { |
| 251 | + if (tid == 0) |
| 252 | + { |
| 253 | + ret.startTime = (int)info->p_ustart_sec; |
| 254 | + ret.nice = info->p_nice; |
| 255 | + ret.userTime = (ulong)info->p_uutime_sec * SecondsToNanoseconds + (ulong)info->p_uutime_usec * MicroSecondsToNanoSeconds; |
| 256 | + ret.systemTime = (ulong)info->p_ustime_sec * SecondsToNanoseconds + (ulong)info->p_ustime_usec * MicroSecondsToNanoSeconds; |
| 257 | + } |
| 258 | + else |
| 259 | + { |
| 260 | + var list = new ReadOnlySpan<kinfo_proc>(info, count); |
| 261 | + for (int i = 0; i < list.Length; i++) |
| 262 | + { |
| 263 | + if (list[i].p_tid == tid) |
| 264 | + { |
| 265 | + ret.startTime = (int)list[i].p_ustart_sec; |
| 266 | + ret.nice = list[i].p_nice; |
| 267 | + ret.userTime = (ulong)list[i].p_uutime_sec * SecondsToNanoseconds + (ulong)list[i].p_uutime_usec * MicroSecondsToNanoSeconds; |
| 268 | + ret.systemTime = (ulong)list[i].p_ustime_sec * SecondsToNanoseconds + (ulong)list[i].p_ustime_usec * MicroSecondsToNanoSeconds; |
| 269 | + break; |
| 270 | + } |
| 271 | + } |
| 272 | + } |
| 273 | + } |
| 274 | + } |
| 275 | + finally |
| 276 | + { |
| 277 | + NativeMemory.Free(info); |
| 278 | + } |
| 279 | + |
| 280 | + return ret; |
| 281 | + } |
| 282 | + } |
| 283 | +} |
0 commit comments