Skip to content

Commit

Permalink
SunOS process and thread support
Browse files Browse the repository at this point in the history
Read binary psinfo for System.Diagnostic.Process on SunOS

Thanks for initial prototype help from:
Austin Wise <AustinWise@gmail.com>

Add Try prefix to SunOS Interop functions
Get rid of unsafe for procfs get methods
  • Loading branch information
gwr committed Aug 22, 2024
1 parent 06ae1be commit 6229847
Show file tree
Hide file tree
Showing 17 changed files with 846 additions and 93 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.InteropServices;

// C# equivalents for <sys/procfs.h> structures. See: struct lwpsinfo, struct psinfo.
// We read directly onto these from procfs, so the layouts and sizes of these structures
// must _exactly_ match those in <sys/procfs.h>

// analyzer incorrectly flags fixed buffer length const
// (https://github.com/dotnet/roslyn/issues/37593)
#pragma warning disable CA1823

internal static partial class Interop
{
internal static partial class @procfs
{
internal const string RootPath = "/proc/";
private const string psinfoFileName = "/psinfo";
private const string lwpDirName = "/lwp";
private const string lwpsinfoFileName = "/lwpsinfo";

// Constants from sys/procfs.h
private const int PRARGSZ = 80;
private const int PRCLSZ = 8;
private const int PRFNSZ = 16;

[StructLayout(LayoutKind.Sequential)]
internal struct @timestruc_t
{
public long tv_sec;
public long tv_nsec;
}

// lwp ps(1) information file. /proc/<pid>/lwp/<lwpid>/lwpsinfo
// Equivalent to sys/procfs.h struct lwpsinfo
// "unsafe" because it has fixed sized arrays.
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct @lwpsinfo
{
private int pr_flag; /* lwp flags (DEPRECATED; do not use) */
public uint pr_lwpid; /* lwp id */
private long pr_addr; /* internal address of lwp */
private long pr_wchan; /* wait addr for sleeping lwp */
public byte pr_stype; /* synchronization event type */
public byte pr_state; /* numeric lwp state */
public byte pr_sname; /* printable character for pr_state */
public byte pr_nice; /* nice for cpu usage */
private short pr_syscall; /* system call number (if in syscall) */
private byte pr_oldpri; /* pre-SVR4, low value is high priority */
private byte pr_cpu; /* pre-SVR4, cpu usage for scheduling */
public int pr_pri; /* priority, high value is high priority */
private ushort pr_pctcpu; /* fixed pt. % of recent cpu time */
private ushort pr_pad;
public timestruc_t pr_start; /* lwp start time, from the epoch */
public timestruc_t pr_time; /* usr+sys cpu time for this lwp */
private fixed byte pr_clname[PRCLSZ]; /* scheduling class name */
private fixed byte pr_name[PRFNSZ]; /* name of system lwp */
private int pr_onpro; /* processor which last ran this lwp */
private int pr_bindpro; /* processor to which lwp is bound */
private int pr_bindpset; /* processor set to which lwp is bound */
private int pr_lgrp; /* lwp home lgroup */
private fixed int pr_filler[4]; /* reserved for future use */
}
private const int PR_LWPSINFO_SIZE = 128; // for debug assertions

// process ps(1) information file. /proc/<pid>/psinfo
// Equivalent to sys/procfs.h struct psinfo
// "unsafe" because it has fixed sized arrays.
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct @psinfo
{
private int pr_flag; /* process flags (DEPRECATED; do not use) */
public int pr_nlwp; /* number of active lwps in the process */
public int pr_pid; /* unique process id */
public int pr_ppid; /* process id of parent */
public int pr_pgid; /* pid of process group leader */
public int pr_sid; /* session id */
public uint pr_uid; /* real user id */
public uint pr_euid; /* effective user id */
public uint pr_gid; /* real group id */
public uint pr_egid; /* effective group id */
private long pr_addr; /* address of process */
public ulong pr_size; /* size of process image in Kbytes */
public ulong pr_rssize; /* resident set size in Kbytes */
private ulong pr_pad1;
private ulong pr_ttydev; /* controlling tty device (or PRNODEV) */
private ushort pr_pctcpu; /* % of recent cpu time used by all lwps */
private ushort pr_pctmem; /* % of system memory used by process */
public timestruc_t pr_start; /* process start time, from the epoch */
public timestruc_t pr_time; /* usr+sys cpu time for this process */
public timestruc_t pr_ctime; /* usr+sys cpu time for reaped children */
public fixed byte pr_fname[PRFNSZ]; /* name of execed file */
public fixed byte pr_psargs[PRARGSZ]; /* initial characters of arg list */
public int pr_wstat; /* if zombie, the wait() status */
public int pr_argc; /* initial argument count */
private long pr_argv; /* address of initial argument vector */
private long pr_envp; /* address of initial environment vector */
private byte pr_dmodel; /* data model of the process */
private fixed byte pr_pad2[3];
public int pr_taskid; /* task id */
public int pr_projid; /* project id */
public int pr_nzomb; /* number of zombie lwps in the process */
public int pr_poolid; /* pool id */
public int pr_zoneid; /* zone id */
public int pr_contract; /* process contract */
private fixed int pr_filler[1]; /* reserved for future use */
public lwpsinfo pr_lwp; /* information for representative lwp */
// C# magic: Accessor method to get a Span for pr_psargs[]
// Does not affect the size or layout of this struct.
internal ReadOnlySpan<byte> PsArgsSpan =>
MemoryMarshal.CreateReadOnlySpan(ref pr_psargs[0], PRARGSZ);
}
private const int PR_PSINFO_SIZE = 416; // for debug assertions

// Ouput type for TryGetThreadInfoById()
internal struct ThreadInfo
{
internal uint Tid;
internal int Priority;
internal int NiceVal;
internal char Status;
internal Interop.Sys.TimeSpec StartTime;
internal Interop.Sys.TimeSpec CpuTotalTime; // user+sys
// add more fields when needed.
}

// Ouput type for TryGetProcessInfoById()
internal struct ProcessInfo
{
internal int Pid;
internal int ParentPid;
internal int SessionId;
internal int Priority;
internal int NiceVal;
internal nuint VirtualSize;
internal nuint ResidentSetSize;
internal Interop.Sys.TimeSpec StartTime;
internal Interop.Sys.TimeSpec CpuTotalTime; // user+sys
internal string? Args;
// add more fields when needed.
}

internal static string GetInfoFilePathForProcess(int pid) =>
$"{RootPath}{(uint)pid}{psinfoFileName}";

internal static string GetLwpDirForProcess(int pid) =>
$"{RootPath}{(uint)pid}{lwpDirName}";

internal static string GetInfoFilePathForThread(int pid, int tid) =>
$"{RootPath}{(uint)pid}{lwpDirName}/{(uint)tid}{lwpsinfoFileName}";

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;

internal static partial class Interop
{
internal static partial class @procfs
{

/// <summary>
/// Attempts to get status info for the specified process ID.
/// </summary>
/// <param name="pid">PID of the process to read status info for.</param>
/// <param name="result">The pointer to ProcessInfo instance.</param>
/// <returns>
/// true if the process info was read; otherwise, false.
/// </returns>

// ProcessManager.SunOS.cs calls this
internal static bool TryGetProcessInfoById(int pid, out ProcessInfo result)
{
result = default;

try
{
string fileName = GetInfoFilePathForProcess(pid);
using FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
psinfo pr;
Unsafe.SkipInit(out pr);
Span<byte> prspan = MemoryMarshal.AsBytes(new Span<psinfo>(ref pr));
Debug.Assert(prspan.Length == PR_PSINFO_SIZE,
$"psinfo struct size {prspan.Length} bytes not {PR_PSINFO_SIZE}.");
fs.ReadExactly(prspan);

result.Pid = pr.pr_pid;
result.ParentPid = pr.pr_ppid;
result.SessionId = pr.pr_sid;
result.VirtualSize = (nuint)pr.pr_size * 1024; // pr_size is in Kbytes
result.ResidentSetSize = (nuint)pr.pr_rssize * 1024; // pr_rssize is in Kbytes
result.StartTime.TvSec = pr.pr_start.tv_sec;
result.StartTime.TvNsec = pr.pr_start.tv_nsec;
result.CpuTotalTime.TvSec = pr.pr_time.tv_sec;
result.CpuTotalTime.TvNsec = pr.pr_time.tv_nsec;

// Get Args as a managed string, using accessor for pr_psargs[]
ReadOnlySpan<byte> argspan = pr.PsArgsSpan;
int argslen = argspan.IndexOf((byte)0);
argslen = (argslen >= 0) ? argslen : argspan.Length;
result.Args = Encoding.UTF8.GetString(argspan.Slice(0, argslen));

// A couple things from pr_lwp
result.Priority = pr.pr_lwp.pr_pri;
result.NiceVal = (int)pr.pr_lwp.pr_nice;

return true;
}
catch (Exception e)
{
Debug.Fail($"Failed to read process info for PID {pid}: {e}");
}

return false;
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.IO;

internal static partial class Interop
{
internal static partial class @procfs
{

/// <summary>
/// Attempts to get status info for the specified thread ID.
/// </summary>
/// <param name="pid">PID of the process to read status info for.</param>
/// <param name="tid">TID of the thread to read status info for.</param>
/// <param name="result">The pointer to ThreadInfo instance.</param>
/// <returns>
/// true if the thread info was read; otherwise, false.
/// </returns>

// ProcessManager.SunOS.cs calls this
internal static bool TryGetThreadInfoById(int pid, int tid, out ThreadInfo result)
{
result = default;

try
{
string fileName = GetInfoFilePathForThread(pid, tid);
using FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
lwpsinfo pr;
Unsafe.SkipInit(out pr);
Span<byte> prspan = MemoryMarshal.AsBytes(new Span<lwpsinfo>(ref pr));
Debug.Assert(prspan.Length == PR_LWPSINFO_SIZE,
$"psinfo struct size {prspan.Length} bytes not {PR_LWPSINFO_SIZE}.");
fs.ReadExactly(prspan);

result.Tid = pr.pr_lwpid;
result.Priority = pr.pr_pri;
result.NiceVal = (int)pr.pr_nice;
result.Status = (char)pr.pr_sname;
result.StartTime.TvSec = pr.pr_start.tv_sec;
result.StartTime.TvNsec = pr.pr_start.tv_nsec;
result.CpuTotalTime.TvSec = pr.pr_time.tv_sec;
result.CpuTotalTime.TvNsec = pr.pr_time.tv_nsec;

return true;
}
catch (Exception e)
{
Debug.Fail($"Failed to read thread info for PID {pid} TID {tid}: {e}");
}

return false;
}

}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
internal static partial class Sys
{
internal struct TimeSpec
{
internal long TvSec;
internal long TvNsec;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,6 @@ internal static partial class Interop
{
internal static partial class Sys
{
internal struct TimeSpec
{
internal long TvSec;
internal long TvNsec;
}

/// <summary>
/// Sets the last access and last modified time of a file
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public static partial class PlatformDetection
public static bool IsNotMacCatalyst => !IsMacCatalyst;
public static bool Isillumos => RuntimeInformation.IsOSPlatform(OSPlatform.Create("ILLUMOS"));
public static bool IsSolaris => RuntimeInformation.IsOSPlatform(OSPlatform.Create("SOLARIS"));
public static bool IsSunOS => Isillumos || IsSolaris;
public static bool IsBrowser => RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER"));
public static bool IsWasi => RuntimeInformation.IsOSPlatform(OSPlatform.Create("WASI"));
public static bool IsNotBrowser => !IsBrowser;
Expand Down
Loading

0 comments on commit 6229847

Please sign in to comment.