| | | 1 | | using System; |
| | | 2 | | using System.Buffers; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.Globalization; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Linq; |
| | | 9 | | using System.Reflection.Metadata; |
| | | 10 | | using System.Text; |
| | | 11 | | using System.Threading; |
| | | 12 | | |
| | | 13 | | namespace LockCheck.Linux; |
| | | 14 | | |
| | | 15 | | internal static class ProcFileSystem |
| | | 16 | | { |
| | | 17 | | private static volatile int s_procMatchesPidNamespace; |
| | | 18 | | |
| | | 19 | | internal static HashSet<ILinuxProcessDetails> GetAllProcesses() |
| | | 20 | | { |
| | | 21 | | var result = new HashSet<ILinuxProcessDetails>(); |
| | | 22 | | foreach (int processId in EnumerateProcessIds()) |
| | | 23 | | { |
| | | 24 | | result.Add(new ProcInfo(processId)); |
| | | 25 | | } |
| | | 26 | | return result; |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | internal static Dictionary<(int, DateTime), ProcessInfo> GetProcessesByWorkingDirectory(List<string> directories) |
| | | 30 | | { |
| | | 31 | | var result = new Dictionary<(int, DateTime), ProcessInfo>(); |
| | | 32 | | |
| | | 33 | | foreach (int processId in EnumerateProcessIds()) |
| | | 34 | | { |
| | | 35 | | var pi = new ProcInfo(processId); |
| | | 36 | | |
| | | 37 | | if (!pi.HasError && !string.IsNullOrEmpty(pi.CurrentDirectory)) |
| | | 38 | | { |
| | | 39 | | // If the process' current directory is the search path itself, or it is somewhere nested below it, |
| | | 40 | | // we have to take it into account. This will also account for differences in the two when the |
| | | 41 | | // search path does not end with a '/'. |
| | | 42 | | if (directories.FindIndex(d => pi.CurrentDirectory.StartsWith(d, StringComparison.Ordinal)) != -1) |
| | | 43 | | { |
| | | 44 | | result[(processId, pi.StartTime)] = ProcessInfoLinux.Create(pi); |
| | | 45 | | } |
| | | 46 | | } |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | return result; |
| | | 50 | | } |
| | | 51 | | |
| | | 52 | | private static IEnumerable<int> EnumerateProcessIds() |
| | | 53 | | { |
| | | 54 | | // This is an attempt to handle what was outlined in "https://github.com/dotnet/runtime/pull/100076". |
| | | 55 | | // Basically, when a process runs inside a root-less container, it can happen that the PID namespaces |
| | | 56 | | // of the process itself and /proc don't match up. In this case, we cannot reliably get information |
| | | 57 | | // about other processes. |
| | | 58 | | if (!ProcMatchesPidNamespace) |
| | | 59 | | { |
| | | 60 | | yield return Environment.ProcessId; |
| | | 61 | | } |
| | | 62 | | |
| | | 63 | | var options = new EnumerationOptions |
| | | 64 | | { |
| | | 65 | | IgnoreInaccessible = true, |
| | | 66 | | MatchCasing = MatchCasing.PlatformDefault, |
| | | 67 | | RecurseSubdirectories = false, |
| | | 68 | | ReturnSpecialDirectories = false |
| | | 69 | | }; |
| | | 70 | | |
| | | 71 | | foreach (string fullPath in Directory.EnumerateDirectories("/proc", "*", options)) |
| | | 72 | | { |
| | | 73 | | if (int.TryParse(Path.GetFileName(fullPath.AsSpan()), NumberStyles.Integer, CultureInfo.InvariantCulture, ou |
| | | 74 | | { |
| | | 75 | | yield return processId; |
| | | 76 | | } |
| | | 77 | | } |
| | | 78 | | } |
| | | 79 | | |
| | | 80 | | public static HashSet<ProcessInfo> GetLockingProcessInfos(string[] paths, [NotNullIfNotNull(nameof(directories))] re |
| | | 81 | | { |
| | | 82 | | if (paths == null) |
| | | 83 | | throw new ArgumentNullException(nameof(paths)); |
| | | 84 | | |
| | | 85 | | Dictionary<long, string>? inodesToPaths = null; |
| | | 86 | | var result = new HashSet<ProcessInfo>(); |
| | | 87 | | |
| | | 88 | | var xpaths = new HashSet<string>(paths.Length, StringComparer.Ordinal); |
| | | 89 | | |
| | | 90 | | foreach (string path in paths) |
| | | 91 | | { |
| | | 92 | | // Get directories, but don't exclude them from lookup via procfs (in contrast to Windows). |
| | | 93 | | // On Linux /proc/locks may also contain directory locks. |
| | | 94 | | if (Directory.Exists(path)) |
| | | 95 | | { |
| | | 96 | | directories?.Add(path); |
| | | 97 | | } |
| | | 98 | | |
| | | 99 | | xpaths.Add(path); |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | using (var reader = new StreamReader("/proc/locks")) |
| | | 103 | | { |
| | | 104 | | string? line; |
| | | 105 | | while ((line = reader.ReadLine()) != null) |
| | | 106 | | { |
| | | 107 | | if (inodesToPaths == null) |
| | | 108 | | { |
| | | 109 | | inodesToPaths = GetInodeToPaths(xpaths); |
| | | 110 | | } |
| | | 111 | | |
| | | 112 | | var lockInfo = LockInfo.ParseLine(line); |
| | | 113 | | if (inodesToPaths.ContainsKey(lockInfo.InodeInfo.INodeNumber)) |
| | | 114 | | { |
| | | 115 | | var processInfo = ProcessInfoLinux.Create(lockInfo); |
| | | 116 | | if (processInfo != null) |
| | | 117 | | { |
| | | 118 | | result.Add(processInfo); |
| | | 119 | | } |
| | | 120 | | } |
| | | 121 | | } |
| | | 122 | | } |
| | | 123 | | |
| | | 124 | | return result; |
| | | 125 | | } |
| | | 126 | | |
| | | 127 | | private static Dictionary<long, string> GetInodeToPaths(HashSet<string> paths) |
| | | 128 | | { |
| | | 129 | | var inodesToPaths = new Dictionary<long, string>(); |
| | | 130 | | |
| | | 131 | | foreach (string path in paths) |
| | | 132 | | { |
| | | 133 | | long inode = NativeMethods.GetInode(path); |
| | | 134 | | if (inode != -1) |
| | | 135 | | { |
| | | 136 | | inodesToPaths.Add(inode, path); |
| | | 137 | | } |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | return inodesToPaths; |
| | | 141 | | } |
| | | 142 | | |
| | | 143 | | // Idea for handling of proc/pid-namespace mismatch is largely copied from dotnet/runtime. |
| | | 144 | | |
| | | 145 | | internal static bool ProcMatchesPidNamespace |
| | | 146 | | { |
| | | 147 | | get |
| | | 148 | | { |
| | | 149 | | // s_procMatchesPidNamespace is set to: |
| | | 150 | | // - 0: when uninitialized, |
| | | 151 | | // - 1: '/proc' and the process pid namespace match, |
| | | 152 | | // - 2: when they don't match. |
| | | 153 | | if (s_procMatchesPidNamespace == 0) |
| | | 154 | | { |
| | | 155 | | // '/proc/self' is a symlink to the pid used by '/proc' for the current process. |
| | | 156 | | // We compare it with the pid of the current process to see if the '/proc' and pid namespace match up. |
| | | 157 | | |
| | | 158 | | int? procSelfPid = null; |
| | | 159 | | |
| | | 160 | | if (Directory.ResolveLinkTarget("/proc/self", false)?.FullName is string target && |
| | | 161 | | int.TryParse(Path.GetFileName(target), out int pid)) |
| | | 162 | | { |
| | | 163 | | procSelfPid = pid; |
| | | 164 | | } |
| | | 165 | | |
| | | 166 | | Debug.Assert(procSelfPid.HasValue); |
| | | 167 | | |
| | | 168 | | s_procMatchesPidNamespace = !procSelfPid.HasValue || procSelfPid == Environment.ProcessId ? 1 : 2; |
| | | 169 | | } |
| | | 170 | | return s_procMatchesPidNamespace == 1; |
| | | 171 | | } |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | internal enum ProcPid : int |
| | | 175 | | { |
| | | 176 | | Invalid = -1, |
| | | 177 | | Self = 0, // Current process: this will also work in root less containers, if accessed via /proc/self/... |
| | | 178 | | // Actual PIDs from /proc, cast as "ProcPid" |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | internal static bool TryGetProcPid(int pid, out ProcPid procPid) |
| | | 182 | | { |
| | | 183 | | if (pid == Environment.ProcessId) |
| | | 184 | | { |
| | | 185 | | // Use '/proc/self' for the current process. |
| | | 186 | | procPid = ProcPid.Self; |
| | | 187 | | return true; |
| | | 188 | | } |
| | | 189 | | |
| | | 190 | | if (ProcMatchesPidNamespace) |
| | | 191 | | { |
| | | 192 | | // Since namespaces match, we can handle any process. |
| | | 193 | | procPid = (ProcPid)pid; |
| | | 194 | | return true; |
| | | 195 | | } |
| | | 196 | | |
| | | 197 | | // Cannot handle arbitrary processes when namespaces do not match. |
| | | 198 | | procPid = ProcPid.Invalid; |
| | | 199 | | return false; |
| | | 200 | | } |
| | | 201 | | |
| | | 202 | | private static string GetProcCmdline(ProcPid procPid) => procPid == ProcPid.Self ? "/proc/self/cmdline" : string.Cre |
| | | 203 | | private static string GetProcExe(ProcPid procPid) => procPid == ProcPid.Self ? "/proc/self/exe" : string.Create(null |
| | | 204 | | private static string GetProcCwd(ProcPid procPid) => procPid == ProcPid.Self ? "/proc/self/cwd" : string.Create(null |
| | | 205 | | private static string GetProcStat(ProcPid procPid) => procPid == ProcPid.Self ? "/proc/self/stat" : string.Create(nu |
| | | 206 | | private static string GetProcDir(ProcPid procPid) => procPid == ProcPid.Self ? "/proc/self" : string.Create(null, st |
| | | 207 | | |
| | | 208 | | internal static bool Exists(int processId) => TryGetProcPid(processId, out var procPid) && Directory.Exists(GetProcD |
| | | 209 | | |
| | | 210 | | // TODO: As of now, we are reading the stat file for a process 3 times (sid, ppid and kthread). |
| | | 211 | | // We should really read the file only once. This would mean that the IsKernelThread(), GetParentProcessId() |
| | | 212 | | // and GetSessionId() methods need to be merged into a single one. |
| | | 213 | | |
| | | 214 | | internal struct Stat |
| | | 215 | | { |
| | 2 | 216 | | public int? ParentProcessId { get; set; } |
| | 2 | 217 | | public int SessionId { get; set; } |
| | 2 | 218 | | public bool? IsKernelThread { get; set; } |
| | | 219 | | } |
| | | 220 | | |
| | | 221 | | private enum StatFields |
| | | 222 | | { |
| | | 223 | | Ppid = 3, |
| | | 224 | | Sid = 5, |
| | | 225 | | Flags = 8, |
| | | 226 | | |
| | | 227 | | Last = Flags |
| | | 228 | | } |
| | | 229 | | |
| | | 230 | | internal static Stat GetStat(int processId) |
| | | 231 | | { |
| | | 232 | | var result = new Stat(); |
| | | 233 | | |
| | | 234 | | if (TryGetProcPid(processId, out var procPid)) |
| | | 235 | | { |
| | | 236 | | var stat = File.ReadAllText(GetProcStat(procPid)).AsSpan().Trim(); |
| | | 237 | | |
| | | 238 | | #if NET9_0_OR_GREATER |
| | | 239 | | int index = 0; |
| | | 240 | | foreach (var range in stat.Split(' ')) |
| | | 241 | | { |
| | | 242 | | switch ((StatFields)index) |
| | | 243 | | { |
| | | 244 | | case StatFields.Ppid: |
| | | 245 | | if (int.TryParse(stat[range], CultureInfo.InvariantCulture, out int ppid)) |
| | | 246 | | { |
| | | 247 | | result.ParentProcessId = ppid; |
| | | 248 | | } |
| | | 249 | | break; |
| | | 250 | | case StatFields.Sid: |
| | | 251 | | if (int.TryParse(stat[range], CultureInfo.InvariantCulture, out int sid)) |
| | | 252 | | { |
| | | 253 | | result.SessionId = sid; |
| | | 254 | | } |
| | | 255 | | break; |
| | | 256 | | case StatFields.Flags: |
| | | 257 | | if (int.TryParse(stat[range], CultureInfo.InvariantCulture, out int flags)) |
| | | 258 | | { |
| | | 259 | | const int PF_KTHREAD = 0x0020_0000; |
| | | 260 | | result.IsKernelThread = (flags & PF_KTHREAD) == PF_KTHREAD; |
| | | 261 | | } |
| | | 262 | | break; |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | index++; |
| | | 266 | | if (index > 8) |
| | | 267 | | { |
| | | 268 | | break; |
| | | 269 | | } |
| | | 270 | | } |
| | | 271 | | |
| | | 272 | | if (index < (int)StatFields.Last) |
| | | 273 | | { |
| | | 274 | | throw new IOException($"Expected at least {(int)StatFields.Last + 1} fields in /proc/{processId}/stat.") |
| | | 275 | | } |
| | | 276 | | #else |
| | | 277 | | int fieldCount = stat.Count(' ') + 1; |
| | | 278 | | if (fieldCount < (int)StatFields.Last + 1) |
| | | 279 | | { |
| | | 280 | | throw new IOException($"Expected at least {(int)StatFields.Last + 1} fields in /proc/{processId}/stat.") |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | // Need only as much ranges as we have fields. Rest of stat can be squished into a single, trailing range |
| | | 284 | | // which we'll never read. |
| | | 285 | | int rangeCount = (int)StatFields.Last + 2; |
| | | 286 | | Span<Range> ranges = rangeCount < 128 ? stackalloc Range[rangeCount] : new Range[rangeCount]; |
| | | 287 | | int num = MemoryExtensions.Split(stat, ranges, ' '); |
| | | 288 | | |
| | | 289 | | // Shouldn't trigger, because of pre-checks done above. |
| | | 290 | | Debug.Assert(num == rangeCount); |
| | | 291 | | |
| | | 292 | | if (int.TryParse(stat[ranges[(int)StatFields.Ppid]], CultureInfo.InvariantCulture, out int ppid)) |
| | | 293 | | { |
| | | 294 | | result.ParentProcessId = ppid; |
| | | 295 | | } |
| | | 296 | | |
| | | 297 | | if (int.TryParse(stat[ranges[(int)StatFields.Sid]], CultureInfo.InvariantCulture, out int sid)) |
| | | 298 | | { |
| | | 299 | | result.SessionId = sid; |
| | | 300 | | } |
| | | 301 | | |
| | | 302 | | if (int.TryParse(stat[ranges[(int)StatFields.Flags]], CultureInfo.InvariantCulture, out int flags)) |
| | | 303 | | { |
| | | 304 | | const int PF_KTHREAD = 0x0020_0000; |
| | | 305 | | result.IsKernelThread = (flags & PF_KTHREAD) == PF_KTHREAD; |
| | | 306 | | } |
| | | 307 | | #endif |
| | | 308 | | } |
| | | 309 | | |
| | | 310 | | return result; |
| | | 311 | | } |
| | | 312 | | |
| | | 313 | | //internal static bool? IsKernelThread(int processId) |
| | | 314 | | //{ |
| | | 315 | | // if (TryGetProcPid(processId, out var procPid)) |
| | | 316 | | // { |
| | | 317 | | // if (procPid == ProcPid.Self) |
| | | 318 | | // { |
| | | 319 | | // // We are for sure not a kernel thread. |
| | | 320 | | // return false; |
| | | 321 | | // } |
| | | 322 | | |
| | | 323 | | // var content = File.ReadAllText(GetProcStat(procPid)).AsSpan().Trim(); |
| | | 324 | | // if (int.TryParse(GetField(content, ' ', 8).Trim(), CultureInfo.InvariantCulture, out int flags)) |
| | | 325 | | // { |
| | | 326 | | // const int PF_KTHREAD = 0x0020_0000; |
| | | 327 | | // return (flags & PF_KTHREAD) == PF_KTHREAD; |
| | | 328 | | // } |
| | | 329 | | // } |
| | | 330 | | |
| | | 331 | | // return null; |
| | | 332 | | //} |
| | | 333 | | |
| | | 334 | | //internal static int? GetParentProcessId(int processId) |
| | | 335 | | //{ |
| | | 336 | | // if (TryGetProcPid(processId, out var procPid)) |
| | | 337 | | // { |
| | | 338 | | // var content = File.ReadAllText(GetProcStat(procPid)).AsSpan().Trim(); |
| | | 339 | | // if (int.TryParse(GetField(content, ' ', 3).Trim(), CultureInfo.InvariantCulture, out int parentProcessId)) |
| | | 340 | | // { |
| | | 341 | | // return parentProcessId; |
| | | 342 | | // } |
| | | 343 | | // } |
| | | 344 | | |
| | | 345 | | // return null; |
| | | 346 | | //} |
| | | 347 | | |
| | | 348 | | //internal static int GetProcessSessionId(int processId) |
| | | 349 | | //{ |
| | | 350 | | // int sessionId = -1; |
| | | 351 | | // if (TryGetProcPid(processId, out ProcPid procPid)) |
| | | 352 | | // { |
| | | 353 | | // var content = File.ReadAllText(GetProcStat(procPid)).AsSpan().Trim(); |
| | | 354 | | // if (int.TryParse(GetField(content, ' ', 5).Trim(), CultureInfo.InvariantCulture, out int sid)) |
| | | 355 | | // { |
| | | 356 | | // sessionId = sid; |
| | | 357 | | // } |
| | | 358 | | // } |
| | | 359 | | |
| | | 360 | | // return sessionId; |
| | | 361 | | //} |
| | | 362 | | |
| | | 363 | | internal static string? GetProcessOwner(int processId) |
| | | 364 | | { |
| | | 365 | | if (TryGetProcPid(processId, out var procPid)) |
| | | 366 | | { |
| | | 367 | | if (procPid == ProcPid.Self) |
| | | 368 | | { |
| | | 369 | | return Environment.UserName; |
| | | 370 | | } |
| | | 371 | | |
| | | 372 | | if (NativeMethods.TryGetUid(GetProcDir(procPid), out uint uid)) |
| | | 373 | | { |
| | | 374 | | return NativeMethods.GetUserName(uid); |
| | | 375 | | } |
| | | 376 | | } |
| | | 377 | | |
| | | 378 | | return null; |
| | | 379 | | } |
| | | 380 | | |
| | | 381 | | internal static DateTime GetProcessStartTime(int processId) |
| | | 382 | | { |
| | | 383 | | if (TryGetProcPid(processId, out ProcPid procPid)) |
| | | 384 | | { |
| | | 385 | | // Apparently it is currently impossible to fully recreate the time that Process.StartTime is. |
| | | 386 | | // Also see https://github.com/dotnet/runtime/issues/108959. |
| | | 387 | | |
| | | 388 | | if (procPid == ProcPid.Self) |
| | | 389 | | { |
| | | 390 | | using var process = Process.GetCurrentProcess(); |
| | | 391 | | return process.StartTime; |
| | | 392 | | } |
| | | 393 | | else |
| | | 394 | | { |
| | | 395 | | using var process = Process.GetProcessById(processId); |
| | | 396 | | return process.StartTime; |
| | | 397 | | } |
| | | 398 | | } |
| | | 399 | | |
| | | 400 | | return default; |
| | | 401 | | } |
| | | 402 | | |
| | | 403 | | internal static string? GetProcessCurrentDirectory(int processId) |
| | | 404 | | { |
| | | 405 | | if (TryGetProcPid(processId, out ProcPid procPid)) |
| | | 406 | | { |
| | | 407 | | return Directory.ResolveLinkTarget(GetProcCwd(procPid), true)?.FullName; |
| | | 408 | | } |
| | | 409 | | |
| | | 410 | | return null; |
| | | 411 | | } |
| | | 412 | | |
| | | 413 | | internal static string[]? GetProcessCommandLineArgs(int processId, int maxArgs = -1) |
| | | 414 | | { |
| | | 415 | | if (TryGetProcPid(processId, out ProcPid procPid)) |
| | | 416 | | { |
| | | 417 | | byte[]? rentedBuffer = null; |
| | | 418 | | try |
| | | 419 | | { |
| | | 420 | | using (var file = new FileStream(GetProcCmdline(procPid), FileMode.Open, FileAccess.Read, FileShare.Read |
| | | 421 | | { |
| | | 422 | | Span<byte> buffer = stackalloc byte[256]; |
| | | 423 | | int bytesRead = 0; |
| | | 424 | | while (true) |
| | | 425 | | { |
| | | 426 | | if (bytesRead == buffer.Length) |
| | | 427 | | { |
| | | 428 | | // Resize buffer |
| | | 429 | | uint newLength = (uint)buffer.Length * 2; |
| | | 430 | | // Store what was read into new buffer |
| | | 431 | | byte[] tmp = ArrayPool<byte>.Shared.Rent((int)newLength); |
| | | 432 | | buffer.CopyTo(tmp); |
| | | 433 | | // Remember current "rented" buffer (might be null) |
| | | 434 | | byte[]? lastRentedBuffer = rentedBuffer; |
| | | 435 | | // From now on, we did rent a buffer. And it will be used for further reads. |
| | | 436 | | buffer = tmp; |
| | | 437 | | rentedBuffer = tmp; |
| | | 438 | | // Return previously rented buffer, if any. |
| | | 439 | | if (lastRentedBuffer != null) |
| | | 440 | | { |
| | | 441 | | ArrayPool<byte>.Shared.Return(lastRentedBuffer); |
| | | 442 | | } |
| | | 443 | | } |
| | | 444 | | |
| | | 445 | | Debug.Assert(bytesRead < buffer.Length); |
| | | 446 | | int n = file.Read(buffer.Slice(bytesRead)); |
| | | 447 | | bytesRead += n; |
| | | 448 | | if (n == 0) |
| | | 449 | | { |
| | | 450 | | break; |
| | | 451 | | } |
| | | 452 | | } |
| | | 453 | | |
| | | 454 | | return ConvertToArgs(ref buffer, maxArgs); |
| | | 455 | | } |
| | | 456 | | } |
| | | 457 | | catch (IOException) |
| | | 458 | | { |
| | | 459 | | } |
| | | 460 | | finally |
| | | 461 | | { |
| | | 462 | | if (rentedBuffer != null) |
| | | 463 | | { |
| | | 464 | | ArrayPool<byte>.Shared.Return(rentedBuffer); |
| | | 465 | | } |
| | | 466 | | } |
| | | 467 | | } |
| | | 468 | | |
| | | 469 | | return null; |
| | | 470 | | } |
| | | 471 | | |
| | | 472 | | internal static string[] ConvertToArgs(ref Span<byte> buffer, int maxArgs = -1) |
| | | 473 | | { |
| | | 474 | | if (buffer.IsEmpty || maxArgs == 0) |
| | | 475 | | { |
| | | 476 | | return []; |
| | | 477 | | } |
| | | 478 | | |
| | | 479 | | // Removing ending '\0\0' from buffer. That is how /proc/<pid>/cmdline is documented to end. |
| | | 480 | | // We need to strip those to not get a phony, empty, trailing argv[argc-1] element. |
| | | 481 | | if (buffer[^1] == '\0' && buffer[^2] == '\0') |
| | | 482 | | { |
| | | 483 | | buffer = buffer.Slice(0, buffer.Length - 2); |
| | | 484 | | } |
| | | 485 | | |
| | | 486 | | if (buffer.IsEmpty) |
| | | 487 | | { |
| | | 488 | | return []; |
| | | 489 | | } |
| | | 490 | | |
| | | 491 | | // Individual argv elements in the buffer are separated by a null byte. |
| | | 492 | | int actual = buffer.Count((byte)'\0') + 1; |
| | | 493 | | int count = maxArgs > 0 ? Math.Min(maxArgs, actual) : actual; |
| | | 494 | | string[] args = new string[count]; |
| | | 495 | | int start = 0; |
| | | 496 | | int p = 0; |
| | | 497 | | for (int i = 0; i < buffer.Length; i++) |
| | | 498 | | { |
| | | 499 | | if (buffer[i] == '\0') |
| | | 500 | | { |
| | | 501 | | args[p++] = Encoding.UTF8.GetString(buffer.Slice(start, i - start)); |
| | | 502 | | start = i + 1; |
| | | 503 | | |
| | | 504 | | if (maxArgs > 0 && maxArgs == p) |
| | | 505 | | { |
| | | 506 | | return args; |
| | | 507 | | } |
| | | 508 | | } |
| | | 509 | | } |
| | | 510 | | |
| | | 511 | | if (start < buffer.Length) |
| | | 512 | | { |
| | | 513 | | args[p++] = Encoding.UTF8.GetString(buffer.Slice(start)); |
| | | 514 | | } |
| | | 515 | | |
| | | 516 | | return args; |
| | | 517 | | } |
| | | 518 | | |
| | | 519 | | internal static string? GetProcessExecutablePath(int processId) |
| | | 520 | | { |
| | | 521 | | if (TryGetProcPid(processId, out ProcPid procPid)) |
| | | 522 | | { |
| | | 523 | | return File.ResolveLinkTarget(GetProcExe(procPid), true)?.FullName; |
| | | 524 | | } |
| | | 525 | | |
| | | 526 | | return null; |
| | | 527 | | } |
| | | 528 | | |
| | | 529 | | internal static string? GetProcessExecutablePathFromCmdLine(int processId) |
| | | 530 | | { |
| | | 531 | | // This is a little more expensive than a specific function only reading up to argv[0] from /proc/<pid>/cmdline |
| | | 532 | | // would be - GetProcessCommandLineArgs() reads all arguments, but then only converts "maxArgs" of them to an |
| | | 533 | | // actual System.String. On the other hand it saves quite some code duplication. |
| | | 534 | | string[]? args = GetProcessCommandLineArgs(processId, maxArgs: 1); |
| | | 535 | | return args?.Length > 0 ? args[0] : null; |
| | | 536 | | } |
| | | 537 | | |
| | | 538 | | internal static ReadOnlySpan<char> GetField(ReadOnlySpan<char> content, char delimiter, int index) |
| | | 539 | | { |
| | | 540 | | if (index < 0) |
| | | 541 | | { |
| | | 542 | | throw new ArgumentOutOfRangeException(nameof(index), index, $"Field index cannot be negative."); |
| | | 543 | | } |
| | | 544 | | |
| | | 545 | | #if NET9_0_OR_GREATER |
| | | 546 | | // PERF NOTE: For larger index values this will perform actually worse than the manual usage of |
| | | 547 | | // Count()/MemoryExtensions.Split() below. However, currently we use rather small indexes (5 out of 52) |
| | | 548 | | // where this performs actually better. |
| | | 549 | | // Also, this is cleaner an less error prone. |
| | | 550 | | // In .NET 10+ the ref struct enumerator returned here will implement IEnumerable<> so that we could |
| | | 551 | | // try using LINQ here, to make things even more simple (and possibly performant, as LINQ is getting |
| | | 552 | | // improved also!) |
| | | 553 | | |
| | | 554 | | int count = 0; |
| | | 555 | | foreach (var range in content.Split(delimiter)) |
| | | 556 | | { |
| | | 557 | | if (count < index) |
| | | 558 | | { |
| | | 559 | | count++; |
| | | 560 | | continue; |
| | | 561 | | } |
| | | 562 | | return content[range]; |
| | | 563 | | } |
| | | 564 | | |
| | | 565 | | throw new ArgumentOutOfRangeException(nameof(index), index, $"Cannot access field at index {index}, only {count} |
| | | 566 | | #else |
| | | 567 | | int fieldCount = content.Count(delimiter) + 1; |
| | | 568 | | if (fieldCount <= index) |
| | | 569 | | { |
| | | 570 | | throw new ArgumentOutOfRangeException(nameof(index), index, $"Cannot access field at index {index}, only {fi |
| | | 571 | | } |
| | | 572 | | |
| | | 573 | | // We need to split into N+1 fields, where N is the field denoted by the index. |
| | | 574 | | // The extra field will receive the remainder of content, that doesn't need to |
| | | 575 | | // be split further, because we're not interested. That also means, that if we |
| | | 576 | | // are supposed to read the last field of content, we don't need that extra field. |
| | | 577 | | int rangeCount = index == fieldCount - 1 ? index + 1 : index + 2; |
| | | 578 | | Span<Range> ranges = rangeCount < 128 ? stackalloc Range[rangeCount] : new Range[rangeCount]; |
| | | 579 | | int num = MemoryExtensions.Split(content, ranges, delimiter); |
| | | 580 | | |
| | | 581 | | // Shouldn't trigger, because of pre-checks done above. |
| | | 582 | | Debug.Assert(num == rangeCount); |
| | | 583 | | |
| | | 584 | | return content[ranges[index]]; |
| | | 585 | | #endif |
| | | 586 | | } |
| | | 587 | | } |