import Foundation import Darwin nonisolated struct ProcessMonitor: Sendable { private var previous: [ProcessIdentity: (UInt64, TimeInterval)] = [:] private var sampleSerial: UInt64 = 0 private var paths: [ProcessIdentity: (name: String, path: String?, expires: TimeInterval)] = [:] static func cpu(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? { guard let previous, current >= previous, elapsed.isFinite, elapsed > 0 else { return nil } return Double(current - previous) / 1_000_000_000 / elapsed } mutating func sample() -> ProcessSnapshot { sampleSerial &+= 1 let date = Date() guard let entries = Self.entries() else { previous = [:] paths = [:] return ProcessSnapshot(date: date, enumerated: 0, readable: 0, rows: [], failed: true) } let now = ProcessInfo.processInfo.systemUptime var next: [ProcessIdentity: (UInt64, TimeInterval)] = [:] var rows: [ProcessMetrics] = [] var pathBuffer = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN)) for entry in entries where entry.kp_proc.p_pid > 0 { let pid = entry.kp_proc.p_pid var info = proc_taskallinfo() let valid = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &info, Int32(MemoryLayout.size(ofValue: info))) == MemoryLayout.size(ofValue: info) if valid && (info.pbsd.pbi_start_tvsec != UInt64(max(0, entry.kp_proc.p_starttime.tv_sec)) || info.pbsd.pbi_start_tvusec != UInt64(max(0, entry.kp_proc.p_starttime.tv_usec))) { continue } // kinfo_proc carries a start time even when task details are restricted. let seconds = valid ? info.pbsd.pbi_start_tvsec : UInt64(max(0, entry.kp_proc.p_starttime.tv_sec)) let micros = valid ? info.pbsd.pbi_start_tvusec : UInt64(max(0, entry.kp_proc.p_starttime.tv_usec)) let id = ProcessIdentity(pid: pid, seconds: seconds, microseconds: seconds == 0 ? sampleSerial : micros) var copy = entry.kp_proc.p_comm let name = withUnsafeBytes(of: ©) { raw in String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self) } let path: String? if let cached = paths[id], seconds > 0, cached.name == name, now < cached.expires { path = cached.path } else { let size = proc_pidpath(pid, &pathBuffer, UInt32(pathBuffer.count)) path = size > 0 ? String(cString: pathBuffer) : nil paths[id] = (name, path, now + 30) } var usage: Double? if valid && seconds > 0 { let (total, overflow) = info.ptinfo.pti_total_user.addingReportingOverflow(info.ptinfo.pti_total_system) if !overflow { usage = Self.cpu(current: total, previous: previous[id]?.0, elapsed: now - (previous[id]?.1 ?? now)) next[id] = (total, now) } } rows.append(ProcessMetrics(id: id, name: name, path: path, cpu: usage, residentBytes: valid ? info.ptinfo.pti_resident_size : nil, threads: valid ? Int(info.ptinfo.pti_threadnum) : nil, restricted: !valid)) } // Recheck the enumeration identity after path reads; never attach a reused PID's path. if let latest = Self.entries() { let identities = Set(latest.map { ProcessIdentity(pid: $0.kp_proc.p_pid, seconds: UInt64(max(0, $0.kp_proc.p_starttime.tv_sec)), microseconds: UInt64(max(0, $0.kp_proc.p_starttime.tv_usec))) }) rows.removeAll { $0.id.seconds > 0 && !identities.contains($0.id) } } else { paths = [:] rows = rows.map { ProcessMetrics(id: $0.id, name: $0.name, path: nil, cpu: $0.cpu, residentBytes: $0.residentBytes, threads: $0.threads, restricted: $0.restricted) } } let retained = Set(rows.map(\.id)) previous = next.filter { retained.contains($0.key) } paths = paths.filter { retained.contains($0.key) && $0.key.seconds > 0 } return ProcessSnapshot(date: date, enumerated: entries.filter { $0.kp_proc.p_pid > 0 }.count, readable: rows.filter { !$0.restricted }.count, rows: rows, failed: false) } private static func entries() -> [kinfo_proc]? { var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0] for _ in 0..<3 { var bytes = 0 guard sysctl(&mib, u_int(mib.count), nil, &bytes, nil, 0) == 0 else { return nil } var entries = [kinfo_proc](repeating: kinfo_proc(), count: bytes / MemoryLayout.stride + 256) bytes = entries.count * MemoryLayout.stride let status = entries.withUnsafeMutableBytes { sysctl(&mib, u_int(mib.count), $0.baseAddress, &bytes, nil, 0) } if status == 0 { return Array(entries.prefix(bytes / MemoryLayout.stride)) } if errno != ENOMEM { return nil } } return nil } }