namespace ThreadPilot.Services { using System; using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using ThreadPilot.Models; using ThreadPilot.Platforms.Windows; public class ProcessService : IProcessService { private static string LegacyProfilesDirectory => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Profiles"); private readonly ConcurrentDictionary cpuSamples = new(); private readonly ConcurrentDictionary cpuSetHandlers = new(); private readonly ConcurrentDictionary processMetadata = new(); private readonly ILogger? logger; private readonly ISecurityService? securityService; private readonly IForegroundProcessService? foregroundProcessService; private readonly IProcessClassifier processClassifier; private readonly IPassiveProcessErrorThrottle passiveProcessErrorThrottle; private readonly Func profilesDirectoryProvider; private readonly CpuSelectionAffinityApplier cpuSelectionAffinityApplier; private readonly ICpuTopologyProvider? cpuTopologyProvider; private readonly CpuSelectionMigrationService cpuSelectionMigrationService; private readonly Func? loadProcessProfilePrioritySetter; private readonly Func>? loadProcessProfileCpuSelectionSetter; private readonly Func? loadProcessProfileLegacyAffinitySetter; private string ProfilesDirectory => this.profilesDirectoryProvider(); private bool useCpuSets = true; // Enable CPU Sets by default // Tracking for cleanup on exit private readonly ConcurrentDictionary appliedMasks = new(); // ProcessId -> MaskId private readonly ConcurrentDictionary originalPriorities = new(); // ProcessId -> OriginalPriority public ProcessService( ILogger? logger = null, ISecurityService? securityService = null, Func? profilesDirectoryProvider = null, IForegroundProcessService? foregroundProcessService = null, IProcessClassifier? processClassifier = null, IPassiveProcessErrorThrottle? passiveProcessErrorThrottle = null, ICpuTopologyProvider? cpuTopologyProvider = null, CpuSelectionMigrationService? cpuSelectionMigrationService = null) : this( logger, securityService, profilesDirectoryProvider, foregroundProcessService, processClassifier, passiveProcessErrorThrottle, cpuTopologyProvider, cpuSelectionMigrationService, loadProcessProfilePrioritySetter: null, loadProcessProfileCpuSelectionSetter: null, loadProcessProfileLegacyAffinitySetter: null) { } internal ProcessService( ILogger? logger, ISecurityService? securityService, Func? profilesDirectoryProvider, IForegroundProcessService? foregroundProcessService, IProcessClassifier? processClassifier, IPassiveProcessErrorThrottle? passiveProcessErrorThrottle, ICpuTopologyProvider? cpuTopologyProvider, CpuSelectionMigrationService? cpuSelectionMigrationService, Func? loadProcessProfilePrioritySetter, Func>? loadProcessProfileCpuSelectionSetter, Func? loadProcessProfileLegacyAffinitySetter) { this.logger = logger; this.securityService = securityService; this.foregroundProcessService = foregroundProcessService; this.processClassifier = processClassifier ?? new ProcessClassifier(new ProcessFilterService()); this.passiveProcessErrorThrottle = passiveProcessErrorThrottle ?? new PassiveProcessErrorThrottle(); this.profilesDirectoryProvider = profilesDirectoryProvider ?? (() => StoragePaths.ProfilesDirectory); this.cpuTopologyProvider = cpuTopologyProvider; this.cpuSelectionMigrationService = cpuSelectionMigrationService ?? new CpuSelectionMigrationService(); this.loadProcessProfilePrioritySetter = loadProcessProfilePrioritySetter; this.loadProcessProfileCpuSelectionSetter = loadProcessProfileCpuSelectionSetter; this.loadProcessProfileLegacyAffinitySetter = loadProcessProfileLegacyAffinitySetter; this.cpuSelectionAffinityApplier = new CpuSelectionAffinityApplier( this.GetOrCreateCpuSetHandler, this.ApplyLegacyProcessorAffinityDirectAsync, logger ?? (ILogger)Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, process => this.cpuSetHandlers.TryRemove(process.ProcessId, out _), (process, success) => this.AuditProcessOperation("SetProcessAffinity", process.Name, success)); StoragePaths.EnsureAppDataDirectories(); this.MigrateLegacyProfilesIfNeeded(); if (!Directory.Exists(this.ProfilesDirectory)) { Directory.CreateDirectory(this.ProfilesDirectory); } this.logger?.LogInformation("ProcessService initialized with CPU Sets support enabled"); } public async Task> GetProcessesAsync() { return await Task.Run(() => new ObservableCollection(this.EnumerateProcessModels())).ConfigureAwait(false); } private List EnumerateProcessModels(Func? filter = null, Func? nameFilter = null) { var foregroundProcessId = this.foregroundProcessService?.TryGetForegroundProcessId(); var models = new List(); foreach (var process in Process.GetProcesses()) { using (process) { // The name is already in the snapshot GetProcesses took, so skipping here costs no query. if (nameFilter != null && !nameFilter(process.ProcessName)) { continue; } var model = this.TryCreateProcessModel(process, foregroundProcessId); if (model != null && (filter == null || filter(model))) { models.Add(model); } } } return models.OrderBy(process => process.Name).ToList(); } private sealed record ProcessMetadata(DateTime StartTimeUtc, string ExecutablePath); private sealed class CpuSample { public CpuSample(TimeSpan totalProcessorTime, DateTime timestamp) { this.TotalProcessorTime = totalProcessorTime; this.Timestamp = timestamp; } public TimeSpan TotalProcessorTime { get; set; } public DateTime Timestamp { get; set; } } private double CalculateCpuUsage(Process process) { try { var now = DateTime.UtcNow; var totalProcessorTime = process.TotalProcessorTime; if (this.cpuSamples.TryGetValue(process.Id, out var previous)) { var cpuDeltaMs = (totalProcessorTime - previous.TotalProcessorTime).TotalMilliseconds; var timeDeltaMs = (now - previous.Timestamp).TotalMilliseconds; // Ignore extremely small deltas to avoid noisy values if (timeDeltaMs <= 0 || cpuDeltaMs < 0) { this.cpuSamples[process.Id] = new CpuSample(totalProcessorTime, now); return 0; } var usage = (cpuDeltaMs / (timeDeltaMs * Environment.ProcessorCount)) * 100.0; usage = Math.Clamp(usage, 0, 100); this.cpuSamples[process.Id] = new CpuSample(totalProcessorTime, now); return usage; } this.cpuSamples[process.Id] = new CpuSample(totalProcessorTime, now); return 0; // First sample cannot produce a rate } catch { return 0; } } public ProcessModel CreateProcessModel(Process process) { return this.CreateProcessModel(process, this.foregroundProcessService?.TryGetForegroundProcessId()); } private ProcessModel? TryCreateProcessModel(Process process, int? foregroundProcessId) { try { return this.CreateProcessModel(process, foregroundProcessId); } catch (Exception ex) when (IsTerminatedProcessException(ex)) { var processId = TryGetProcessId(process); if (processId.HasValue) { this.CleanupProcessResources(processId.Value); this.LogPassiveProcessReadFailure(processId.Value, PassiveProcessErrorKind.Terminated, ex); } return CreateMinimalProcessModel(process, processId, ProcessClassification.Terminated); } catch (Exception ex) when (IsPassiveProcessAccessException(ex)) { var processId = TryGetProcessId(process); if (processId.HasValue) { this.LogPassiveProcessReadFailure(processId.Value, PassiveProcessErrorKind.AccessDenied, ex); } return CreateMinimalProcessModel(process, processId, ProcessClassification.ProtectedOrAccessDenied); } catch (Exception ex) { var processId = TryGetProcessId(process); if (processId.HasValue) { this.LogPassiveProcessReadFailure(processId.Value, PassiveProcessErrorKind.Unknown, ex); } return CreateMinimalProcessModel(process, processId, ProcessClassification.Unknown); } } private ProcessModel CreateProcessModel(Process process, int? foregroundProcessId) { var model = new ProcessModel(); var accessDenied = false; var terminated = false; try { model.ProcessId = process.Id; } catch { model.Classification = ProcessClassification.Unknown; return model; } try { model.Name = process.ProcessName; } catch (Exception ex) when (IsAccessDeniedException(ex)) { accessDenied = true; model.Name = $"PID_{model.ProcessId}"; this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex); } catch (Exception ex) when (IsTerminatedProcessException(ex)) { terminated = true; model.Name = $"PID_{model.ProcessId}"; } if (!terminated) { try { if (process.HasExited) { terminated = true; } } catch (Exception ex) when (IsTerminatedProcessException(ex)) { terminated = true; } catch (Exception ex) when (IsAccessDeniedException(ex)) { accessDenied = true; this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex); } } DateTime? startTimeUtc = null; if (!terminated) { try { startTimeUtc = process.StartTime.ToUniversalTime(); } catch (Exception ex) when (IsPassiveProcessAccessException(ex) || IsTerminatedProcessException(ex)) { // Start time is used only to validate static metadata against PID reuse. } try { model.MemoryUsage = process.PrivateMemorySize64; } catch (Exception ex) when (IsAccessDeniedException(ex)) { accessDenied = true; this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex); } catch (Exception ex) when (IsTerminatedProcessException(ex)) { terminated = true; } if (!terminated) { try { model.Priority = process.PriorityClass; } catch (Exception ex) when (IsAccessDeniedException(ex)) { accessDenied = true; model.MainWindowHandle = IntPtr.Zero; model.MainWindowTitle = string.Empty; model.HasVisibleWindow = false; this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex); } catch (Exception ex) when (IsPassiveProcessAccessException(ex)) { accessDenied = true; model.MainWindowHandle = IntPtr.Zero; model.MainWindowTitle = string.Empty; model.HasVisibleWindow = false; this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex); } catch (Exception ex) when (IsTerminatedProcessException(ex)) { terminated = true; } } if (!terminated) { try { model.ProcessorAffinity = (long)process.ProcessorAffinity; } catch (Exception ex) when (IsAccessDeniedException(ex)) { accessDenied = true; this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex); } catch (Exception ex) when (IsTerminatedProcessException(ex)) { terminated = true; } } if (!terminated) { model.CpuUsage = this.CalculateCpuUsage(process); } if (!terminated) { try { model.MainWindowHandle = process.MainWindowHandle; model.MainWindowTitle = process.MainWindowTitle ?? string.Empty; model.HasVisibleWindow = model.MainWindowHandle != IntPtr.Zero && !string.IsNullOrWhiteSpace(model.MainWindowTitle); } catch (Exception ex) when (IsTerminatedProcessException(ex)) { terminated = true; } } if (!terminated) { if (startTimeUtc.HasValue && this.processMetadata.TryGetValue(model.ProcessId, out var cachedMetadata) && cachedMetadata.StartTimeUtc == startTimeUtc.Value) { model.ExecutablePath = cachedMetadata.ExecutablePath; } else { try { model.ExecutablePath = process.MainModule?.FileName ?? string.Empty; if (startTimeUtc.HasValue && !string.IsNullOrWhiteSpace(model.ExecutablePath)) { this.processMetadata[model.ProcessId] = new ProcessMetadata(startTimeUtc.Value, model.ExecutablePath); } } catch (Exception ex) when (IsAccessDeniedException(ex)) { accessDenied = true; model.ExecutablePath = string.Empty; this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex); } catch (Exception ex) when (IsPassiveProcessAccessException(ex)) { accessDenied = true; model.ExecutablePath = string.Empty; this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex); } catch (Exception ex) when (IsTerminatedProcessException(ex)) { terminated = true; } } } } if (terminated) { this.CleanupProcessResources(model.ProcessId); } this.ApplyProcessClassification(model, foregroundProcessId, accessDenied, terminated); return model; } public async Task SetProcessorAffinity(ProcessModel process, long affinityMask) { this.EnsureProcessOperationAllowed(process, "SetProcessAffinity"); await Task.Run(() => { try { if (affinityMask == 0) { throw new InvalidOperationException("Affinity mask cannot be zero."); } // This overload means "hard affinity mask": callers verify the result against // GetProcessAffinityMask. CPU Sets (SetProcessDefaultCpuSets) are only a soft // scheduling hint and leave that mask untouched, so applying them here made every // caller report a VerificationMismatch failure. Soft assignment keeps its own // entry points (CpuAssignmentMode.CpuSets / CpuSelectionAffinityApplier). using var targetProcess = Process.GetProcessById(process.ProcessId); targetProcess.ProcessorAffinity = new IntPtr(affinityMask); process.ProcessorAffinity = (long)targetProcess.ProcessorAffinity; this.AuditProcessOperation("SetProcessAffinity", process.Name, success: true); this.logger?.LogInformation( "Successfully applied classic ProcessorAffinity 0x{AffinityMask:X} to process {ProcessName} (PID: {ProcessId})", affinityMask, process.Name, process.ProcessId); } catch (Win32Exception ex) when (ex.NativeErrorCode == 87) { this.AuditProcessOperation("SetProcessAffinity", process.Name, success: false); throw new InvalidOperationException("Invalid affinity mask for this system.", ex); } catch (Win32Exception ex) when (ex.NativeErrorCode == 5) { this.AuditProcessOperation("SetProcessAffinity", process.Name, success: false); throw new InvalidOperationException("Access denied while setting processor affinity. The process may be protected (e.g., anti-cheat).", ex); } catch (Exception ex) { this.AuditProcessOperation("SetProcessAffinity", process.Name, success: false); throw new InvalidOperationException($"Failed to set processor affinity: {ex.Message}"); } }).ConfigureAwait(false); } public async Task SetProcessorAffinity(ProcessModel process, CpuSelection selection) { if (process == null) { return AffinityApplyResult.Failed( AffinityApplyErrorCodes.ProcessExited, "Process is no longer running.", "ProcessModel is null.", failureReason: AffinityApplyFailureReason.ProcessTerminated); } try { this.EnsureProcessOperationAllowed(process, "SetProcessAffinity"); } catch (Exception ex) when (AffinityApplyExceptionClassifier.IsAccessDenied(ex)) { this.AuditProcessOperation("SetProcessAffinity", process?.Name ?? string.Empty, success: false); var antiCheatLikely = AffinityApplyExceptionClassifier.IsAntiCheatLikely(ex); return AffinityApplyResult.Failed( antiCheatLikely ? AffinityApplyErrorCodes.AntiCheatOrProtectedProcessLikely : AffinityApplyErrorCodes.AccessDenied, antiCheatLikely ? CpuSelectionAffinityApplier.AntiCheatUserMessage : CpuSelectionAffinityApplier.AccessDeniedUserMessage, ex.Message, isAccessDenied: true, isAntiCheatLikely: antiCheatLikely, verifiedMask: process?.ProcessorAffinity ?? 0, failureReason: AffinityApplyFailureReason.AccessDenied); } catch (Exception ex) when (AffinityApplyExceptionClassifier.IsProcessExited(ex)) { this.AuditProcessOperation("SetProcessAffinity", process?.Name ?? string.Empty, success: false); return AffinityApplyResult.Failed( AffinityApplyErrorCodes.ProcessExited, "Process is no longer running.", ex.Message, verifiedMask: process?.ProcessorAffinity ?? 0, failureReason: AffinityApplyFailureReason.ProcessTerminated); } return await this.cpuSelectionAffinityApplier.ApplyAsync(process, selection).ConfigureAwait(false); } private IProcessCpuSetHandler GetOrCreateCpuSetHandler(ProcessModel process) => this.cpuSetHandlers.GetOrAdd(process.ProcessId, pid => { return new ProcessCpuSetHandler((uint)pid, process.Name, this.logger); }); public Task?> GetCpuAssignmentLogicalProcessorIndexesAsync( ProcessModel process, CpuAssignmentMode mode) { ArgumentNullException.ThrowIfNull(process); return Task.Run?>(() => mode switch { CpuAssignmentMode.CpuSets => this.GetOrCreateCpuSetHandler(process) .GetDefaultCpuSetLogicalProcessorIndexes(), CpuAssignmentMode.IdealProcessor => new ProcessThreadCpuAssignmentHandler(process.ProcessId) .GetIdealProcessorIndexes(), _ => null, }); } private async Task ApplyLegacyProcessorAffinityDirectAsync(ProcessModel process, long affinityMask) { return await Task.Run(() => { try { using var targetProcess = Process.GetProcessById(process.ProcessId); targetProcess.ProcessorAffinity = new IntPtr(affinityMask); var verifiedMask = (long)targetProcess.ProcessorAffinity; process.ProcessorAffinity = verifiedMask; this.AuditProcessOperation("SetProcessAffinity", process.Name, success: true); this.logger?.LogInformation( "Successfully applied classic ProcessorAffinity 0x{AffinityMask:X} to process {ProcessName} (PID: {ProcessId})", affinityMask, process.Name, process.ProcessId); return verifiedMask; } catch { this.AuditProcessOperation("SetProcessAffinity", process.Name, success: false); throw; } }).ConfigureAwait(false); } public Task SetProcessPriority(ProcessModel process, ProcessPriorityClass priority) => this.SetProcessPriority(process, priority, ProcessPriorityWriteSource.UnknownInternal); public async Task SetProcessPriority(ProcessModel process, ProcessPriorityClass priority, ProcessPriorityWriteSource source) { ArgumentNullException.ThrowIfNull(process); if (ProcessPriorityGuardrails.IsBlocked(priority)) { this.logger?.LogWarning( "Blocked priority change for process {ProcessName} (PID: {ProcessId}): {Message}", process.Name, process.ProcessId, ProcessOperationUserMessages.RealtimePriorityBlocked); this.AuditProcessOperation("SetProcessPriority", process.Name, success: false); throw new InvalidOperationException(ProcessOperationUserMessages.RealtimePriorityBlocked); } this.EnsureProcessOperationAllowed(process, "SetProcessPriority"); var warning = ProcessPriorityGuardrails.GetWarning(priority); if (!string.IsNullOrWhiteSpace(warning)) { this.logger?.LogWarning( "Applying High priority to process {ProcessName} (PID: {ProcessId}): {Message}", process.Name, process.ProcessId, warning); } await Task.Run(() => { try { using var targetProcess = Process.GetProcessById(process.ProcessId); targetProcess.PriorityClass = priority; process.Priority = targetProcess.PriorityClass; this.logger?.LogInformation( "Set process priority for {ProcessName} (PID: {ProcessId}). Source: {Source}; requested: {RequestedPriority}; observed: {ObservedPriority}; path: {ExecutablePath}", process.Name, process.ProcessId, source, priority, process.Priority, process.ExecutablePath); this.AuditProcessOperation("SetProcessPriority", process.Name, success: true); } catch (Win32Exception ex) when (ex.NativeErrorCode == 5) { this.AuditProcessOperation("SetProcessPriority", process.Name, success: false); throw new InvalidOperationException(ProcessOperationUserMessages.AccessDenied, ex); } catch (UnauthorizedAccessException ex) { this.AuditProcessOperation("SetProcessPriority", process.Name, success: false); throw new InvalidOperationException(ProcessOperationUserMessages.AccessDenied, ex); } catch (Exception ex) { this.AuditProcessOperation("SetProcessPriority", process.Name, success: false); throw new InvalidOperationException($"Failed to set process priority: {ex.Message}"); } }).ConfigureAwait(false); } public async Task SaveProcessProfile(string profileName, ProcessModel process) { var profile = new ProcessProfileSnapshot { ProcessName = process.Name, Priority = process.Priority, ProcessorAffinity = process.ProcessorAffinity, }; var topology = await this.TryGetTopologySnapshotAsync().ConfigureAwait(false); if (topology != null) { this.cpuSelectionMigrationService.PrepareProcessProfileForSave(profile, topology); } if (!IsValidProfileName(profileName)) { return false; } var filePath = Path.Combine(this.ProfilesDirectory, $"{profileName}.json"); var json = JsonSerializer.Serialize(profile, new JsonSerializerOptions { WriteIndented = true }); await AtomicFileWriter.WriteAllTextAsync(filePath, json, Encoding.UTF8).ConfigureAwait(false); return true; } public async Task LoadProcessProfile(string profileName, ProcessModel process) { if (!IsValidProfileName(profileName)) { return false; } var filePath = Path.Combine(this.ProfilesDirectory, $"{profileName}.json"); if (!File.Exists(filePath)) { return false; } var content = await File.ReadAllTextAsync(filePath).ConfigureAwait(false); var profile = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }); if (profile == null) { return false; } if (ProcessPriorityGuardrails.IsBlocked(profile.Priority)) { this.logger?.LogWarning( "Profile {ProfileName} requested blocked priority {Priority} for process {ProcessName} (PID: {ProcessId}). {Message}", profileName, profile.Priority, process.Name, process.ProcessId, ProcessOperationUserMessages.RealtimePriorityBlocked); return false; } await this.SetLoadProcessProfilePriorityAsync(process, profile.Priority).ConfigureAwait(false); var topology = await this.TryGetTopologySnapshotAsync().ConfigureAwait(false); if (topology != null) { this.cpuSelectionMigrationService.MigrateProcessProfile(profile, topology); } if (profile.CpuSelection != null) { var result = await this.SetLoadProcessProfileCpuSelectionAsync(process, profile.CpuSelection).ConfigureAwait(false); if (!result.Success) { this.logger?.LogWarning( "Failed to apply CpuSelection profile {ProfileName} to process {ProcessName} (PID: {ProcessId}). ErrorCode: {ErrorCode}. Message: {Message}", profileName, process.Name, process.ProcessId, result.ErrorCode, result.Message); return false; } } else { await this.SetLoadProcessProfileLegacyAffinityAsync(process, profile.ProcessorAffinity).ConfigureAwait(false); } return true; } private Task SetLoadProcessProfilePriorityAsync(ProcessModel process, ProcessPriorityClass priority) => this.loadProcessProfilePrioritySetter != null ? this.loadProcessProfilePrioritySetter(process, priority) : this.SetProcessPriority(process, priority, ProcessPriorityWriteSource.ProcessProfileLoad); private Task SetLoadProcessProfileCpuSelectionAsync(ProcessModel process, CpuSelection selection) => this.loadProcessProfileCpuSelectionSetter != null ? this.loadProcessProfileCpuSelectionSetter(process, selection) : this.SetProcessorAffinity(process, selection); private Task SetLoadProcessProfileLegacyAffinityAsync(ProcessModel process, long affinityMask) => this.loadProcessProfileLegacyAffinitySetter != null ? this.loadProcessProfileLegacyAffinitySetter(process, affinityMask) : this.SetProcessorAffinity(process, affinityMask); private async Task TryGetTopologySnapshotAsync() { if (this.cpuTopologyProvider == null) { return null; } try { return await this.cpuTopologyProvider.GetTopologySnapshotAsync().ConfigureAwait(false); } catch (Exception ex) { this.logger?.LogWarning(ex, "Failed to get CPU topology snapshot for profile CpuSelection migration"); return null; } } public async Task RefreshProcessInfo(ProcessModel process) { await Task.Run(() => { try { using var p = Process.GetProcessById(process.ProcessId); // Check if process has exited if (p.HasExited) { throw new InvalidOperationException("Process has exited"); } process.MemoryUsage = p.PrivateMemorySize64; process.Priority = p.PriorityClass; process.ProcessorAffinity = (long)p.ProcessorAffinity; process.CpuUsage = this.CalculateCpuUsage(p); // Update window information process.MainWindowHandle = p.MainWindowHandle; process.MainWindowTitle = p.MainWindowTitle ?? string.Empty; process.HasVisibleWindow = process.MainWindowHandle != IntPtr.Zero && !string.IsNullOrWhiteSpace(process.MainWindowTitle); if (string.IsNullOrWhiteSpace(process.ExecutablePath)) { process.ExecutablePath = p.MainModule?.FileName ?? string.Empty; } this.ApplyProcessClassification( process, this.foregroundProcessService?.TryGetForegroundProcessId(), accessDenied: false, terminated: false); } catch (ArgumentException) { // Process with the specified ID does not exist this.CleanupProcessResources(process.ProcessId); this.ApplyProcessClassification(process, null, accessDenied: false, terminated: true); throw new InvalidOperationException("Process no longer exists"); } catch (Exception ex) when (IsAccessDeniedException(ex)) { this.ApplyProcessClassification(process, null, accessDenied: true, terminated: false); throw new InvalidOperationException("Access denied while refreshing process information.", ex); } catch (Exception ex) when (ex.Message.Contains("exited") || ex.Message.Contains("terminated")) { // Process has terminated this.CleanupProcessResources(process.ProcessId); this.ApplyProcessClassification(process, null, accessDenied: false, terminated: true); throw new InvalidOperationException("Process has terminated"); } }).ConfigureAwait(false); } private void ApplyProcessClassification( ProcessModel process, int? foregroundProcessId, bool accessDenied, bool terminated) { process.IsForeground = foregroundProcessId == process.ProcessId && !accessDenied && !terminated; process.Classification = this.processClassifier.Classify( process, new ProcessClassificationContext(foregroundProcessId, accessDenied, terminated)); } private void LogPassiveProcessReadFailure(int processId, PassiveProcessErrorKind errorKind, Exception exception) { if (this.passiveProcessErrorThrottle.ShouldLog(processId, errorKind)) { this.logger?.LogDebug( exception, "Passive process read returned {ErrorKind} for PID {ProcessId}", errorKind, processId); } } internal static bool IsPassiveProcessAccessException(Exception exception) { return IsAccessDeniedException(exception) || exception is Win32Exception { NativeErrorCode: 299 } || exception.Message.Contains("enumerate the process modules", StringComparison.OrdinalIgnoreCase) || exception.Message.Contains("access modules", StringComparison.OrdinalIgnoreCase) || exception.Message.Contains("ReadProcessMemory", StringComparison.OrdinalIgnoreCase); } private static bool IsAccessDeniedException(Exception exception) { return exception is UnauthorizedAccessException || exception is Win32Exception { NativeErrorCode: 5 }; } private static bool IsTerminatedProcessException(Exception exception) { return exception is ArgumentException || (exception is InvalidOperationException invalidOperationException && (invalidOperationException.Message.Contains("exited", StringComparison.OrdinalIgnoreCase) || invalidOperationException.Message.Contains("terminated", StringComparison.OrdinalIgnoreCase) || invalidOperationException.Message.Contains("no longer exists", StringComparison.OrdinalIgnoreCase))); } private static int? TryGetProcessId(Process process) { try { return process.Id; } catch { return null; } } private static ProcessModel? CreateMinimalProcessModel( Process process, int? processId, ProcessClassification classification) { if (!processId.HasValue) { return null; } return new ProcessModel { ProcessId = processId.Value, Name = TryGetProcessName(process, processId.Value), ExecutablePath = string.Empty, MainWindowHandle = IntPtr.Zero, MainWindowTitle = string.Empty, HasVisibleWindow = false, Classification = classification, }; } private static string TryGetProcessName(Process process, int processId) { try { return process.ProcessName; } catch { return $"PID_{processId}"; } } private void CleanupProcessResources(int processId) { // Remove process-scoped samples and static metadata. this.cpuSamples.TryRemove(processId, out _); this.processMetadata.TryRemove(processId, out _); // Dispose and remove CPU Set handler if (this.cpuSetHandlers.TryRemove(processId, out var handler)) { try { handler.Dispose(); this.logger?.LogDebug("Cleaned up CPU Set handler for process ID {ProcessId}", processId); } catch (Exception ex) { this.logger?.LogWarning(ex, "Error disposing CPU Set handler for process ID {ProcessId}", processId); } } } public void SetUseCpuSets(bool useCpuSets) { this.useCpuSets = useCpuSets; this.logger?.LogInformation("CPU Sets usage {Status}", useCpuSets ? "enabled" : "disabled"); } public bool GetUseCpuSets() { return this.useCpuSets; } public async Task ClearProcessCpuSetAsync(ProcessModel process) { return await Task.Run(() => { try { if (!this.useCpuSets) { this.logger?.LogDebug("CPU Sets are disabled, cannot clear CPU Set for process {ProcessName}", process.Name); return false; } // Get or create CPU Set handler for this process var handler = this.cpuSetHandlers.GetOrAdd(process.ProcessId, pid => { return new ProcessCpuSetHandler((uint)pid, process.Name, this.logger); }); if (!handler.IsValid) { this.logger?.LogDebug( "CPU Set handler for process {ProcessName} (PID: {ProcessId}) is invalid", process.Name, process.ProcessId); this.cpuSetHandlers.TryRemove(process.ProcessId, out _); return false; } // Clear the mask (set clearMask = true) bool success = handler.ApplyCpuSetMask(0, clearMask: true); if (success) { this.logger?.LogInformation( "Successfully cleared CPU Set for process {ProcessName} (PID: {ProcessId})", process.Name, process.ProcessId); } else { this.cpuSetHandlers.TryRemove(process.ProcessId, out _); } return success; } catch (Exception ex) { this.logger?.LogWarning(ex, "Exception while clearing CPU Set for process {ProcessName} (PID: {ProcessId})", process.Name, process.ProcessId); this.cpuSetHandlers.TryRemove(process.ProcessId, out _); return false; } }).ConfigureAwait(false); } public async Task GetProcessByIdAsync(int processId) { return await Task.Run(() => { try { using var process = Process.GetProcessById(processId); return this.CreateProcessModel(process); } catch { return null; } }).ConfigureAwait(false); } public async Task> GetProcessesByNameAsync(string executableName) { return await Task.Run>(() => { try { var foregroundProcessId = this.foregroundProcessService?.TryGetForegroundProcessId(); var models = new List(); foreach (var process in Process.GetProcessesByName(executableName)) { using (process) { var model = this.TryCreateProcessModel(process, foregroundProcessId); if (model != null) { models.Add(model); } } } return models; } catch { return Array.Empty(); } }).ConfigureAwait(false); } public async Task IsProcessRunningAsync(string executableName) { var processes = await this.GetProcessesByNameAsync(executableName).ConfigureAwait(false); return processes.Any(); } public async Task> GetProcessesWithPathsAsync(Func nameFilter) { return await Task.Run>(() => this.EnumerateProcessModels(process => !string.IsNullOrEmpty(process.ExecutablePath), nameFilter)).ConfigureAwait(false); } public async Task> GetActiveApplicationsAsync() { return await Task.Run(() => new ObservableCollection( this.EnumerateProcessModels(process => process.HasVisibleWindow))).ConfigureAwait(false); } public async Task IsProcessStillRunning(ProcessModel process) { return await Task.Run(() => { try { using var targetProcess = Process.GetProcessById(process.ProcessId); return !targetProcess.HasExited; } catch (ArgumentException) { // Process with the specified ID does not exist return false; } catch { // Any other exception means process is not accessible/running return false; } }).ConfigureAwait(false); } public async Task SetRegistryPriorityAsync(ProcessModel process, bool enable, ProcessPriorityClass priority) { ArgumentNullException.ThrowIfNull(process); if (enable && ProcessPriorityGuardrails.IsBlocked(priority)) { this.logger?.LogWarning( "Registry priority request blocked for process {ProcessName} (PID: {ProcessId}). {Message}", process.Name, process.ProcessId, ProcessOperationUserMessages.RealtimePriorityBlocked); this.AuditProcessOperation("SetProcessPriority", process.Name, success: false); return false; } this.EnsureProcessOperationAllowed(process, "SetProcessPriority"); // Without an image name the key below would be the IFEO root itself. var imageName = Path.GetFileName(process.ExecutablePath); if (string.IsNullOrWhiteSpace(imageName)) { this.AuditProcessOperation("SetProcessPriority", process.Name, success: false); return false; } return await Task.Run(() => { try { var imageKeyPath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\" + imageName; using (var legacyKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(imageKeyPath, writable: true)) { // Earlier versions wrote this value, which Windows never reads. legacyKey?.DeleteValue("PriorityClass", false); } using var key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(imageKeyPath + @"\PerfOptions"); if (enable) { int priorityValue = priority switch { ProcessPriorityClass.Idle => 1, ProcessPriorityClass.BelowNormal => 5, ProcessPriorityClass.AboveNormal => 6, ProcessPriorityClass.High => 3, _ => 2, // Normal }; key.SetValue("CpuPriorityClass", priorityValue, Microsoft.Win32.RegistryValueKind.DWord); } else { key.DeleteValue("CpuPriorityClass", false); } this.AuditProcessOperation("SetProcessPriority", process.Name, success: true); return true; } catch (Exception) { this.AuditProcessOperation("SetProcessPriority", process.Name, success: false); return false; } }).ConfigureAwait(false); } // A plain file name: no folders, no "..", nothing Windows rejects in a file name. internal static bool IsValidProfileName(string? profileName) => !string.IsNullOrWhiteSpace(profileName) && profileName.Trim('.').Length > 0 && string.Equals(Path.GetFileName(profileName), profileName, StringComparison.Ordinal) && profileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0; private void EnsureProcessOperationAllowed(ProcessModel process, string operation) { ArgumentNullException.ThrowIfNull(process); if (this.securityService == null) { return; } var processName = this.GetProcessDisplayName(process); if (!this.securityService.ValidateProcessOperation(processName, operation)) { this.AuditProcessOperation(operation, processName, success: false); throw new UnauthorizedAccessException( $"Operation '{operation}' is not permitted for process '{processName}'."); } try { using var liveProcess = Process.GetProcessById(process.ProcessId); if (this.securityService.IsProtected(liveProcess)) { this.AuditProcessOperation(operation, processName, success: false); throw new UnauthorizedAccessException( $"Operation '{operation}' is blocked for protected process '{processName}'."); } } catch (ArgumentException) { // Process already exited; defer to operation code-paths for termination handling. } } private string GetProcessDisplayName(ProcessModel process) { if (!string.IsNullOrWhiteSpace(process.Name)) { return process.Name; } return $"PID_{process.ProcessId}"; } private void AuditProcessOperation(string operation, string processName, bool success) { if (this.securityService == null) { return; } TaskSafety.FireAndForget( this.securityService.AuditElevatedAction(operation, processName, success), ex => this.logger?.LogDebug(ex, "Security audit logging failed for {Operation} on {ProcessName}", operation, processName)); } public void TrackAppliedMask(int processId, string maskId) { this.appliedMasks[processId] = maskId; this.logger?.LogDebug("Tracking mask {MaskId} applied to process {ProcessId}", maskId, processId); } public void TrackPriorityChange(int processId, ProcessPriorityClass originalPriority) { // Only track if not already tracked (keep the original priority) if (!this.originalPriorities.ContainsKey(processId)) { this.originalPriorities[processId] = originalPriority; this.logger?.LogDebug("Tracking original priority {Priority} for process {ProcessId}", originalPriority, processId); } } public void UntrackProcess(int processId) { this.appliedMasks.TryRemove(processId, out _); this.originalPriorities.TryRemove(processId, out _); this.CleanupProcessResources(processId); this.logger?.LogDebug("Untracked process {ProcessId}", processId); } public Task ClearAllAppliedMasksAsync() { this.logger?.LogInformation("Clearing all applied CPU masks from {Count} tracked processes", this.appliedMasks.Count); var processIds = this.appliedMasks.Keys.ToList(); var clearedCount = 0; var failedCount = 0; foreach (var processId in processIds) { try { // Check if process is still running Process process; try { process = Process.GetProcessById(processId); if (process.HasExited) { this.appliedMasks.TryRemove(processId, out _); continue; } } catch (ArgumentException) { // Process no longer exists this.appliedMasks.TryRemove(processId, out _); continue; } // Clear CPU Set if we have a handler if (this.cpuSetHandlers.TryGetValue(processId, out var handler) && handler.IsValid) { handler.ApplyCpuSetMask(0, clearMask: true); this.logger?.LogDebug( "Cleared CPU Set for process {ProcessName} (PID: {ProcessId})", process.ProcessName, processId); } // Reset processor affinity to all cores try { long allCoresMask = this.GetAllCoresAffinityMask(); process.ProcessorAffinity = new IntPtr(allCoresMask); this.logger?.LogDebug( "Reset ProcessorAffinity for process {ProcessName} (PID: {ProcessId})", process.ProcessName, processId); } catch (Exception ex) { this.logger?.LogWarning(ex, "Failed to reset ProcessorAffinity for process PID {ProcessId}", processId); } this.appliedMasks.TryRemove(processId, out _); clearedCount++; } catch (Exception ex) { this.logger?.LogWarning(ex, "Failed to clear mask for process PID {ProcessId}", processId); failedCount++; } } this.logger?.LogInformation("Cleared CPU masks: {Cleared} succeeded, {Failed} failed", clearedCount, failedCount); return Task.CompletedTask; } public Task ResetAllProcessPrioritiesAsync() { this.logger?.LogInformation("Resetting priorities for {Count} tracked processes", this.originalPriorities.Count); var processIds = this.originalPriorities.Keys.ToList(); var resetCount = 0; var failedCount = 0; foreach (var processId in processIds) { try { // Check if process is still running Process process; try { process = Process.GetProcessById(processId); if (process.HasExited) { this.originalPriorities.TryRemove(processId, out _); continue; } } catch (ArgumentException) { // Process no longer exists this.originalPriorities.TryRemove(processId, out _); continue; } // Get original priority if (this.originalPriorities.TryGetValue(processId, out var originalPriority)) { process.PriorityClass = originalPriority; this.logger?.LogInformation( "Set process priority for {ProcessName} (PID: {ProcessId}). Source: {Source}; requested: {RequestedPriority}; observed: {ObservedPriority}; path: {ExecutablePath}", process.ProcessName, processId, ProcessPriorityWriteSource.CleanupOrRestore, originalPriority, process.PriorityClass, string.Empty); } this.originalPriorities.TryRemove(processId, out _); resetCount++; } catch (Exception ex) { this.logger?.LogWarning(ex, "Failed to reset priority for process PID {ProcessId}", processId); failedCount++; } } this.logger?.LogInformation("Reset priorities: {Reset} succeeded, {Failed} failed", resetCount, failedCount); return Task.CompletedTask; } private long GetAllCoresAffinityMask() { int coreCount = Environment.ProcessorCount; return coreCount >= 64 ? -1L : (1L << coreCount) - 1; } private void MigrateLegacyProfilesIfNeeded() { try { if (!Directory.Exists(LegacyProfilesDirectory)) { return; } Directory.CreateDirectory(this.ProfilesDirectory); var legacyFiles = Directory.GetFiles(LegacyProfilesDirectory, "*.json"); foreach (var legacyFile in legacyFiles) { var destinationFile = Path.Combine(this.ProfilesDirectory, Path.GetFileName(legacyFile)); if (!File.Exists(destinationFile)) { File.Copy(legacyFile, destinationFile); } } if (legacyFiles.Length > 0) { this.logger?.LogInformation("Migrated {Count} legacy profile files to AppData storage", legacyFiles.Length); } } catch (Exception ex) { this.logger?.LogWarning(ex, "Failed to migrate legacy profile files"); } } } }