diff --git a/Helpers/WindowPlacementHelper.cs b/Helpers/WindowPlacementHelper.cs index 4a39681..c91b789 100644 --- a/Helpers/WindowPlacementHelper.cs +++ b/Helpers/WindowPlacementHelper.cs @@ -32,7 +32,7 @@ public readonly record struct MonitorWorkingArea(double Left, double Top, double public static class WindowPlacementHelper { private const double DefaultWindowWidth = 1280; - private const double DefaultWindowHeight = 864; + private const double DefaultWindowHeight = 960; private const double MinimumVisibleAreaRatio = 0.25; // A window this close to filling its monitor's working area is treated as having no diff --git a/Locales/de-DE.xaml b/Locales/de-DE.xaml index cc78435..95b1734 100644 --- a/Locales/de-DE.xaml +++ b/Locales/de-DE.xaml @@ -266,6 +266,9 @@ CPU-Zuweisungsmodus System wach halten, solange dieser Prozess läuft Wählen Sie eine gespeicherte CPU-Maske für die Kerne dieser Regel. Masken werden auf der Seite „CPU-Masken“ bearbeitet. + CPU-Masken-Vorlage (legt die Kerne fest; der Modus oben entscheidet CPU-Sets oder Affinität) + Aktuelle Kerne beibehalten + Diese Regeln legen Kerne einer anderen CPU als der aktuellen fest, daher bedeutet ihre Auswahl möglicherweise nicht mehr dasselbe wie beim Speichern: {0}. Lege ihre Kerne unten mit einer gespeicherten Maske neu fest. Änderungen speichern Noch keine gespeicherten Prozessregeln. Klicken Sie auf der Registerkarte Prozesse mit der rechten Maustaste auf einen Prozess und wählen Sie Regeln. Ausführbar @@ -293,6 +296,12 @@ Kein Prozess ausgewählt Ausstehende Kernmaske + Aktuelle CPU-Sets: CPU {0} ({1}) + von Game Boost gesetzt, solange das Spiel läuft + aus deiner gespeicherten Regel + manuell, von der App selbst oder von einem anderen Tool gesetzt + Aktuelle ideale Prozessoren: CPU {0} + keine CPU-Sets, Windows wählt die Kerne Kerne anwenden Wendet die CPU-Auswahl im gewählten Modus an und überprüft den Windows-Status CPU-Zuweisung anwenden und als Regel speichern diff --git a/Locales/en-US.xaml b/Locales/en-US.xaml index b05f493..0f4daea 100644 --- a/Locales/en-US.xaml +++ b/Locales/en-US.xaml @@ -266,6 +266,9 @@ CPU assignment mode Keep the system awake while this process runs Pick a saved CPU mask for this rule's cores. Masks are edited on the CPU masks page. + CPU mask preset (sets the cores; the mode above decides CPU Sets or affinity) + Keep the current cores + These rules pin cores from a different CPU than the one running now, so what they select may not mean what it did when they were saved: {0}. Set their cores again from a saved mask below. Save changes No saved process rules yet. Right-click a process in the Process tab and choose Rules to save one. Executable @@ -293,6 +296,12 @@ No process selected Pending core mask + Current CPU Sets: CPU {0} ({1}) + set by Game Boost while the game runs + from your saved rule + set by hand, by the app itself or by another tool + Current ideal processors: CPU {0} + no CPU Sets, Windows picks the cores Apply cores Apply the pending CPU selection with the selected mode and verify the Windows state Apply CPU Assignment and Save as Rule diff --git a/Locales/es-ES.xaml b/Locales/es-ES.xaml index b22a1ff..ebcb4ba 100644 --- a/Locales/es-ES.xaml +++ b/Locales/es-ES.xaml @@ -266,6 +266,9 @@ Modo de asignación de CPU Impedir la suspensión mientras este proceso se ejecuta Elige una máscara de CPU guardada para los núcleos de esta regla. Las máscaras se editan en la página Máscaras de CPU. + Plantilla de máscara de CPU (fija los núcleos; el modo de arriba decide CPU Sets o afinidad) + Mantener los núcleos actuales + Estas reglas fijan núcleos de una CPU distinta de la actual, así que su selección puede no significar lo mismo que cuando se guardaron: {0}. Vuelve a fijar sus núcleos con una máscara guardada abajo. Guardar cambios Aún no hay reglas de proceso guardadas. Haz clic derecho en un proceso en la pestaña Procesos y elige Reglas para guardar una. ejecutable @@ -293,6 +296,12 @@ Ningún proceso seleccionado Máscara de núcleos pendiente + CPU Sets actuales: CPU {0} ({1}) + establecidos por Game Boost mientras el juego está abierto + de tu regla guardada + establecidos a mano, por la propia app o por otra herramienta + Procesadores ideales actuales: CPU {0} + sin CPU Sets, Windows elige los núcleos Aplicar núcleos Aplica la selección de CPU con el modo elegido y verifica el estado de Windows Aplicar asignación de CPU y guardar como regla diff --git a/Locales/fr-FR.xaml b/Locales/fr-FR.xaml index 2c06466..26695cf 100644 --- a/Locales/fr-FR.xaml +++ b/Locales/fr-FR.xaml @@ -266,6 +266,9 @@ Mode d'affectation CPU Empêcher la mise en veille pendant l'exécution de ce processus Choisissez un masque CPU enregistré pour les cœurs de cette règle. Les masques se modifient dans la page Masques CPU. + Modèle de masque CPU (fixe les cœurs ; le mode ci-dessus décide CPU Sets ou affinité) + Garder les cœurs actuels + Ces règles fixent des cœurs d'un autre processeur que celui en cours, leur sélection peut donc ne plus avoir le même sens qu'à l'enregistrement : {0}. Redéfinissez leurs cœurs avec un masque enregistré ci-dessous. Enregistrer les modifications Aucune règle de processus enregistrée. Faites un clic droit sur un processus dans l'onglet Processus et choisissez Règles pour en enregistrer une. Exécutable @@ -293,6 +296,12 @@ Aucun processus sélectionné Masque de cœurs en attente + CPU Sets actuels : CPU {0} ({1}) + définis par Game Boost tant que le jeu tourne + depuis votre règle enregistrée + définis à la main, par l'application elle-même ou par un autre outil + Processeurs idéaux actuels : CPU {0} + aucun CPU Set, Windows choisit les cœurs Appliquer les cœurs Applique la sélection CPU avec le mode choisi et vérifie l’état Windows Appliquer l’affectation CPU et enregistrer la règle diff --git a/Locales/it-IT.xaml b/Locales/it-IT.xaml index 2a482b0..f1aedef 100644 --- a/Locales/it-IT.xaml +++ b/Locales/it-IT.xaml @@ -266,6 +266,9 @@ Modalità di assegnazione CPU Impedisci la sospensione mentre il processo è in esecuzione Scegli una maschera CPU salvata per i core di questa regola. Le maschere si modificano nella pagina Maschere CPU. + Preset maschera CPU (imposta i core; la modalità sopra decide CPU Set o affinità) + Mantieni i core attuali + Queste regole fissano core di una CPU diversa da quella in uso, quindi la loro selezione potrebbe non significare più ciò che significava al salvataggio: {0}. Reimposta i loro core con una maschera salvata qui sotto. Salva modifiche Nessuna regola di processo salvata. Fai clic destro su un processo nella scheda Processi e scegli Regole per salvarne una. Eseguibile @@ -293,6 +296,12 @@ Nessun processo selezionato Maschera core in sospeso + CPU Set attuali: CPU {0} ({1}) + impostati da Game Boost finché il gioco è aperto + dalla tua regola salvata + impostati a mano, dall'app stessa o da un altro programma + Processori ideali attuali: CPU {0} + nessun CPU Set, i core li sceglie Windows Applica core Applica la selezione CPU con la modalità scelta e verifica lo stato di Windows Applica assegnazione CPU e salva come regola diff --git a/Locales/ru-RU.xaml b/Locales/ru-RU.xaml index 2bc6a53..e4a33f5 100644 --- a/Locales/ru-RU.xaml +++ b/Locales/ru-RU.xaml @@ -266,6 +266,9 @@ Режим назначения ЦП Не давать системе засыпать, пока процесс работает Выберите сохранённую маску CPU для ядер этого правила. Маски редактируются на странице «Маски CPU». + Шаблон маски ЦП (задаёт ядра; режим выше определяет CPU Sets или привязку) + Оставить текущие ядра + Эти правила закрепляют ядра другого процессора, поэтому их выбор может значить не то, что при сохранении: {0}. Задайте их ядра заново с помощью сохранённой маски ниже. Сохранить изменения Сохранённых правил процессов пока нет. Щёлкните процесс правой кнопкой на вкладке «Процессы» и выберите «Правила». Исполняемый файл @@ -293,6 +296,12 @@ Процесс не выбран Ожидающая маска ядер + Текущие наборы ЦП (CPU Sets): ЦП {0} ({1}) + заданы Game Boost, пока запущена игра + из вашего сохранённого правила + заданы вручную, самим приложением или другой программой + Текущие идеальные процессоры: ЦП {0} + нет CPU Sets, ядра выбирает Windows Применить ядра Применяет выбор ЦП в выбранном режиме и проверяет состояние Windows. Применить назначение ЦП и сохранить правило diff --git a/Locales/zh-CN.xaml b/Locales/zh-CN.xaml index 76d2b5a..cbbbd46 100644 --- a/Locales/zh-CN.xaml +++ b/Locales/zh-CN.xaml @@ -266,6 +266,9 @@ CPU 分配模式 该进程运行时阻止系统休眠 为此规则的核心选择已保存的 CPU 掩码。掩码在“CPU 掩码”页面中编辑。 + CPU 掩码预设(设定核心;上方的模式决定使用 CPU 集或亲和性) + 保留当前核心 + 这些规则固定的是另一颗 CPU 的核心,所选内容可能已与保存时含义不同:{0}。请在下方用已保存的掩码重新设置其核心。 保存更改 尚无已保存的进程规则。在“进程”选项卡中右键点击某个进程并选择“规则”即可保存。 可执行文件 @@ -293,6 +296,12 @@ 未选择进程 待处理的核心掩码 + 当前 CPU 集:CPU {0}({1}) + 由 Game Boost 在游戏运行期间设置 + 来自你保存的规则 + 由手动、应用自身或其他工具设置 + 当前理想处理器:CPU {0} + 无 CPU 集,由 Windows 选择核心 应用核心 使用所选模式应用待处理 CPU 选择,并验证 Windows 状态 应用 CPU 分配并保存为规则 diff --git a/MainWindow.UiState.partial.cs b/MainWindow.UiState.partial.cs index 6946bb6..d6527e3 100644 --- a/MainWindow.UiState.partial.cs +++ b/MainWindow.UiState.partial.cs @@ -20,7 +20,7 @@ private void RestoreUiState() this.Left = state.WindowLeft.Value; this.Top = state.WindowTop.Value; this.Width = state.WindowWidth.Value; - this.Height = state.WindowHeight.Value; + this.Height = UpgradeLegacyDefaultHeight(state.WindowWidth.Value, state.WindowHeight.Value); } if (state.WindowMaximized) @@ -29,6 +29,12 @@ private void RestoreUiState() } } + // 1280 x 864 was the default size before the editors on the Rules page got taller: a saved size that is + // exactly that was never resized by the user, so it gets the new default height. Placement correction still + // shrinks it to the screen's working area. + internal static double UpgradeLegacyDefaultHeight(double width, double height) => + width == 1280 && height == 864 ? 960 : height; + private void SaveWindowPlacement() { // RestoreBounds is the normal-size rectangle even while maximized or minimized. diff --git a/MainWindow.xaml b/MainWindow.xaml index 6dd0912..6ff8a0c 100644 --- a/MainWindow.xaml +++ b/MainWindow.xaml @@ -11,7 +11,7 @@ ExtendsContentIntoTitleBar="True" WindowBackdropType="Mica" Title="{DynamicResource MainWindow_Title}" - Height="864" + Height="960" Width="1280" WindowStartupLocation="CenterScreen" UseLayoutRounding="True" diff --git a/Platforms/Windows/MainWindowSnapshot.cs b/Platforms/Windows/MainWindowSnapshot.cs new file mode 100644 index 0000000..7959a5c --- /dev/null +++ b/Platforms/Windows/MainWindowSnapshot.cs @@ -0,0 +1,81 @@ +namespace ThreadPilot.Platforms.Windows +{ + using System; + using System.Collections.Generic; + using System.Runtime.InteropServices; + + /// + /// The main window of every process from one EnumWindows pass. Process.MainWindowHandle runs its own + /// EnumWindows over the whole desktop for each process, so a list refresh cost processes × windows. + /// Same rule as .NET's MainWindowFinder: the first visible, unowned top-level window in Z order. + /// + internal static partial class MainWindowSnapshot + { + private const uint GwOwner = 4; + + public static unsafe Dictionary Capture() + { + var windows = new Dictionary(); + var handle = GCHandle.Alloc(windows); + try + { + EnumWindows(&OnWindow, GCHandle.ToIntPtr(handle)); + } + finally + { + handle.Free(); + } + + return windows; + } + + /// Gets the window title the way Process.MainWindowTitle reads it. + public static unsafe string GetTitle(nint window) + { + var length = GetWindowTextLengthW(window); + if (length <= 0) + { + return string.Empty; + } + + var buffer = new char[length + 1]; + fixed (char* text = buffer) + { + var copied = GetWindowTextW(window, text, buffer.Length); + return copied > 0 ? new string(text, 0, copied) : string.Empty; + } + } + + [UnmanagedCallersOnly] + private static int OnWindow(nint window, nint state) + { + if (GetWindow(window, GwOwner) == 0 && IsWindowVisible(window)) + { + _ = GetWindowThreadProcessId(window, out var processId); + ((Dictionary)GCHandle.FromIntPtr(state).Target!).TryAdd(processId, window); + } + + return 1; + } + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static unsafe partial bool EnumWindows(delegate* unmanaged callback, nint state); + + [LibraryImport("user32.dll")] + private static partial nint GetWindow(nint window, uint command); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool IsWindowVisible(nint window); + + [LibraryImport("user32.dll")] + private static partial uint GetWindowThreadProcessId(nint window, out int processId); + + [LibraryImport("user32.dll")] + private static partial int GetWindowTextLengthW(nint window); + + [LibraryImport("user32.dll")] + private static unsafe partial int GetWindowTextW(nint window, char* text, int maxCount); + } +} diff --git a/Platforms/Windows/ProcessCpuSetHandler.cs b/Platforms/Windows/ProcessCpuSetHandler.cs index 58c8a84..6cf562b 100644 --- a/Platforms/Windows/ProcessCpuSetHandler.cs +++ b/Platforms/Windows/ProcessCpuSetHandler.cs @@ -377,7 +377,7 @@ private CpuSetApplyResult ApplyCpuSetIdsDetailed(uint[]? cpuSetIds, uint cpuSetI } this.logger?.LogWarning(errorMessage); - return this.CreateNativeFailureResult(operationName, error, errorMessage); + return this.CreateNativeFailureResult(operationName, error, errorMessage, handleOpened: true); } private bool VerifyCpuSetIds(uint[] expected, uint expectedCount) @@ -458,21 +458,31 @@ private List GetUnavailableAllocatedCpuSetIds(IReadOnlyList selected return unavailable; } + // handleOpened: Windows granted the handle, then refused the call made with it. ThreadPilot always runs + // elevated, so that is a kernel callback (anti-cheat, anti-tamper) stripping rights, not missing admin rights. private CpuSetApplyResult CreateNativeFailureResult( string operationName, int win32ErrorCode, - string? technicalMessage = null) + string? technicalMessage = null, + bool handleOpened = false) { var message = technicalMessage ?? $"Could not {operationName} for '{this.executableName}' (PID: {this.pid}): {new Win32Exception(win32ErrorCode).Message}"; var accessDenied = win32ErrorCode == 5; + var protectedLikely = accessDenied && handleOpened; + var userMessage = ProcessOperationUserMessages.CpuSetsUnavailable; + if (accessDenied) + { + userMessage = protectedLikely ? ProcessOperationUserMessages.AntiCheatProtectedLikely : ProcessOperationUserMessages.AccessDenied; + } return CpuSetApplyResult.Failed( accessDenied ? AffinityApplyErrorCodes.AccessDenied : AffinityApplyErrorCodes.NativeApplyFailed, - accessDenied ? ProcessOperationUserMessages.AccessDenied : ProcessOperationUserMessages.CpuSetsUnavailable, + userMessage, message, win32ErrorCode, - isAccessDenied: accessDenied); + isAccessDenied: accessDenied, + isAntiCheatLikely: protectedLikely); } private static CpuSetMapping GetCpuSetMapping(IProcessCpuSetNativeApi nativeApi) diff --git a/Platforms/Windows/ProcessImagePath.cs b/Platforms/Windows/ProcessImagePath.cs new file mode 100644 index 0000000..78b0adb --- /dev/null +++ b/Platforms/Windows/ProcessImagePath.cs @@ -0,0 +1,58 @@ +namespace ThreadPilot.Platforms.Windows +{ + using System; + using System.Runtime.InteropServices; + using Microsoft.Win32.SafeHandles; + + /// + /// Reads a process's executable path with QueryFullProcessImageName and PROCESS_QUERY_LIMITED_INFORMATION. + /// Process.MainModule needs PROCESS_VM_READ to walk the module list in the target's memory, which anti-cheats + /// (BattlEye on Arma Reforger, for one) refuse, so their games looked pathless and were never detected. + /// + internal static partial class ProcessImagePath + { + private const uint ProcessQueryLimitedInformation = 0x1000; + private const int ErrorInsufficientBuffer = 122; + private const int MaxPathChars = 32768; + + /// Gets the Win32 path of the process image, or null when Windows does not give it. + public static string? TryGet(int processId) + { + if (processId <= 0) + { + return null; + } + + using var handle = OpenProcess(ProcessQueryLimitedInformation, false, (uint)processId); + if (handle.IsInvalid) + { + return null; + } + + // Almost every path fits in 1024 chars; long-path installs get one retry with the largest size. + foreach (var capacity in new[] { 1024, MaxPathChars }) + { + var buffer = new char[capacity]; + var length = buffer.Length; + if (QueryFullProcessImageName(handle, 0, buffer, ref length)) + { + return length > 0 ? new string(buffer, 0, length) : null; + } + + if (Marshal.GetLastPInvokeError() != ErrorInsufficientBuffer) + { + return null; + } + } + + return null; + } + + [LibraryImport("kernel32.dll", SetLastError = true)] + private static partial SafeProcessHandle OpenProcess(uint access, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, uint processId); + + [LibraryImport("kernel32.dll", EntryPoint = "QueryFullProcessImageNameW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool QueryFullProcessImageName(SafeProcessHandle process, uint flags, [Out] char[] exeName, ref int size); + } +} diff --git a/Services/ActivityAuditService.cs b/Services/ActivityAuditService.cs index ee0f527..9140829 100644 --- a/Services/ActivityAuditService.cs +++ b/Services/ActivityAuditService.cs @@ -6,14 +6,16 @@ public sealed class ActivityAuditService : IActivityAuditService { private const int MaxEntries = 1000; private readonly ILogger logger; + private readonly IEnhancedLoggingService? fileLog; private readonly object syncRoot = new(); private readonly List entries = new(); public event EventHandler? EntryAdded; - public ActivityAuditService(ILogger logger) + public ActivityAuditService(ILogger logger, IEnhancedLoggingService? fileLog = null) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); + this.fileLog = fileLog; } public Task LogInfoAsync(string category, string message, string? details = null) => @@ -66,11 +68,11 @@ public Task ClearDisplayAsync() return Task.CompletedTask; } - private Task AddEntryAsync(string category, ActivityAuditSeverity severity, string message, string? details) + private async Task AddEntryAsync(string category, ActivityAuditSeverity severity, string message, string? details) { if (string.IsNullOrWhiteSpace(message)) { - return Task.CompletedTask; + return; } var entry = new ActivityAuditEntry @@ -98,7 +100,22 @@ private Task AddEntryAsync(string category, ActivityAuditSeverity severity, stri entry.Severity, entry.Message); this.EntryAdded?.Invoke(this, entry); - return Task.CompletedTask; + + // The Activity page keeps only this run in memory; the log file is what survives a restart or a bug report. + if (this.fileLog != null) + { + try + { + await this.fileLog.LogSystemEventAsync( + $"ActivityAudit/{entry.Category}", + entry.Details == null ? $"{entry.Category}: {entry.Message}" : $"{entry.Category}: {entry.Message} ({entry.Details})", + ToLogLevel(severity)).ConfigureAwait(false); + } + catch (Exception ex) + { + this.logger.LogDebug(ex, "Could not copy an activity entry to the log file"); + } + } } private static LogLevel ToLogLevel(ActivityAuditSeverity severity) => diff --git a/Services/CpuSelectionMigrationService.cs b/Services/CpuSelectionMigrationService.cs index afcdbba..31ba366 100644 --- a/Services/CpuSelectionMigrationService.cs +++ b/Services/CpuSelectionMigrationService.cs @@ -80,7 +80,7 @@ public bool ShouldRequireReview( // of those would train the user to ignore the warning. What actually changes the // meaning of "core 9" is a different chip or a different shape of one. if (savedSignature != null && - (!string.Equals(savedSignature.CpuBrand, currentTopology.Signature.CpuBrand, StringComparison.OrdinalIgnoreCase) || + (IsDifferentKnownBrand(savedSignature.CpuBrand, currentTopology.Signature.CpuBrand) || savedSignature.LogicalProcessorCount != currentTopology.Signature.LogicalProcessorCount || savedSignature.PhysicalCoreCount != currentTopology.Signature.PhysicalCoreCount || savedSignature.ProcessorGroupCount != currentTopology.Signature.ProcessorGroupCount)) @@ -92,6 +92,15 @@ public bool ShouldRequireReview( return selection.LogicalProcessors.Any(processor => !currentProcessors.Contains(processor)); } + // The topology provider does not fill in the brand ("Unknown"), so a brand only counts when both sides + // have one; otherwise any rule written with a brand (a hand-edited file, an import) was flagged on the + // very CPU it was made for. Core counts and the processor list still catch a real CPU change. + private static bool IsDifferentKnownBrand(string? saved, string? current) => + IsKnownBrand(saved) && IsKnownBrand(current) && !string.Equals(saved, current, StringComparison.OrdinalIgnoreCase); + + private static bool IsKnownBrand(string? brand) => + !string.IsNullOrWhiteSpace(brand) && !string.Equals(brand, "Unknown", StringComparison.OrdinalIgnoreCase); + public ProcessProfileSnapshot MigrateProcessProfile( ProcessProfileSnapshot profile, CpuTopologySnapshot topology) diff --git a/Services/GameModeService.cs b/Services/GameModeService.cs index 229e8f4..79a9e47 100644 --- a/Services/GameModeService.cs +++ b/Services/GameModeService.cs @@ -1,80 +1,92 @@ -namespace ThreadPilot.Services -{ - using System; - using System.Threading.Tasks; - using Microsoft.Extensions.Logging; - using Microsoft.Win32; - - public class GameModeService : IGameModeService - { - private readonly ILogger logger; - private const string GameBarKeyPath = @"Software\Microsoft\GameBar"; - private const string GameModeValueName = "AutoGameModeEnabled"; - - public GameModeService(ILogger logger) - { - this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } - - public async Task IsGameModeEnabledAsync() - { - await Task.CompletedTask; // Make async for consistency - - try - { - using var key = Registry.CurrentUser.OpenSubKey(GameBarKeyPath, writable: false); - if (key == null) - { - this.logger.LogDebug("GameBar registry key not found, assuming Game Mode is disabled"); - return false; - } - - var value = key.GetValue(GameModeValueName); - if (value is int intValue) - { - bool isEnabled = intValue != 0; - this.logger.LogDebug("Game Mode status: {Status}", isEnabled ? "Enabled" : "Disabled"); - return isEnabled; - } - - this.logger.LogDebug("GameMode value not found, assuming disabled"); - return false; - } - catch (Exception ex) - { - this.logger.LogWarning(ex, "Failed to read Game Mode registry key, assuming disabled"); - return false; - } - } - - public async Task SetGameModeAsync(bool enabled) - { - await Task.CompletedTask; // Make async for consistency - - try - { - using var key = Registry.CurrentUser.CreateSubKey(GameBarKeyPath, writable: true); - if (key == null) - { - this.logger.LogWarning("GameBar registry key not found, cannot modify Game Mode"); - return false; - } - - key.SetValue(GameModeValueName, enabled ? 1 : 0, RegistryValueKind.DWord); - this.logger.LogInformation("Set Windows Game Mode to {State}", enabled ? "enabled" : "disabled"); - return true; - } - catch (UnauthorizedAccessException ex) - { - this.logger.LogWarning(ex, "Insufficient permissions to modify Game Mode registry key"); - return false; - } - catch (Exception ex) - { - this.logger.LogError(ex, "Failed to set Game Mode to {State}", enabled ? "enabled" : "disabled"); - return false; - } - } - } -} - +namespace ThreadPilot.Services +{ + using System; + using System.Threading.Tasks; + using Microsoft.Extensions.Logging; + using Microsoft.Win32; + + public class GameModeService : IGameModeService + { + private const string DefaultGameBarKeyPath = @"Software\Microsoft\GameBar"; + private const string GameModeValueName = "AutoGameModeEnabled"; + private readonly ILogger logger; + private readonly string gameBarKeyPath; + + public GameModeService(ILogger logger) + : this(logger, DefaultGameBarKeyPath) + { + } + + // Tests point this at a scratch key under HKCU so the real Game Bar settings are never touched. + internal GameModeService(ILogger logger, string gameBarKeyPath) + { + this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); + this.gameBarKeyPath = string.IsNullOrWhiteSpace(gameBarKeyPath) + ? throw new ArgumentException("A registry key path is required.", nameof(gameBarKeyPath)) + : gameBarKeyPath; + } + + public async Task IsGameModeEnabledAsync() + { + await Task.CompletedTask; // Make async for consistency + + try + { + using var key = Registry.CurrentUser.OpenSubKey(this.gameBarKeyPath, writable: false); + var value = key?.GetValue(GameModeValueName); + var isEnabled = IsEnabledFromRegistryValue(value); + this.logger.LogDebug( + "Game Mode status: {Status} ({Source})", + isEnabled ? "Enabled" : "Disabled", + value == null ? "value not set, Windows default" : "registry value"); + return isEnabled; + } + catch (Exception ex) + { + // Unreadable is not the same as off: report the Windows default rather than a false "disabled". + this.logger.LogWarning(ex, "Failed to read Game Mode registry key, assuming the Windows default (enabled)"); + return true; + } + } + + public async Task SetGameModeAsync(bool enabled) + { + await Task.CompletedTask; // Make async for consistency + + try + { + using var key = Registry.CurrentUser.CreateSubKey(this.gameBarKeyPath, writable: true); + if (key == null) + { + this.logger.LogWarning("GameBar registry key not found, cannot modify Game Mode"); + return false; + } + + key.SetValue(GameModeValueName, enabled ? 1 : 0, RegistryValueKind.DWord); + this.logger.LogInformation("Set Windows Game Mode to {State}", enabled ? "enabled" : "disabled"); + return true; + } + catch (UnauthorizedAccessException ex) + { + this.logger.LogWarning(ex, "Insufficient permissions to modify Game Mode registry key"); + return false; + } + catch (Exception ex) + { + this.logger.LogError(ex, "Failed to set Game Mode to {State}", enabled ? "enabled" : "disabled"); + return false; + } + } + + /// + /// Windows 10 1703+ and Windows 11 turn Game Mode on by default and only write AutoGameModeEnabled + /// once the user changes the switch, so a missing key or value means "on"; only an explicit 0 means "off". + /// + internal static bool IsEnabledFromRegistryValue(object? value) => value switch + { + int dword => dword != 0, + long qword => qword != 0, + _ => true, + }; + } +} diff --git a/Services/GameSessionService.cs b/Services/GameSessionService.cs index 731a8b6..b281e3a 100644 --- a/Services/GameSessionService.cs +++ b/Services/GameSessionService.cs @@ -190,6 +190,9 @@ public interface IGameSessionService : IDisposable Task GetDecisionAsync(); + /// True while Game Boost owns the default CPU Sets of this process (confirmed in its journal). + bool HasAppliedCpuSets(int processId); + /// Undoes what a previous run left behind (crash), then starts watching for games. Task StartAsync(); @@ -235,6 +238,9 @@ public sealed class GameSessionService : IGameSessionService private readonly object timerGate = new(); private List journal = new(); + + // Read by the UI thread without the state lock: replaced, never mutated, on every journal save. + private volatile HashSet cpuSetProcessIds = new HashSet(); private volatile JournalRecoveryState startupRecovery; private Timer? timer; private bool started; @@ -242,6 +248,10 @@ public sealed class GameSessionService : IGameSessionService // Set by StopAsync: a tick already queued when the timer was disposed must not begin a session. private bool stopped; private (int ProcessId, long StartTicks, long Timestamp)? rejectedForeground; + + // Foreground processes already reported as unreadable, so the Activity page gets one line each, not one per tick. + private readonly HashSet<(int ProcessId, long StartTicks)> reportedUnreadableForeground = new(); + private string? lastTickFailure; private GameSession? session; private IGameProcessHandle? gameHandle; private GameBoostDecision? cachedDecision; @@ -291,6 +301,8 @@ public GameSessionService( public string? ActiveGameName => this.session?.Game.Name; + public bool HasAppliedCpuSets(int processId) => this.cpuSetProcessIds.Contains(processId); + private ApplicationSettingsModel Settings => this.settingsService.Settings; public async Task GetDecisionAsync() @@ -394,7 +406,7 @@ private void SyncTimer() if (this.started && !this.disposed && (this.Settings.GameBoostEnabled || this.startupRecovery != JournalRecoveryState.Complete)) { - this.timer ??= new Timer(_ => TaskSafety.FireAndForget(this.TickAsync(), ex => this.logger.LogWarning(ex, "Game Boost tick failed")), null, TickInterval, TickInterval); + this.timer ??= new Timer(_ => TaskSafety.FireAndForget(this.RunTickAsync(), this.OnTickFailed), null, TickInterval, TickInterval); return; } @@ -494,6 +506,14 @@ private async Task TryBeginSessionAsync() { this.rejectedForeground = (processId, foregroundStartTicks, this.timeProvider.GetTimestamp()); } + else if (this.reportedUnreadableForeground.Add((processId, foregroundStartTicks))) + { + // Without a path the library check cannot match: say so once, or a protected game looks ignored for no reason. + await this.AuditAsync( + ActivityAuditSeverity.Info, + $"{game.Name}: not recognized as a game, its executable path cannot be read", + "Protected or anti-cheat processes can hide it; add the name to Game Boost's manual game list").ConfigureAwait(false); + } return; } @@ -510,6 +530,24 @@ private async Task TryBeginSessionAsync() await this.ApplyToSessionAsync(includeGame: true).ConfigureAwait(false); } + // A tick that completes clears the failure memory, so an error that comes back after a recovery is reported again. + internal async Task RunTickAsync() + { + await this.TickAsync().ConfigureAwait(false); + this.lastTickFailure = null; + } + + // A failing tick repeats every 3 s: Activity (and the log file) get each new error once, not every tick. + internal void OnTickFailed(Exception ex) + { + this.logger.LogWarning(ex, "Game Boost tick failed"); + if (ex.Message != this.lastTickFailure) + { + this.lastTickFailure = ex.Message; + _ = this.AuditAsync(ActivityAuditSeverity.Warning, "Game Boost check failed", ex.Message); + } + } + private async Task AuditSessionStartAsync(ProcessModel game) { var decision = await this.GetDecisionAsync().ConfigureAwait(false); @@ -904,7 +942,7 @@ private bool IsBackgroundCandidate(ProcessModel process, GameSession currentSess if (!result.Success) { this.logger.LogInformation("Game Boost could not set efficiency mode {Mode} on {ProcessName} (PID {ProcessId})", mode, process.Name, process.ProcessId); - return (ApplyOutcome.Failed, "efficiency mode not applied"); + return (ApplyOutcome.Failed, string.IsNullOrWhiteSpace(result.UserMessage) ? "efficiency mode not applied" : result.UserMessage.TrimEnd('.')); } await this.ConfirmJournalEntryAsync(entry).ConfigureAwait(false); @@ -1284,6 +1322,10 @@ await this.AuditAsync( private async Task SaveJournalAsync() { + this.cpuSetProcessIds = this.journal + .Where(entry => entry.Setting == GameBoostSetting.CpuSets && entry.Confirmed) + .Select(entry => entry.ProcessId) + .ToHashSet(); try { if (this.journal.Count == 0) diff --git a/Services/PersistentRulePriorityVerificationService.cs b/Services/PersistentRulePriorityVerificationService.cs index a6e686e..72ebac5 100644 --- a/Services/PersistentRulePriorityVerificationService.cs +++ b/Services/PersistentRulePriorityVerificationService.cs @@ -17,6 +17,10 @@ public sealed class PersistentRulePriorityVerificationService : IPersistentRuleP private static readonly TimeSpan[] DefaultDelays = [TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3)]; private static readonly TimeSpan DefaultRetryDelay = TimeSpan.FromSeconds(4); // ponytail: one conservative startup-settling retry; no polling. + // Some games reset their own priority once they finish starting, well after the early checks (Assetto Corsa + // Competizione went back to Normal within ~66 s once). One more look, sharing the single retry; still no polling. + private static readonly TimeSpan DefaultLateDelay = TimeSpan.FromSeconds(90); + private readonly IProcessService processService; private readonly ILogger logger; private readonly IActivityAuditService? activityAuditService; @@ -24,6 +28,7 @@ public sealed class PersistentRulePriorityVerificationService : IPersistentRuleP private readonly IPersistentProcessRuleMatcher? matcher; private readonly IReadOnlyList delays; private readonly TimeSpan retryDelay; + private readonly TimeSpan? lateDelay; private readonly Func delayAsync; private readonly ConcurrentDictionary retryUsed = new(); private readonly ConcurrentDictionary pendingRetries = new(); @@ -34,7 +39,7 @@ public PersistentRulePriorityVerificationService( IActivityAuditService? activityAuditService = null, IPersistentProcessRuleStore? ruleStore = null, IPersistentProcessRuleMatcher? matcher = null) - : this(processService, logger, activityAuditService, ruleStore, matcher, DefaultDelays, DefaultRetryDelay, Task.Delay) + : this(processService, logger, activityAuditService, ruleStore, matcher, DefaultDelays, DefaultRetryDelay, Task.Delay, DefaultLateDelay) { } @@ -56,7 +61,8 @@ public PersistentRulePriorityVerificationService( IPersistentProcessRuleMatcher? matcher, IReadOnlyList delays, TimeSpan retryDelay, - Func delayAsync) + Func delayAsync, + TimeSpan? lateDelay = null) { this.processService = processService ?? throw new ArgumentNullException(nameof(processService)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); @@ -66,6 +72,7 @@ public PersistentRulePriorityVerificationService( this.delays = delays?.Take(2).ToArray() ?? DefaultDelays; this.retryDelay = retryDelay < TimeSpan.Zero ? DefaultRetryDelay : retryDelay; this.delayAsync = delayAsync ?? Task.Delay; + this.lateDelay = lateDelay > TimeSpan.Zero ? lateDelay : null; } public void ScheduleDelayedVerification(PersistentRuleAutoApplyResult result, ProcessModel process, string source) @@ -158,6 +165,42 @@ await this.LogActivityAsync( return; } } + + await this.VerifyLateAsync(result, process, source, requested, cancellationToken).ConfigureAwait(false); + } + + // The early checks passed. A process that exits before this is simply gone, not a failed check, so it is skipped quietly. + private async Task VerifyLateAsync(PersistentRuleAutoApplyResult result, ProcessModel process, string source, ProcessPriorityClass requested, CancellationToken cancellationToken) + { + if (this.lateDelay is not TimeSpan delay) + { + return; + } + + const string phase = "late"; + try + { + await this.delayAsync(delay, cancellationToken).ConfigureAwait(false); + if (!await this.processService.IsProcessStillRunning(process).ConfigureAwait(false)) + { + return; + } + + await this.processService.RefreshProcessInfo(process).ConfigureAwait(false); + var observed = process.Priority; + if (observed == requested) + { + await this.LogVerifiedAsync(result, process, source, phase, requested, observed, attempt: 0).ConfigureAwait(false); + return; + } + + await this.LogRevertedAsync(result, process, source, phase, requested, observed).ConfigureAwait(false); + await this.ScheduleRetryAsync(result, process, source, requested, observed).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + this.logger.LogDebug(ex, "Late priority verification skipped for {ProcessName} (PID: {ProcessId})", result.ProcessName, result.ProcessId); + } } private async Task ScheduleRetryAsync(PersistentRuleAutoApplyResult result, ProcessModel process, string source, ProcessPriorityClass requested, ProcessPriorityClass observed) diff --git a/Services/ProcessMemoryPriorityService.cs b/Services/ProcessMemoryPriorityService.cs index 38371ce..bdaf6d3 100644 --- a/Services/ProcessMemoryPriorityService.cs +++ b/Services/ProcessMemoryPriorityService.cs @@ -135,7 +135,8 @@ public Task SetMemoryPriorityAsync(ProcessModel process, MemoryPriorityInformationSize)) { return Task.FromResult(this.FromLastError( - "SetProcessInformation(ProcessMemoryPriority) failed.")); + "SetProcessInformation(ProcessMemoryPriority) failed.", + handleOpened: true)); } return Task.FromResult(ProcessOperationResult.Succeeded( @@ -386,7 +387,7 @@ public Task SetEfficiencyModeAsync(ProcessModel process, state.StateMask = mode == ProcessEfficiencyMode.On ? state.StateMask | speed : state.StateMask & ~speed; if (!this.nativeApi.SetPowerThrottling(handle, ref state)) { - return Task.FromResult(this.FromLastError("SetProcessInformation(ProcessPowerThrottling) failed.", FailureMessage)); + return Task.FromResult(this.FromLastError("SetProcessInformation(ProcessPowerThrottling) failed.", FailureMessage, handleOpened: true)); } return Task.FromResult(ProcessOperationResult.Succeeded( @@ -450,15 +451,23 @@ private static ProcessOperationResult Unsupported(string technicalMessage) => UnsupportedUserMessage, technicalMessage); + // handleOpened: the handle was granted and the call made with it was refused; see ProcessCpuSetHandler. private ProcessOperationResult FromLastError( string context, - string failureMessage = "ThreadPilot could not apply the memory priority change.") + string failureMessage = "ThreadPilot could not apply the memory priority change.", + bool handleOpened = false) { var error = this.nativeApi.GetLastWin32Error(); var technicalMessage = $"{context} Win32 error {error}."; return error switch { + 5 when handleOpened => ProcessOperationResult.Failed( + AffinityApplyErrorCodes.AntiCheatOrProtectedProcessLikely, + ProcessOperationUserMessages.AntiCheatProtectedLikely, + technicalMessage, + isAccessDenied: true, + isAntiCheatLikely: true), 5 => ProcessOperationResult.Failed( AffinityApplyErrorCodes.AccessDenied, ProcessOperationUserMessages.AccessDenied, diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index 660c30b..a3fe2aa 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -117,6 +117,7 @@ public async Task> GetProcessesAsync() private List EnumerateProcessModels(Func? filter = null, Func? nameFilter = null) { var foregroundProcessId = this.foregroundProcessService?.TryGetForegroundProcessId(); + var mainWindows = MainWindowSnapshot.Capture(); var models = new List(); foreach (var process in Process.GetProcesses()) { @@ -128,7 +129,7 @@ private List EnumerateProcessModels(Func? filt continue; } - var model = this.TryCreateProcessModel(process, foregroundProcessId); + var model = this.TryCreateProcessModel(process, foregroundProcessId, mainWindows); if (model != null && (filter == null || filter(model))) { models.Add(model); @@ -207,11 +208,11 @@ public ProcessModel CreateProcessModel(Process process) return this.CreateProcessModel(process, this.foregroundProcessService?.TryGetForegroundProcessId()); } - private ProcessModel? TryCreateProcessModel(Process process, int? foregroundProcessId) + private ProcessModel? TryCreateProcessModel(Process process, int? foregroundProcessId, IReadOnlyDictionary? mainWindows = null) { try { - return this.CreateProcessModel(process, foregroundProcessId); + return this.CreateProcessModel(process, foregroundProcessId, mainWindows); } catch (Exception ex) when (IsTerminatedProcessException(ex)) { @@ -246,7 +247,8 @@ public ProcessModel CreateProcessModel(Process process) } } - private ProcessModel CreateProcessModel(Process process, int? foregroundProcessId) + // mainWindows: one EnumWindows pass shared by a whole list refresh; null looks the window up per process. + private ProcessModel CreateProcessModel(Process process, int? foregroundProcessId, IReadOnlyDictionary? mainWindows = null) { var model = new ProcessModel(); var accessDenied = false; @@ -378,8 +380,17 @@ private ProcessModel CreateProcessModel(Process process, int? foregroundProcessI { try { - model.MainWindowHandle = process.MainWindowHandle; - model.MainWindowTitle = process.MainWindowTitle ?? string.Empty; + if (mainWindows == null) + { + model.MainWindowHandle = process.MainWindowHandle; + model.MainWindowTitle = process.MainWindowTitle ?? string.Empty; + } + else + { + model.MainWindowHandle = mainWindows.GetValueOrDefault(model.ProcessId); + model.MainWindowTitle = model.MainWindowHandle == 0 ? string.Empty : MainWindowSnapshot.GetTitle(model.MainWindowHandle); + } + model.HasVisibleWindow = model.MainWindowHandle != IntPtr.Zero && !string.IsNullOrWhiteSpace(model.MainWindowTitle); } catch (Exception ex) when (IsTerminatedProcessException(ex)) @@ -400,7 +411,7 @@ private ProcessModel CreateProcessModel(Process process, int? foregroundProcessI { try { - model.ExecutablePath = process.MainModule?.FileName ?? string.Empty; + model.ExecutablePath = ProcessImagePath.TryGet(model.ProcessId) ?? process.MainModule?.FileName ?? string.Empty; if (startTimeUtc.HasValue && !string.IsNullOrWhiteSpace(model.ExecutablePath)) { this.processMetadata[model.ProcessId] = new ProcessMetadata(startTimeUtc.Value, model.ExecutablePath); @@ -795,7 +806,7 @@ await Task.Run(() => process.HasVisibleWindow = process.MainWindowHandle != IntPtr.Zero && !string.IsNullOrWhiteSpace(process.MainWindowTitle); if (string.IsNullOrWhiteSpace(process.ExecutablePath)) { - process.ExecutablePath = p.MainModule?.FileName ?? string.Empty; + process.ExecutablePath = ProcessImagePath.TryGet(p.Id) ?? p.MainModule?.FileName ?? string.Empty; } this.ApplyProcessClassification( diff --git a/Tests/ThreadPilot.Core.Tests/ActivityAuditServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ActivityAuditServiceTests.cs index 006b88f..fc39a83 100644 --- a/Tests/ThreadPilot.Core.Tests/ActivityAuditServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ActivityAuditServiceTests.cs @@ -1,6 +1,8 @@ namespace ThreadPilot.Core.Tests { + using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; + using Moq; using ThreadPilot.Services; public sealed class ActivityAuditServiceTests @@ -22,8 +24,8 @@ public sealed class ActivityAuditServiceTests [InlineData("CpuSetsCleared", "CPU Sets cleared for Game.exe", "Affinity", ActivityAuditSeverity.Success)] [InlineData("CpuSetsClearFailed", "The process exited before ThreadPilot could apply the change.", "Affinity", ActivityAuditSeverity.Error)] [InlineData("ProcessAffinityApplied", "Affinity applied successfully to Game.exe", "Affinity", ActivityAuditSeverity.Success)] - [InlineData("ProcessAffinityFailed", "The process appears protected by anti-cheat or process protection.", "Affinity", ActivityAuditSeverity.Warning)] - [InlineData("ProcessCpuAssignmentApplied", "CPU assignment applied with IdealProcessor", "Affinity", ActivityAuditSeverity.Success)] + [InlineData("ProcessAffinityFailed", "The process appears protected by anti-cheat or process protection.", "Affinity", ActivityAuditSeverity.Warning)] + [InlineData("ProcessCpuAssignmentApplied", "CPU assignment applied with IdealProcessor", "Affinity", ActivityAuditSeverity.Success)] [InlineData("PersistentRuleSaved", "Saved rule for Game.exe.", "Rules", ActivityAuditSeverity.Success)] [InlineData("PersistentRuleSaveFailed", "Failed to save rule for Game.exe.", "Rules", ActivityAuditSeverity.Error)] [InlineData("PersistentRuleAutoApplied", "Auto-applied saved rule for Game.exe.", "Rules", ActivityAuditSeverity.Success)] @@ -62,5 +64,45 @@ public async Task GetEntriesAsync_ReturnsMostRecentFirstAndPreservesTimestamp() entry => Assert.Equal("First", entry.Message)); Assert.All(entries, entry => Assert.NotEqual(default, entry.Timestamp)); } + + [Theory] + [InlineData(ActivityAuditSeverity.Info, LogLevel.Information)] + [InlineData(ActivityAuditSeverity.Success, LogLevel.Information)] + [InlineData(ActivityAuditSeverity.Warning, LogLevel.Warning)] + [InlineData(ActivityAuditSeverity.Error, LogLevel.Error)] + public async Task EveryEntry_IsAlsoWrittenToTheLogFile(ActivityAuditSeverity severity, LogLevel expectedLevel) + { + var fileLog = new Mock(); + var service = new ActivityAuditService(NullLogger.Instance, fileLog.Object); + + var log = severity switch + { + ActivityAuditSeverity.Success => service.LogSuccessAsync("Game Boost", "Session started: Game (Automatic)", "Intel hybrid"), + ActivityAuditSeverity.Warning => service.LogWarningAsync("Game Boost", "Session started: Game (Automatic)", "Intel hybrid"), + ActivityAuditSeverity.Error => service.LogErrorAsync("Game Boost", "Session started: Game (Automatic)", "Intel hybrid"), + _ => service.LogInfoAsync("Game Boost", "Session started: Game (Automatic)", "Intel hybrid"), + }; + await log; + + fileLog.Verify( + file => file.LogSystemEventAsync( + "ActivityAudit/Game Boost", + "Game Boost: Session started: Game (Automatic) (Intel hybrid)", + expectedLevel), + Times.Once); + } + + [Fact] + public async Task FileLogFailure_DoesNotLoseTheActivityEntry() + { + var fileLog = new Mock(); + fileLog.Setup(file => file.LogSystemEventAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ThrowsAsync(new IOException("disk full")); + var service = new ActivityAuditService(NullLogger.Instance, fileLog.Object); + + await service.LogInfoAsync("Game Boost", "Session ended for Game: the game exited"); + + Assert.Single(await service.GetEntriesAsync()); + } } } diff --git a/Tests/ThreadPilot.Core.Tests/CpuSelectionMigrationServiceTests.cs b/Tests/ThreadPilot.Core.Tests/CpuSelectionMigrationServiceTests.cs index 4df5161..394a8d0 100644 --- a/Tests/ThreadPilot.Core.Tests/CpuSelectionMigrationServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/CpuSelectionMigrationServiceTests.cs @@ -29,6 +29,44 @@ public void MigrateFromLegacyAffinityMask_WithSingleGroupBelow64_SelectsExpected Assert.Equal(0b0101, service.BuildLegacyAffinityMaskIfRepresentable(result.Selection)); } + [Theory] + [InlineData("GenuineIntel 12th Gen Intel(R) Core(TM) i9-12900K", false)] + [InlineData("Unknown", false)] + [InlineData("", false)] + public void ShouldRequireReview_BrandOnlyCountsWhenBothSidesKnowIt(string savedBrand, bool expected) + { + // The topology provider leaves the brand "Unknown"; a rule written with a brand on the same CPU was flagged. + var topology = CreateTopology(8, cpuBrand: "Unknown"); + var service = new CpuSelectionMigrationService(); + var selection = service.MigrateFromLegacyAffinityMask(0b11, topology).Selection; + + var saved = topology.Signature with { CpuBrand = savedBrand }; + + Assert.Equal(expected, service.ShouldRequireReview(selection, saved, topology)); + } + + [Fact] + public void ShouldRequireReview_TwoKnownDifferentBrands_StillFlagged() + { + var topology = CreateTopology(8); + var service = new CpuSelectionMigrationService(); + var selection = service.MigrateFromLegacyAffinityMask(0b11, topology).Selection; + + Assert.True(service.ShouldRequireReview(selection, topology.Signature with { CpuBrand = "Another CPU" }, topology)); + } + + [Fact] + public void ShouldRequireReview_DifferentCpuShape_StillFlagged() + { + var topology = CreateTopology(8); + var service = new CpuSelectionMigrationService(); + var selection = service.MigrateFromLegacyAffinityMask(0b11, topology).Selection; + + var saved = topology.Signature with { CpuBrand = "Some Other CPU", LogicalProcessorCount = 16 }; + + Assert.True(service.ShouldRequireReview(selection, saved, topology)); + } + [Fact] public void MigrateFromLegacyAffinityMask_OnTopologyAbove64_DoesNotAliasCpu64ToCpu0() { @@ -240,7 +278,7 @@ public void CoreMaskWithCpuSelection_DeserializesAsVersionTwo() Assert.Equal([false, true], deserialized.BoolMask.ToArray()); } - private static CpuTopologySnapshot CreateTopology(int processorCount) + private static CpuTopologySnapshot CreateTopology(int processorCount, string cpuBrand = "Synthetic CPU") { var processors = Enumerable .Range(0, processorCount) @@ -251,7 +289,7 @@ private static CpuTopologySnapshot CreateTopology(int processorCount) processors, signature: new CpuTopologySignature { - CpuBrand = "Synthetic CPU", + CpuBrand = cpuBrand, LogicalProcessorCount = processorCount, PhysicalCoreCount = processorCount, ProcessorGroupCount = Math.Max(1, (processorCount + 63) / 64), diff --git a/Tests/ThreadPilot.Core.Tests/GameBoostIntelHybridTests.cs b/Tests/ThreadPilot.Core.Tests/GameBoostIntelHybridTests.cs new file mode 100644 index 0000000..cf36ae0 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/GameBoostIntelHybridTests.cs @@ -0,0 +1,113 @@ +namespace ThreadPilot.Core.Tests +{ + using ThreadPilot.Models; + using ThreadPilot.Services; + + /// + /// Intel hybrid generations. The i9-12900K case is the CPU Set table read from a real 12900K + /// (docs/validation/intel-hybrid-12900k.md); the others are synthetic and only show what the policy decides. + /// + public sealed class GameBoostIntelHybridTests + { + // (CPU Set ID, logical processor, CoreIndex, L3 index, EfficiencyClass) as GetSystemCpuSetInformation reported them. + private static readonly (uint Id, int Lp, int Core, int L3, byte Class)[] CoreI9With12900KCpuSets = + [ + (256, 0, 0, 0, 1), (257, 1, 0, 0, 1), (258, 2, 2, 0, 1), (259, 3, 2, 0, 1), + (260, 4, 4, 0, 1), (261, 5, 4, 0, 1), (262, 6, 6, 0, 1), (263, 7, 6, 0, 1), + (264, 8, 8, 0, 1), (265, 9, 8, 0, 1), (266, 10, 10, 0, 1), (267, 11, 10, 0, 1), + (268, 12, 12, 0, 1), (269, 13, 12, 0, 1), (270, 14, 14, 0, 1), (271, 15, 14, 0, 1), + (272, 16, 16, 0, 0), (273, 17, 17, 0, 0), (274, 18, 18, 0, 0), (275, 19, 19, 0, 0), + (276, 20, 20, 0, 0), (277, 21, 21, 0, 0), (278, 22, 22, 0, 0), (279, 23, 23, 0, 0), + ]; + + [Theory] + [InlineData(GameBoostMode.Automatic)] + [InlineData(GameBoostMode.Isolation)] + public void RealCoreI9With12900KCpuSets_GameOnTheSixteenPCoreThreads_BackgroundOnTheEightECores(GameBoostMode mode) + { + var decision = GameBoostPolicy.Decide(FromCpuSets(CoreI9With12900KCpuSets), "12th Gen Intel(R) Core(TM) i9-12900K", mode); + + Assert.Equal(GameBoostTopologyKind.IntelHybrid, decision.Kind); + Assert.Equal(Enumerable.Range(0, 16), decision.GameSelection!.GlobalLogicalProcessorIndexes); + Assert.Equal(Enumerable.Range(256, 16).Select(id => (uint)id), decision.GameSelection.CpuSetIds); + Assert.Equal(Enumerable.Range(16, 8), decision.BackgroundSelection!.GlobalLogicalProcessorIndexes); + Assert.Equal(Enumerable.Range(272, 8).Select(id => (uint)id), decision.BackgroundSelection.CpuSetIds); + } + + [Theory] + [InlineData("13th Gen Intel(R) Core(TM) i9-13900K", 8, 16)] + [InlineData("14th Gen Intel(R) Core(TM) i9-14900K", 8, 16)] + [InlineData("14th Gen Intel(R) Core(TM) i7-14700K", 8, 12)] + [InlineData("13th Gen Intel(R) Core(TM) i7-13700K", 8, 8)] + [InlineData("12th Gen Intel(R) Core(TM) i5-12600K", 6, 4)] + [InlineData("13th Gen Intel(R) Core(TM) i5-13600K", 6, 8)] + public void DesktopHybrid_GameOnPThreads_BackgroundOnECores(string brand, int performanceCores, int efficiencyCores) + { + var decision = GameBoostPolicy.Decide(TopologyFixtures.IntelHybrid(performanceCores, efficiencyCores), brand, GameBoostMode.Automatic); + + Assert.Equal(GameBoostTopologyKind.IntelHybrid, decision.Kind); + Assert.Equal(Enumerable.Range(0, performanceCores * 2), decision.GameSelection!.GlobalLogicalProcessorIndexes); + Assert.Equal(Enumerable.Range(performanceCores * 2, efficiencyCores), decision.BackgroundSelection!.GlobalLogicalProcessorIndexes); + } + + [Fact] + public void I5_12400_SixPCoresNoECores_DoesNothing() + { + var topology = TopologyFixtures.IntelHybrid(performanceCores: 6, efficiencyCores: 0); + + Assert.Equal(GameBoostDecision.None, GameBoostPolicy.Decide(topology, "12th Gen Intel(R) Core(TM) i5-12400", GameBoostMode.Isolation)); + } + + [Fact] + public void CoreUltraWithoutSmt_ThreeEfficiencyClasses_LowPowerECoresAreTreatedAsECores() + { + // Synthetic Core Ultra layout: 6 P-cores (class 2), 8 E-cores (class 1), 2 LP E-cores (class 0), no SMT. + var cpuSets = Enumerable.Range(0, 16) + .Select(lp => ((uint)(256 + lp), lp, lp, lp < 14 ? 0 : 1, (byte)(lp < 6 ? 2 : lp < 14 ? 1 : 0))) + .ToArray(); + + var decision = GameBoostPolicy.Decide(FromCpuSets(cpuSets), "Intel(R) Core(TM) Ultra 7 155H", GameBoostMode.Automatic); + + Assert.Equal(GameBoostTopologyKind.IntelHybrid, decision.Kind); + Assert.Equal(Enumerable.Range(0, 6), decision.GameSelection!.GlobalLogicalProcessorIndexes); + + // Only the top class is "P": E-cores and the slower LP E-cores end up in the same background set. + Assert.Equal(Enumerable.Range(6, 10), decision.BackgroundSelection!.GlobalLogicalProcessorIndexes); + } + + [Fact] + public void CoreUltra200S_EightPCoresWithoutSmt_GameGetsEightCpus() + { + // Arrow Lake desktop: 8 P-cores and 16 E-cores, no Hyper-Threading. + var cpuSets = Enumerable.Range(0, 24) + .Select(lp => ((uint)(256 + lp), lp, lp, 0, (byte)(lp < 8 ? 1 : 0))) + .ToArray(); + + var decision = GameBoostPolicy.Decide(FromCpuSets(cpuSets), "Intel(R) Core(TM) Ultra 9 285K", GameBoostMode.Automatic); + + Assert.Equal(Enumerable.Range(0, 8), decision.GameSelection!.GlobalLogicalProcessorIndexes); + Assert.Equal(Enumerable.Range(8, 16), decision.BackgroundSelection!.GlobalLogicalProcessorIndexes); + } + + [Fact] + public void LunarLakeFourPCores_TooSmallForTheGame_DoesNothing() + { + var cpuSets = Enumerable.Range(0, 8) + .Select(lp => ((uint)(256 + lp), lp, lp, lp < 4 ? 0 : 1, (byte)(lp < 4 ? 1 : 0))) + .ToArray(); + + Assert.Equal(GameBoostDecision.None, GameBoostPolicy.Decide(FromCpuSets(cpuSets), "Intel(R) Core(TM) Ultra 7 258V", GameBoostMode.Automatic)); + } + + private static CpuTopologySnapshot FromCpuSets((uint Id, int Lp, int Core, int L3, byte Class)[] cpuSets) + { + var processors = cpuSets.Select(set => new ProcessorRef(0, (byte)set.Lp, set.Lp)).ToList(); + return CpuTopologySnapshot.Create( + processors, + cpuSetIds: cpuSets.ToDictionary(set => processors[set.Lp], set => set.Id), + efficiencyClasses: cpuSets.ToDictionary(set => processors[set.Lp], set => set.Class), + coreIndexes: cpuSets.ToDictionary(set => processors[set.Lp], set => set.Core), + lastLevelCacheIndexes: cpuSets.ToDictionary(set => processors[set.Lp], set => set.L3)); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/GameModeServiceTests.cs b/Tests/ThreadPilot.Core.Tests/GameModeServiceTests.cs new file mode 100644 index 0000000..f120d19 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/GameModeServiceTests.cs @@ -0,0 +1,78 @@ +namespace ThreadPilot.Core.Tests +{ + using Microsoft.Extensions.Logging.Abstractions; + using Microsoft.Win32; + using ThreadPilot.Services; + + /// + /// Runs against a throw-away key under HKCU\Software\ThreadPilot.Tests, never the real Game Bar settings. + /// + public sealed class GameModeServiceTests : IDisposable + { + private const string ValueName = "AutoGameModeEnabled"; + private const string ParentPath = @"Software\ThreadPilot.Tests"; + private readonly string keyPath = $@"{ParentPath}\GameBar-{Guid.NewGuid():N}"; + + public void Dispose() + { + Registry.CurrentUser.DeleteSubKeyTree(this.keyPath, throwOnMissingSubKey: false); + using var parent = Registry.CurrentUser.OpenSubKey(ParentPath); + if (parent != null && parent.SubKeyCount == 0 && parent.ValueCount == 0) + { + parent.Dispose(); + Registry.CurrentUser.DeleteSubKey(ParentPath, throwOnMissingSubKey: false); + } + } + + [Fact] + public async Task MissingKey_IsTheWindowsDefault_Enabled() + { + Assert.True(await this.CreateService().IsGameModeEnabledAsync()); + } + + [Fact] + public async Task KeyWithoutValue_IsTheWindowsDefault_Enabled() + { + Registry.CurrentUser.CreateSubKey(this.keyPath)!.Dispose(); + + Assert.True(await this.CreateService().IsGameModeEnabledAsync()); + } + + [Theory] + [InlineData(0, false)] + [InlineData(1, true)] + public async Task ExplicitValue_IsReadAsIs(int value, bool expected) + { + using (var key = Registry.CurrentUser.CreateSubKey(this.keyPath)!) + { + key.SetValue(ValueName, value, RegistryValueKind.DWord); + } + + Assert.Equal(expected, await this.CreateService().IsGameModeEnabledAsync()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Set_ThenRead_RoundTrips(bool enabled) + { + var service = this.CreateService(); + + Assert.True(await service.SetGameModeAsync(enabled)); + + Assert.Equal(enabled, await service.IsGameModeEnabledAsync()); + using var key = Registry.CurrentUser.OpenSubKey(this.keyPath)!; + Assert.Equal(enabled ? 1 : 0, key.GetValue(ValueName)); + } + + [Fact] + public void UnexpectedValueType_FallsBackToTheWindowsDefault() + { + Assert.True(GameModeService.IsEnabledFromRegistryValue("0")); + Assert.True(GameModeService.IsEnabledFromRegistryValue(null)); + Assert.False(GameModeService.IsEnabledFromRegistryValue(0L)); + } + + private GameModeService CreateService() => new(NullLogger.Instance, this.keyPath); + } +} diff --git a/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs b/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs index 17da5f6..4866dfc 100644 --- a/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs @@ -79,6 +79,50 @@ public async Task RejectedPid_ReusedByAGame_StartsASessionAtTheNextTick() Assert.Equal("Game2", service.ActiveGameName); } + [Fact] + public async Task ForegroundWithUnreadablePath_IsReportedOnce_AndNotTreatedAsAGame() + { + // An anti-cheat or protected process may hide its path: the library check then cannot match it. + this.processes.Add(701, "ProtectedGame", string.Empty); + this.foregroundPid = 701; + using var service = this.CreateService(); + + for (var i = 0; i < 5; i++) + { + await service.TickAsync(); + this.clock.Advance(TimeSpan.FromSeconds(3)); + } + + Assert.Null(service.ActiveGameName); + var entry = Assert.Single(await this.audit.GetEntriesAsync()); + Assert.Equal("ProtectedGame: not recognized as a game, its executable path cannot be read", entry.Message); + } + + [Fact] + public async Task RepeatedTickFailure_IsReportedOnce_AndAgainAfterARecovery() + { + using var service = this.CreateService(); + var error = new InvalidOperationException("boom"); + + service.OnTickFailed(error); + service.OnTickFailed(error); + await this.WaitForAuditCountAsync(1); + + await service.RunTickAsync(); + service.OnTickFailed(error); + await this.WaitForAuditCountAsync(2); + } + + private async Task WaitForAuditCountAsync(int expected) + { + for (var i = 0; i < 100 && (await this.audit.GetEntriesAsync()).Count(e => e.Message == "Game Boost check failed") < expected; i++) + { + await Task.Delay(20); + } + + Assert.Equal(expected, (await this.audit.GetEntriesAsync()).Count(e => e.Message == "Game Boost check failed")); + } + [Fact] public async Task NonGameForeground_IsNotReexaminedEveryTick_ButIsAfterAWhile() { diff --git a/Tests/ThreadPilot.Core.Tests/MainWindowSnapshotTests.cs b/Tests/ThreadPilot.Core.Tests/MainWindowSnapshotTests.cs new file mode 100644 index 0000000..f638e2f --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/MainWindowSnapshotTests.cs @@ -0,0 +1,71 @@ +namespace ThreadPilot.Core.Tests +{ + using System.Diagnostics; + using ThreadPilot.Platforms.Windows; + + public sealed class MainWindowSnapshotTests + { + [Fact] + public void Snapshot_PicksTheSameMainWindowAsProcessMainWindowHandle() + { + // Windows can open or close between the two reads, so allow a stray difference or two. + var snapshot = MainWindowSnapshot.Capture(); + var compared = 0; + var mismatches = 0; + foreach (var process in Process.GetProcesses()) + { + using (process) + { + nint expected; + try + { + expected = process.MainWindowHandle; + } + catch (InvalidOperationException) + { + continue; // exited + } + + compared++; + if (snapshot.GetValueOrDefault(process.Id) != expected) + { + mismatches++; + } + } + } + + Assert.True(compared > 10); + Assert.True(mismatches <= 2, $"{mismatches} of {compared} processes disagreed"); + } + + [Fact] + public void Title_MatchesProcessMainWindowTitle() + { + // Some titles change on their own (terminals, players), so a stray difference is allowed here too. + var mismatches = 0; + foreach (var (processId, window) in MainWindowSnapshot.Capture()) + { + try + { + using var process = Process.GetProcessById(processId); + if (process.MainWindowHandle == window && process.MainWindowTitle != MainWindowSnapshot.GetTitle(window)) + { + mismatches++; + } + } + catch (ArgumentException) + { + // exited + } + } + + Assert.True(mismatches <= 2, $"{mismatches} titles disagreed"); + } + + [Fact] + public void Title_OfNoWindow_IsEmpty() + { + Assert.Equal(string.Empty, MainWindowSnapshot.GetTitle(0)); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/PersistentRulePriorityVerificationServiceTests.cs b/Tests/ThreadPilot.Core.Tests/PersistentRulePriorityVerificationServiceTests.cs index 9af8efb..04df653 100644 --- a/Tests/ThreadPilot.Core.Tests/PersistentRulePriorityVerificationServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/PersistentRulePriorityVerificationServiceTests.cs @@ -24,6 +24,51 @@ public async Task DelayedVerification_PriorityRemainsHigh_RecordsVerifiedState() processService.Verify(x => x.RefreshProcessInfo(It.IsAny()), Times.Exactly(2)); } + [Fact] + public async Task LateVerification_PriorityStillSet_RecordsLateVerifiedState() + { + var audit = new ActivityAuditService(NullLogger.Instance); + var processService = CreateRetryProcessService(ProcessPriorityClass.High); + var service = CreateLateService(processService.Object, audit); + + await service.VerifyDelayedAsync(CreateVerifiedResult(), CreateProcess(), "ProcessStarted"); + + var entries = await audit.GetEntriesAsync(); + Assert.Equal(3, entries.Count); + Assert.Contains(entries, entry => entry.Details?.Contains("Phase: late") == true && entry.Message.Contains("Verified saved priority")); + processService.Verify(x => x.SetProcessPriority(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task LateVerification_GameResetsPriorityAfterStartup_ReappliesItOnce() + { + // Early checks pass, the game later puts itself back to Normal (seen once with Assetto Corsa Competizione). + var audit = new ActivityAuditService(NullLogger.Instance); + var processService = CreateRetryProcessService( + ProcessPriorityClass.High, ProcessPriorityClass.High, ProcessPriorityClass.Normal, ProcessPriorityClass.Normal, ProcessPriorityClass.High, ProcessPriorityClass.High); + var service = CreateLateService(processService.Object, audit); + + await service.VerifyDelayedAsync(CreateVerifiedResult(), CreateProcess(), "ProcessStarted"); + var entries = await WaitForAuditAsync(audit, "PersistentRulePriorityRetryVerified"); + + Assert.Contains(entries, entry => entry.Details?.Contains("PersistentRulePriorityRevertedAfterApply") == true && entry.Details.Contains("Phase: late")); + processService.Verify(x => x.SetProcessPriority(It.IsAny(), ProcessPriorityClass.High, ProcessPriorityWriteSource.PersistentRuleRetry), Times.Once); + } + + [Fact] + public async Task LateVerification_ProcessAlreadyExited_StaysQuiet() + { + var audit = new ActivityAuditService(NullLogger.Instance); + var processService = CreateRetryProcessService(ProcessPriorityClass.High); + processService.Setup(x => x.IsProcessStillRunning(It.IsAny())).ReturnsAsync(false); + var service = CreateLateService(processService.Object, audit); + + await service.VerifyDelayedAsync(CreateVerifiedResult(), CreateProcess(), "ProcessStarted"); + + Assert.Equal(2, (await audit.GetEntriesAsync()).Count); + processService.Verify(x => x.RefreshProcessInfo(It.IsAny()), Times.Exactly(2)); + } + [Fact] public async Task DelayedVerification_PriorityRevertsToNormal_RecordsReversion() { @@ -196,6 +241,18 @@ private static PersistentRulePriorityVerificationService CreateRetryService( TimeSpan.Zero, delayAsync ?? ((_, _) => Task.CompletedTask)); + private static PersistentRulePriorityVerificationService CreateLateService(IProcessService processService, IActivityAuditService audit) => + new( + processService, + NullLogger.Instance, + audit, + new FakePersistentProcessRuleStore([CreateRule()]), + new PersistentProcessRuleMatcher(), + [TimeSpan.Zero, TimeSpan.Zero], + TimeSpan.Zero, + (_, _) => Task.CompletedTask, + lateDelay: TimeSpan.FromSeconds(90)); + private static Mock CreateProcessService(params ProcessPriorityClass[] observedPriorities) { var calls = 0; diff --git a/Tests/ThreadPilot.Core.Tests/ProcessCpuSetHandlerTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessCpuSetHandlerTests.cs index 354cbe8..a6f39e9 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessCpuSetHandlerTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessCpuSetHandlerTests.cs @@ -236,8 +236,9 @@ public void ProcessCpuSetHandler_ApplyCpuSelectionDetailed_WithoutResolvableCpuS } [Fact] - public void ProcessCpuSetHandler_ApplyCpuSelectionDetailed_WhenNativeAccessDenied_ReturnsAccessDenied() + public void ProcessCpuSetHandler_ApplyCpuSelectionDetailed_WhenGrantedHandleIsRefused_ReportsProtection() { + // Seen with Call of Duty (Ricochet): OpenProcess succeeds, SetProcessDefaultCpuSets fails with 5. var nativeApi = new FakeProcessCpuSetNativeApi { SetProcessDefaultCpuSetsResult = false, @@ -255,7 +256,27 @@ public void ProcessCpuSetHandler_ApplyCpuSelectionDetailed_WhenNativeAccessDenie Assert.Equal(AffinityApplyErrorCodes.AccessDenied, result.ErrorCode); Assert.Equal(5, result.Win32ErrorCode); Assert.True(result.IsAccessDenied); + Assert.True(result.IsAntiCheatLikely); + Assert.Equal(ProcessOperationUserMessages.AntiCheatProtectedLikely, result.UserMessage); + } + + [Fact] + public void ProcessCpuSetHandler_ApplyCpuSelectionDetailed_WhenHandleIsRefused_ReportsPlainAccessDenied() + { + var nativeApi = new FakeProcessCpuSetNativeApi + { + FailSetHandleOpen = true, + LastWin32Error = 5, + }; + using var handler = CreateHandler(nativeApi, CpuSetMapping.Empty); + + var result = handler.ApplyCpuSelectionDetailed(new CpuSelection { CpuSetIds = [400] }); + + Assert.False(result.Success); + Assert.True(result.IsAccessDenied); + Assert.False(result.IsAntiCheatLikely); Assert.Equal(ProcessOperationUserMessages.AccessDenied, result.UserMessage); + Assert.False(nativeApi.WasSetProcessDefaultCpuSetsCalled); } [Fact] @@ -381,13 +402,17 @@ private sealed class FakeProcessCpuSetNativeApi : IProcessCpuSetNativeApi public bool SetProcessDefaultCpuSetsResult { get; init; } = true; + public bool FailSetHandleOpen { get; init; } + public uint[]? VerifiedCpuSetIds { get; init; } public IReadOnlyList SystemCpuSets { get; init; } = []; public SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId) { - return new SafeProcessHandle(new IntPtr(1), ownsHandle: false); + return this.FailSetHandleOpen && access.HasFlag(ProcessAccessFlags.PROCESS_SET_LIMITED_INFORMATION) + ? new SafeProcessHandle(IntPtr.Zero, ownsHandle: false) + : new SafeProcessHandle(new IntPtr(1), ownsHandle: false); } public bool SetProcessDefaultCpuSets(SafeProcessHandle process, uint[]? cpuSetIds, uint cpuSetIdCount) diff --git a/Tests/ThreadPilot.Core.Tests/ProcessImagePathTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessImagePathTests.cs new file mode 100644 index 0000000..c6e2c54 --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/ProcessImagePathTests.cs @@ -0,0 +1,40 @@ +namespace ThreadPilot.Core.Tests +{ + using System.Diagnostics; + using ThreadPilot.Platforms.Windows; + + public sealed class ProcessImagePathTests + { + [Fact] + public void CurrentProcess_MatchesMainModulePath() + { + using var self = Process.GetCurrentProcess(); + + Assert.Equal(self.MainModule!.FileName, ProcessImagePath.TryGet(Environment.ProcessId), ignoreCase: true); + } + + [Fact] + public void ChildProcess_IsReadWithLimitedRightsOnly() + { + var cmd = Path.Combine(Environment.SystemDirectory, "cmd.exe"); + using var child = Process.Start(new ProcessStartInfo(cmd, "/c ping -n 3 127.0.0.1 >nul") { CreateNoWindow = true, UseShellExecute = false })!; + try + { + Assert.Equal(cmd, ProcessImagePath.TryGet(child.Id), ignoreCase: true); + } + finally + { + child.Kill(); + } + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(int.MaxValue - 3)] + public void MissingProcess_ReturnsNull(int processId) + { + Assert.Null(ProcessImagePath.TryGet(processId)); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/ProcessMemoryPriorityServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessMemoryPriorityServiceTests.cs index 2b37043..995e190 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessMemoryPriorityServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessMemoryPriorityServiceTests.cs @@ -67,14 +67,17 @@ public async Task SetEfficiencyModeAsync_KeepsTheProcessesOtherThrottlingFlags(P } [Fact] - public async Task SetEfficiencyModeAsync_WhenWindowsDenies_ReportsAccessDenied() + public async Task SetEfficiencyModeAsync_WhenGrantedHandleIsRefused_ReportsProtection() { + // The handle opened, the call made with it was refused: rights stripped by anti-cheat, not missing admin. var nativeApi = new FakeProcessMemoryPriorityNativeApi { SetResult = false, LastError = 5 }; var result = await CreateService(nativeApi).SetEfficiencyModeAsync(CreateProcess(), ProcessEfficiencyMode.On); Assert.False(result.Success); Assert.True(result.IsAccessDenied); + Assert.True(result.IsAntiCheatLikely); + Assert.Equal(ProcessOperationUserMessages.AntiCheatProtectedLikely, result.UserMessage); } [Fact] diff --git a/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs index a34a654..781e85f 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs @@ -145,7 +145,53 @@ public void SelectingProcessInCpuSetsMode_SynchronizesCheckboxesFromWindowsCpuSe Assert.True(SpinWait.SpinUntil( () => viewModel.CpuCores[0].IsSelected && !viewModel.CpuCores[1].IsSelected, TimeSpan.FromSeconds(2))); - Assert.Equal("Current CPU Sets: CPU 0", viewModel.CurrentAffinityText); + Assert.Equal("Current CPU Sets: CPU 0 (set by hand, by the app itself or by another tool)", viewModel.CurrentAffinityText); + } + + [Fact] + public void SelectingProcessBoostedByGameBoost_SaysGameBoostSetTheCpuSets() + { + var processService = CreateRunningProcessService(cpuSets: [0]); + var session = new Mock(MockBehavior.Loose); + session.Setup(service => service.HasAppliedCpuSets(1234)).Returns(true); + using var viewModel = CreateViewModel( + processService.Object, + new Mock(MockBehavior.Loose).Object, + cpuTopologyProvider: null, + settingsService: null, + gameSessionService: session.Object); + viewModel.CpuTopology = CreateTwoCoreTopology(); + viewModel.CpuCores = new System.Collections.ObjectModel.ObservableCollection(viewModel.CpuTopology.LogicalCores); + + viewModel.SelectedProcess = new ProcessModel { ProcessId = 1234, Name = "Game", ProcessorAffinity = 3 }; + + var expected = "Current CPU Sets: CPU 0 (set by Game Boost while the game runs)"; + Assert.True(SpinWait.SpinUntil(() => viewModel.CurrentAffinityText == expected, TimeSpan.FromSeconds(2)), viewModel.CurrentAffinityText); + } + + [Fact] + public void SelectingProcessWithoutCpuSets_SaysWindowsPicksTheCores() + { + var processService = CreateRunningProcessService(cpuSets: []); + using var viewModel = CreateViewModel(processService.Object, new Mock(MockBehavior.Loose).Object, cpuTopologyProvider: null); + viewModel.CpuTopology = CreateTwoCoreTopology(); + viewModel.CpuCores = new System.Collections.ObjectModel.ObservableCollection(viewModel.CpuTopology.LogicalCores); + + viewModel.SelectedProcess = new ProcessModel { ProcessId = 1234, Name = "Game", ProcessorAffinity = 3 }; + + var expected = "Current OS affinity: 0x3 (no CPU Sets, Windows picks the cores)"; + Assert.True(SpinWait.SpinUntil(() => viewModel.CurrentAffinityText == expected, TimeSpan.FromSeconds(2)), viewModel.CurrentAffinityText); + } + + private static Mock CreateRunningProcessService(IReadOnlyList cpuSets) + { + var processService = new Mock(MockBehavior.Loose); + processService.Setup(service => service.IsProcessStillRunning(It.IsAny())).ReturnsAsync(true); + processService.Setup(service => service.RefreshProcessInfo(It.IsAny())).Returns(Task.CompletedTask); + processService + .Setup(service => service.GetCpuAssignmentLogicalProcessorIndexesAsync(It.IsAny(), CpuAssignmentMode.CpuSets)) + .ReturnsAsync(cpuSets); + return processService; } private static ProcessViewModel CreateViewModel(IProcessService processService, IGameModeService gameModeService) @@ -155,7 +201,8 @@ private static ProcessViewModel CreateViewModel( IProcessService processService, IGameModeService gameModeService, ICpuTopologyProvider? cpuTopologyProvider, - IApplicationSettingsService? settingsService = null) + IApplicationSettingsService? settingsService = null, + IGameSessionService? gameSessionService = null) { var virtualizedProcessService = new Mock(MockBehavior.Loose); virtualizedProcessService.SetupProperty( @@ -182,7 +229,8 @@ private static ProcessViewModel CreateViewModel( associationService.Object, gameModeService, cpuTopologyProvider: cpuTopologyProvider, - settingsService: settingsService); + settingsService: settingsService, + gameSessionService: gameSessionService); } private static CpuTopologyModel CreateTwoCoreTopology() diff --git a/Tests/ThreadPilot.Core.Tests/WindowPlacementHelperTests.cs b/Tests/ThreadPilot.Core.Tests/WindowPlacementHelperTests.cs index 76746a3..48d876f 100644 --- a/Tests/ThreadPilot.Core.Tests/WindowPlacementHelperTests.cs +++ b/Tests/ThreadPilot.Core.Tests/WindowPlacementHelperTests.cs @@ -63,6 +63,15 @@ public void CorrectWindowBounds_WhenPartiallyOutside_ClampsInsideIntersectingWor Assert.Equal(864, result.Bounds.Height); } + [Theory] + [InlineData(1280, 864, 960)] + [InlineData(1280, 900, 900)] + [InlineData(1100, 864, 864)] + public void SavedSize_OnlyTheOldUntouchedDefaultGetsTheNewHeight(double width, double height, double expected) + { + Assert.Equal(expected, MainWindow.UpgradeLegacyDefaultHeight(width, height)); + } + [Fact] public void CorrectWindowBounds_WhenFillingWorkingAreaAndShrinkRequested_CentersDefaultSizeOnSameMonitor() { @@ -80,9 +89,9 @@ public void CorrectWindowBounds_WhenFillingWorkingAreaAndShrinkRequested_Centers Assert.True(result.WasCorrected); Assert.Equal(1280, result.Bounds.Width); - Assert.Equal(864, result.Bounds.Height); + Assert.Equal(960, result.Bounds.Height); Assert.Equal(1920 + ((2560 - 1280) / 2), result.Bounds.Left); - Assert.Equal((1400 - 864) / 2, result.Bounds.Top); + Assert.Equal((1400 - 960) / 2, result.Bounds.Top); } [Fact] diff --git a/ViewModels/ProcessPowerPlanAssociationViewModel.cs b/ViewModels/ProcessPowerPlanAssociationViewModel.cs index e0cab95..1117974 100644 --- a/ViewModels/ProcessPowerPlanAssociationViewModel.cs +++ b/ViewModels/ProcessPowerPlanAssociationViewModel.cs @@ -182,7 +182,12 @@ public async Task RefreshSavedProcessRulesAsync() : await this.ruleCreationService.GetRulesNeedingTopologyReviewAsync().ConfigureAwait(true); this.SavedRulesReviewMessage = needingReview.Count == 0 ? string.Empty - : $"These rules pin cores from a different CPU than the one running now, so what they select may not mean what it did when they were saved: {string.Join(", ", needingReview)}. Set their cores again from a saved mask below."; + : string.Format( + System.Globalization.CultureInfo.CurrentCulture, + this.Localize( + "Rules_TopologyReviewWarning", + "These rules pin cores from a different CPU than the one running now, so what they select may not mean what it did when they were saved: {0}. Set their cores again from a saved mask below."), + string.Join(", ", needingReview)); } catch (Exception ex) { diff --git a/ViewModels/ProcessViewModel.Behaviors.partial.cs b/ViewModels/ProcessViewModel.Behaviors.partial.cs index b2a364d..21b5571 100644 --- a/ViewModels/ProcessViewModel.Behaviors.partial.cs +++ b/ViewModels/ProcessViewModel.Behaviors.partial.cs @@ -231,10 +231,19 @@ private async Task HandleSelectedProcessChangedAsync(ProcessModel value) value, CpuAssignmentMode.CpuSets); IReadOnlyList? softAssignmentIndexes; + var cpuSetsSource = CpuSetsSource.Other; if (cpuSetIndexes is { Count: > 0 }) { assignment = (CpuAssignmentMode.CpuSets, assignment.FromRule && assignment.Mode == CpuAssignmentMode.CpuSets); softAssignmentIndexes = cpuSetIndexes; + if (this.gameSessionService?.HasAppliedCpuSets(value.ProcessId) == true) + { + cpuSetsSource = CpuSetsSource.GameBoost; + } + else if (assignment.FromRule) + { + cpuSetsSource = CpuSetsSource.Rule; + } } else { @@ -254,11 +263,14 @@ await InvokeOnUiAsync(() => this.SetCpuAssignmentMode(assignment.Mode, assignment.FromRule); if (softAssignmentIndexes is { Count: > 0 }) { - this.UpdateCoreSelections(softAssignmentIndexes, assignment.Mode); + this.UpdateCoreSelections(softAssignmentIndexes, assignment.Mode, cpuSetsSource: cpuSetsSource); } else { - this.UpdateCoreSelections(value.ProcessorAffinity); + // An empty list (not null) means Windows answered: the process has no CPU Sets of its own. + this.UpdateCoreSelections( + value.ProcessorAffinity, + note: cpuSetIndexes is { Count: 0 } ? this.UiText("ProcessView_NoCpuSetsNote", "no CPU Sets, Windows picks the cores") : null); } this.UpdateAffinityDisplayState(); @@ -441,9 +453,10 @@ private void UpdateAffinityPresets() } } - private void UpdateCoreSelections(long affinityMask, bool forceSync = false) + private void UpdateCoreSelections(long affinityMask, bool forceSync = false, string? note = null) { this.currentSoftCpuAssignmentText = null; + this.currentAffinityNote = note; this.UpdateCoreSelections( core => (affinityMask & core.AffinityMask) != 0, $"affinity mask 0x{affinityMask:X}", @@ -453,12 +466,27 @@ private void UpdateCoreSelections(long affinityMask, bool forceSync = false) private void UpdateCoreSelections( IReadOnlyCollection logicalProcessorIndexes, CpuAssignmentMode mode, - bool forceSync = false) + bool forceSync = false, + CpuSetsSource cpuSetsSource = CpuSetsSource.Other) { var selectedIndexes = logicalProcessorIndexes.ToHashSet(); + var cpus = string.Join(", ", selectedIndexes.OrderBy(index => index)); + this.currentAffinityNote = null; this.currentSoftCpuAssignmentText = mode == CpuAssignmentMode.CpuSets - ? $"Current CPU Sets: CPU {string.Join(", ", selectedIndexes.OrderBy(index => index))}" - : $"Current ideal processors: CPU {string.Join(", ", selectedIndexes.OrderBy(index => index))}"; + ? string.Format( + System.Globalization.CultureInfo.CurrentCulture, + this.UiText("ProcessView_CurrentCpuSets", "Current CPU Sets: CPU {0} ({1})"), + cpus, + cpuSetsSource switch + { + CpuSetsSource.GameBoost => this.UiText("ProcessView_CpuSetsFromGameBoost", "set by Game Boost while the game runs"), + CpuSetsSource.Rule => this.UiText("ProcessView_CpuSetsFromRule", "from your saved rule"), + _ => this.UiText("ProcessView_CpuSetsFromOther", "set by hand, by the app itself or by another tool"), + }) + : string.Format( + System.Globalization.CultureInfo.CurrentCulture, + this.UiText("ProcessView_CurrentIdealProcessors", "Current ideal processors: CPU {0}"), + cpus); this.UpdateCoreSelections( core => selectedIndexes.Contains(core.LogicalCoreId), this.currentSoftCpuAssignmentText, @@ -544,7 +572,7 @@ private void UpdateAffinityDisplayState() { var currentMask = this.SelectedProcess?.ProcessorAffinity; this.CurrentAffinityText = this.currentSoftCpuAssignmentText ?? (currentMask.HasValue - ? $"Current OS affinity: 0x{currentMask.Value:X}" + ? (this.currentAffinityNote == null ? $"Current OS affinity: 0x{currentMask.Value:X}" : $"Current OS affinity: 0x{currentMask.Value:X} ({this.currentAffinityNote})") : "Current OS affinity: no process selected"); if (this.SelectedProcess == null) diff --git a/ViewModels/ProcessViewModel.cs b/ViewModels/ProcessViewModel.cs index fe38b6c..65be7fa 100644 --- a/ViewModels/ProcessViewModel.cs +++ b/ViewModels/ProcessViewModel.cs @@ -40,6 +40,7 @@ public partial class ProcessViewModel : BaseViewModel private readonly ILocalizationService? uiLocalization; private readonly IPersistentProcessRuleStore? persistentRuleStore; private readonly IPersistentProcessRuleMatcher? persistentRuleMatcher; + private readonly IGameSessionService? gameSessionService; private readonly Action clipboardSetter; private readonly Action executableLocationOpener; private System.Timers.Timer? refreshTimer; @@ -55,6 +56,7 @@ public partial class ProcessViewModel : BaseViewModel private bool suppressCpuAssignmentModeChanges; private bool cpuAssignmentModeOverriddenByRule; private string? currentSoftCpuAssignmentText; + private string? currentAffinityNote; [ObservableProperty] private bool isAutomationMonitoringEnabled = true; @@ -197,7 +199,8 @@ public ProcessViewModel( Action? executableLocationOpener = null, ILocalizationService? localizationService = null, IApplicationSettingsService? settingsService = null, - ProcessPowerRequestService? powerRequestService = null) + ProcessPowerRequestService? powerRequestService = null, + IGameSessionService? gameSessionService = null) : base(logger, enhancedLoggingService, activityAuditService) { this.processService = processService ?? throw new ArgumentNullException(nameof(processService)); @@ -225,6 +228,7 @@ public ProcessViewModel( this.uiLocalization = localizationService; this.persistentRuleStore = persistentRuleStore; this.persistentRuleMatcher = persistentRuleMatcher; + this.gameSessionService = gameSessionService; this.SelectedCpuAssignmentMode = settingsService?.Settings.DefaultCpuAssignmentMode ?? CpuAssignmentMode.Automatic; // Fields, not properties: the change handlers would reload and re-save the list during construction. @@ -302,6 +306,14 @@ private void OnSettingsChanged(object? sender, ApplicationSettingsChangedEventAr public SelectedProcessSummaryViewModel SelectedProcessSummary { get; } + // Who set the CPU Sets shown for the selected process, as far as ThreadPilot can tell. + private enum CpuSetsSource + { + Other, + GameBoost, + Rule, + } + private static void OpenExecutableLocationInExplorer(string executablePath) { var startInfo = new ProcessStartInfo diff --git a/Views/ProcessPowerPlanAssociationView.xaml b/Views/ProcessPowerPlanAssociationView.xaml index 4ce72db..2f649d7 100644 --- a/Views/ProcessPowerPlanAssociationView.xaml +++ b/Views/ProcessPowerPlanAssociationView.xaml @@ -146,6 +146,8 @@ Width="330" Header="{DynamicResource ProcessPowerPlanAssociationView_SavedRuleEditor}" VerticalAlignment="Top"> + + @@ -199,11 +201,35 @@ FontWeight="SemiBold" TextWrapping="Wrap" Margin="0,0,0,6"/> - + + + + + + + + + + @@ -216,6 +242,7 @@ Padding="10,4" HorizontalAlignment="Left"/> + - + diff --git a/docs/design/protected-processes.md b/docs/design/protected-processes.md new file mode 100644 index 0000000..abe9711 --- /dev/null +++ b/docs/design/protected-processes.md @@ -0,0 +1,104 @@ +# Protected processes: what ThreadPilot does, what it will not do, and why + +Some games run a kernel-mode anti-cheat or anti-tamper driver (Ricochet in Call of Duty, Vanguard, EasyAntiCheat, +BattlEye, FACEIT…). They can make `SetProcessDefaultCpuSets`, `SetProcessAffinityMask`, `SetPriorityClass` or +`SetProcessInformation` fail with `ERROR_ACCESS_DENIED`. This note records how ThreadPilot handles that today, what +other tools do, and the design ThreadPilot follows. Measurements come from a real i9-12900K +(see `docs/validation/`). + +## What actually happens (measured) + +| Game / protection | OpenProcess (limited rights) | CPU Sets | QoS / efficiency | Priority | +|---|---|---|---|---| +| Call of Duty (Ricochet) | granted | **refused, ERROR_ACCESS_DENIED** after the handle was granted | refused the same way | not tested | +| Arma Reforger (BattlEye) | granted, but `PROCESS_VM_READ` refused (so `Process.MainModule` gave no path) | accepted | accepted | accepted | +| Assetto Corsa Competizione (none) | granted | accepted | accepted | accepted (rule, AboveNormal) | + +Two details matter for the design: + +1. **The refusal happens on the call, not on the open.** Ricochet lets `OpenProcess` succeed and strips the access + rights from the handle (an `ObRegisterCallbacks` pre-operation callback), so the error shows up on the call. + ThreadPilot always runs elevated (`requireAdministrator`), so "you may need administrator rights" was the wrong + hint. Since commit "Report a refused granted handle as protection…" such failures are reported as + *appears protected by anti-cheat or process protection; ThreadPilot will not try to bypass it*. +2. **The decision depends on the caller.** During diagnosis the same `SetProcessDefaultCpuSets` call from a + Microsoft-signed process was accepted, while an unsigned .NET executable got `ERROR_ACCESS_DENIED`. The anti-cheat + decides who may change its game; administrator rights, `SeDebugPrivilege` or `LocalSystem` do not enter into it. + +## How other tools do it + +Process Lasso and similar tools use the same documented Win32 calls ThreadPilot uses (`SetProcessAffinityMask`, +`SetProcessDefaultCpuSets`, `SetPriorityClass`, IFEO `PerfOptions`). Such tools typically run an elevated background "governor" +(optionally as a service) and may enable `SeDebugPrivilege` to open processes of other users and services. That helps with +**ordinary** access-denied cases (services, other sessions). It does not help against kernel callbacks that strip +handle rights or against protected processes (PPL): the kernel enforces those whatever the caller's token holds. +Ways that *do* get around them (opening the process before the driver is up, racing process creation in suspended +state, injecting into a trusted process, borrowing a signed binary, using a driver) defeat the anti-cheat's intent +and can get the user's account banned. ThreadPilot does none of them, and this design keeps it that way. + +## Design + +### 1. Least rights, per operation + +- Read with `PROCESS_QUERY_LIMITED_INFORMATION` only (paths via `QueryFullProcessImageName`, not + `Process.MainModule`, which needs `PROCESS_VM_READ` – the right anti-cheats refuse first). +- Write with the narrowest right the call needs (`PROCESS_SET_LIMITED_INFORMATION` for CPU Sets). +- Never hold a full-access handle to a game for its lifetime (Game Boost holds `SYNCHRONIZE | + PROCESS_QUERY_LIMITED_INFORMATION` only, to be told when it exits). +- No `SeDebugPrivilege`: ThreadPilot never asks for rights that need it, and some anti-cheats treat a process holding + it as suspicious. + +### 2. Classify, do not retry + +| Observation | Classification | User message | +|---|---|---| +| `OpenProcess` refused with 5 | access denied (other session, PPL, service) | "Windows denied this change…" | +| handle granted, call refused with 5 | protected by anti-cheat / anti-tamper | "appears protected… will not try to bypass it" | +| error 87 / process gone | exited | "The process exited…" | +| CPU Sets rejected for another reason | unavailable | CPU Sets unavailable, safe fallback only when possible | + +Each Game Boost change is attempted once per process instance; persistent rules have a cooldown. A protected game +therefore produces one Activity line per launch, not one per tick. The native calls return result objects and +the apply paths classify failures instead of throwing, so a refusal is a reported outcome, not a crash. + +### 3. Offer what does work + +For a protected game ThreadPilot can still: + +- move the listed **background** (Steam, browsers, launchers) to other cores and EcoQoS – measured working on Call of + Duty; +- set a **launch-time priority** with IFEO `PerfOptions\CpuPriorityClass` (already in the app as "registry + priority"): Windows itself applies it when the process is created, so no handle to the game is needed. It is + documented as not bypassing protection, and the game may still change its own priority later; +- point the user at the game's own settings when they exist (e.g. Call of Duty's `RendererWorkerCount`). + +There is no IFEO equivalent for affinity or CPU Sets, and setting them on the launcher so the game inherits them is +unreliable (anti-cheat bootstrappers create the game process themselves). ThreadPilot does not offer either. + +### 4. What a SYSTEM service would and would not change + +A `LocalSystem` service would let rules apply before anyone logs on and without the UI process. It would not let +ThreadPilot change a game whose anti-cheat refuses it (see above), and it would add a privileged endpoint that the +user-level UI talks to, which is an elevation-of-privilege surface to secure. ThreadPilot already starts elevated +at logon through a scheduled task. **Recommendation: no service for this purpose.** + +### 5. Code signing (open question) + +Because the refusal depends on the caller, a signed ThreadPilot *might* be accepted by some anti-cheats. That is the +only legitimate lever, and it is the anti-cheat vendor's decision; it was not tested and is not a reason to sign. + +## CPU-bound tuning that stays within these rules + +- **Hybrid Intel (P/E):** Game Boost puts the game on the P-core threads and the listed background on the E-cores. + On the 12900K this removed the game's own work from the E-cores (≈1.7 CPUs of Arma Reforger moved to P threads) + without a measurable frame-rate change in a GPU-bound scene. +- **One thread per P-core (skip SMT siblings):** expressible as CPU Sets (one logical processor per `CoreIndex` of + the top class). Measured on Arma Reforger: no benefit. Kept as an idea, not a default. +- **Core 0 isolation:** Windows services many interrupts and DPCs on CPU 0. Keeping the game's busiest work off + CPU 0/1 could reduce jitter on some systems, but it was not measured here (needs a DPC/ISR latency tool and + frame-time data); not proposed as a default. +- **Core parking:** with the Ultimate Performance plan no core is parked, so CPU Sets are never pointed at parked + cores. On Balanced, parked P-cores wake on demand; ThreadPilot's "prevent core parking" tweak exists for users who + want it. No change needed in Game Boost. +- **AMD with several CCDs:** already handled by Game Boost's AMD policies (V-Cache CCD for the game, or background + off CCD0); unchanged. diff --git a/docs/validation/intel-hybrid-12900k.md b/docs/validation/intel-hybrid-12900k.md new file mode 100644 index 0000000..5c340e8 --- /dev/null +++ b/docs/validation/intel-hybrid-12900k.md @@ -0,0 +1,168 @@ +# Game Boost on a real Intel hybrid CPU (Core i9-12900K) + +This is the record of one validation session of Game Boost on real Alder Lake hardware: what was measured, +what was found broken, what was fixed on branch `validation/intel-hybrid-12900k`, and what is still open. +Every result is tagged with how it was established: + +- **HW** – verified on the real i9-12900K (numbers read from Windows, not from the ThreadPilot UI) +- **Test** – verified only by automated tests or a simulated topology +- **Inferred** – reasoned from the code or from other measurements, not measured +- **Not run** – not executed (reason given) + +## Test system + +| | | +|---|---| +| CPU | Intel Core i9-12900K: 8 P-cores with Hyper-Threading + 8 E-cores, 24 logical processors, one 30 MB L3 | +| RAM / GPU | 32 GB / NVIDIA GeForce RTX 4070 Ti (driver 32.0.16.2140) | +| Board / BIOS | ASUS TUF GAMING Z690-PLUS D4, BIOS 4701 | +| OS | Windows 11 Pro 26H2, build 26300.9974; VBS/HVCI not running | +| Power plan | Ultimate Performance ("Prestazioni eccellenti"): core parking minimum 100 %, heterogeneous thread scheduling policy 5 (automatic) | +| ThreadPilot | 1.7.11, starting commit `4fa24ee`, Italian UI | +| Tools | Throw-away tools kept outside the repository: a CPU Set reader (`GetSystemCpuSetInformation`, `GetProcessDefaultCpuSets`, `GetProcessInformation(ProcessPowerThrottling)`), a kernel context-switch tracer (TraceEvent, run time of every process on every CPU), a controllable fake game installed under `…\steamapps\common\FakeGame\`, renamed copies of it as `chrome`/`steam`/`discord`/`Spotify`, and PresentMon 2.6.0 for frame times | + +CPU Set table as Windows reports it (HW): 24 CPU Sets, IDs 256–279; EfficiencyClass 1 on logical processors +0–15 (CoreIndex 0, 2, …, 14: SMT pairs (0,1)…(14,15)); EfficiencyClass 0 on logical processors 16–23 (one per +core); one L3 group. This exact table is now a regression test (`GameBoostIntelHybridTests`). + +## Results V1–V12 + +| # | Check | Result | How | +|---|---|---|---| +| V1 | Topology and decision | 24 CPU Sets, P = class 1 (16 CPUs), E = class 0 (8 CPUs). The Optimizations page shows "game on the P-cores (16 CPUs), selected background apps on the E-cores (8 CPUs)" in both modes. | HW | +| V2 | Detection and session | Fake game in `\steamapps\common\` starts a session within one 3 s tick; Alt+Tab to ThreadPilot keeps it; closing the game ends it. Real games: Farming Simulator 25 and Call of Duty detected; **Arma Reforger was not detected before the fix** (see problem 2), detected after it. | HW | +| V3 | CPU Sets read from Windows | Automatic: game → CPU 0–15 + high QoS; listed background (`chrome`, `steam`, `steamwebhelper` ×6) → CPU 16–23; unlisted processes untouched. Isolation (switched mid-session): additionally `Spotify` moved, EcoQoS on the listed background, game keeps all 16 P threads. | HW | +| V4 | Restore | Game exit, switch off, mode change mid-session, `taskkill /f` mid-session (journal with 8 confirmed entries on disk, everything restored at the next start) all restore every change. A user rule (CPU Sets 0,2,4,6) on the game is left alone ("cores left to your rule"). A game's own `PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION` flag is kept (ControlMask 0x5 / StateMask 0x4 during the session, 0x4 / 0x4 after). | HW | +| V5 | Dynamic release | 20 busy threads on the 16 P CPUs: released after **13.3 s** and **15.8 s** (expected 12–15 s); load back to 4 threads: confined again after **63 s** (expected ~60 s); after the 2nd release the game stays free for the rest of the session. | HW | +| V6 | What the user sees | Processes page did show the CPU Sets for a boosted game, but in English, without saying who set them, next to a status line printing the full OS affinity. Fixed: localized line naming Game Boost / your rule / other, and a "no CPU Sets, Windows picks the cores" note. The real cause of "nothing shown" for Arma was V2 (nothing was applied). | HW (before and after) + Test | +| V7 | Windows Game Mode | Reproduced: with `AutoGameModeEnabled` absent the page said "Disabled" while Windows uses its default (enabled). Fixed; registry restored after the test. | HW (repro) + Test | +| V8 | Real games | Arma Reforger (offline training scene, ~120 fps GPU/limit-bound) and Farming Simulator 25 (main menu only). See below. | HW | +| V8-bis | Call of Duty | Detected; **CPU Sets and QoS refused**: Ricochet returns ERROR_ACCESS_DENIED (5) from `SetProcessDefaultCpuSets` for an unsigned caller although `OpenProcess` succeeds. Not worked around. Assetto Corsa Competizione / Rally could not be started without interacting with a Steam dialog: not run. | HW | +| V9 | Diagnostics | Activity entries (session start/end, mode, what was applied or skipped and why, dynamic release/confine, restore) now also go to `ThreadPilot.log`; new one-line reports for a foreground process whose path cannot be read and for a failing tick. | HW + Test | +| V10 | Windows / Thread Director | Plan parks no cores and uses automatic heterogeneous scheduling: no conflict with CPU Sets, no warning needed. Without Game Boost Windows did **not** keep light background work on the E-cores (fake background at 30 % duty ran ~88 % on P-cores), and let Arma's workers spread evenly onto the E-cores. Balanced plan not tried (not changing system settings). | HW (partial) | +| V11 | 12th/13th/14th gen, Core Ultra | Real 12900K table + synthetic 13900K/14900K/14700K/13700K/12600K/13600K, 12400 (no E-cores: no action), Core Ultra with three classes, Arrow Lake without SMT, Lunar Lake (4 P-cores: no action). | Test | +| V12 | Cost and leftovers | Idle, no game, main window open: ThreadPilot used 1.37 % of one CPU over 120 s with Game Boost on and 1.21 % with it off (0.06 % / 0.05 % of the machine), ~215 MB working set. No warning or error in the log apart from the expected Call of Duty refusals. No process left with CPU Sets after all tests except one `svchost` whose all-24 CPU Sets were already there before ThreadPilot ran. | HW | + +### V8 numbers (45 s windows, kernel context-switch accounting) + +| Scene | Game Boost | Game on P (CPUs) | Game on E (CPUs) | P busy avg | E busy avg | avg fps | 1 % low fps | +|---|---|---|---|---|---|---|---| +| Arma Reforger training | off | 2.69 | **1.66** | 17.9 % | **22.3 %** | 121.7 | 99.3 | +| Arma Reforger training | Automatic | 4.21 | 0 | 27.5 % | 2.6 % | 121.6 | 101.0 | +| Arma Reforger training | Isolation | 4.14 | 0 | 27.1 % | 2.2 % | 122.0 | 102.8 | +| Arma Reforger training (2nd run) | Automatic | 4.44 | 0 | 28.7 % | 2.1 % | 119.9 | 97.8 | +| Arma Reforger training (2nd run) | off, CPU Sets = one thread per P-core (CPU 0,2,…,14) | 3.15 | 0 | 20.6 % | 1.7 % | 120.9 | 87.5 | +| Arma Reforger training (2nd run) | off | 2.71 | 1.66 | 18.0 % | 22.2 % | 122.8 | 101.0 | +| Farming Simulator 25 main menu | off / Automatic / Isolation | 0.27 | 0 | ~2 % | <1 % | 60.2 | ~58.7 | +| Call of Duty menu, `RendererWorkerCount = 7`, first start after a driver update (shader compilation) | on (refused for the game) | 6.21 | 2.51 | 44.5 % | 34.9 % | 30.2 | 26.3 | +| Call of Duty menu, default `RendererWorkerCount` | on (refused for the game) | 1.17 | 0 | 13.8 % | 1.1 % | 30.0 | 29.0 | + +What this shows, and what it does not: + +- Game Boost does what it says on this CPU: a detected, writable game runs only on the P-core threads and + the listed background only on the E-cores. +- **No frame-rate benefit was measured.** Arma Reforger's training scene is GPU/limit-bound at ~120 fps and every + configuration gives the same average; 1 % lows differ by a few fps between single 45 s runs, within run-to-run + noise. The Farming Simulator 25 and Call of Duty menus are frame-capped (60 / 30 fps). Saved games were not + loaded, to leave the owner's saves untouched, so CPU-bound gameplay was not measured. +- The "one thread per P-core" mask did not help Arma; its single lower 1 % low is not enough to call it worse. +- `RendererWorkerCount = 7` does not keep Call of Duty off the SMT siblings or the E-cores in the menu: during + shader compilation `cod.exe` ran on all 24 logical processors (2.5 CPUs on the E-cores). The setting limits the + render workers only. The two CoD rows are not comparable to each other (the first one includes shader + compilation after a driver update). + +## The three reported problems + +### 1. All eight E-cores evenly at ~25 % during Arma Reforger / Farming Simulator 25 + +Measured cause (HW): with Game Boost not applied to the game, **Arma Reforger's own worker threads** run on the +E-cores: 1.66 CPUs of `ArmaReforgerSteam` spread evenly, ~21 % on each of the eight E-cores, and nothing else +of significance there (BattlEye's `BEService` < 0.05 CPU, Steam < 0.01). With Game Boost applied the E-cores +drop to ~2–3 % and the game's work moves to the P-core threads. In the reported session Game Boost was not +being applied to Arma at all (problem 2), which matches the picture. The even ~0 % on the second SMT threads +is Windows preferring one thread per P-core before the siblings. Farming Simulator 25 could only be measured +in its menu (0.27 CPU, all on P-cores with or without Game Boost), so its in-game E-core load is not explained +by a measurement here. + +### 2. "Processes" showed no Game Boost CPU Sets for the game + +Two separate things: + +1. **Arma Reforger was never boosted.** ThreadPilot read executable paths through `Process.MainModule`, which + needs `PROCESS_VM_READ` to walk the module list in the target's memory. BattlEye refuses that right, so + `ArmaReforgerSteam.exe` had an empty path, failed the `\steamapps\common\` check and no session started — + silently. The same process accepts CPU Sets and QoS changes from ThreadPilot (verified by adding it to the + manual list). Fixed by reading the path with `QueryFullProcessImageName` and only + `PROCESS_QUERY_LIMITED_INFORMATION` (the right Task Manager uses). After the fix Arma is detected and confined + with no manual entry (HW). +2. **The page did show CPU Sets for a boosted game** (verified with the fake game on the unmodified build), but + as an English "Current CPU Sets: …" line without a source, next to "Affinity: 0xFFFFFF", which reads as + "nothing applied". The line is now localized and says "set by Game Boost while the game runs", "from your + saved rule" or "set by hand, by the app itself or by another tool"; it also wraps instead of being cut. + +### 3. Windows Game Mode shown as disabled + +`GameModeService` treated a missing `HKCU\Software\Microsoft\GameBar` key or `AutoGameModeEnabled` value as +"disabled". Windows writes the value only after the user flips the switch and defaults to enabled. Now only an +explicit 0 means off; unreadable values report the Windows default. `SetGameModeAsync` still writes an explicit +DWORD, so the switch and the page stay consistent. + +### 4. Game Boost sessions missing from the log file + +`ServiceConfiguration` calls `AddLogging` without any provider, so everything logged through `ILogger` — +including Game Boost's session messages — was discarded; `ThreadPilot.log` only receives +`IEnhancedLoggingService` events. Activity entries are now also written to the log file (one line per entry), +which covers Game Boost start/end, mode, applied/skipped with reasons, dynamic release/confine and restore. + +## Commits on this branch + +| Commit | Change | Tests | +|---|---|---| +| Treat a missing Game Mode registry value as enabled | V7 | `GameModeServiceTests` (scratch HKCU key) | +| Write Activity entries to the log file | V9 | `ActivityAuditServiceTests` | +| Say who set the CPU Sets shown on the Processes page | V6, 7 languages | `ProcessViewModelAffinityTests` | +| Report Game Boost skips that left no trace | V9 | `GameSessionServiceTests` | +| Add Intel hybrid regression tests from a real i9-12900K | V11 | `GameBoostIntelHybridTests` | +| Read process paths without PROCESS_VM_READ | V2 / problem 2 | `ProcessImagePathTests` (native) | +| Wrap the current CPU assignment line on the Processes page | V6 | – | + +Baseline: 969 tests passed, 0 skipped (the native `GameSessionNativeIntegrationTests` run on this 24-thread CPU). +Branch: all tests pass (1001 at the time of writing); Debug and Release build with no new warnings. + +## 12th, 13th and 14th generation and Core Ultra + +- **Proven on hardware:** Alder Lake i9-12900K only (8P+8E, one L3, Windows 11 26H2). +- **Inferred for Raptor Lake / Raptor Lake Refresh (13th/14th gen):** same EfficiencyClass scheme (1 = P, 0 = E), + P-cores with Hyper-Threading listed first, one L3. The policy picks the P threads for the game and the E-cores + for the background exactly as on the 12900K (synthetic tests). With 16 E-cores (13900K/14900K) the background + side is larger, which does not change anything for the game. +- **Inferred for Core Ultra:** only the highest EfficiencyClass is treated as P; every lower class, including + low-power E-cores on a three-class part, goes to the background set. That is acceptable for background work, + but on laptops the LP E-cores are slow, and the policy does not prefer the normal E-cores for the background. + Parts with fewer than 6 P-cores (Lunar Lake, 2P+8E mobile chips) get no action. Arrow Lake desktop (8 P-cores + without SMT) gives the game 8 CPUs. None of this was run on such hardware. +- **Anti-cheat:** Ricochet (Call of Duty) refuses CPU Set and QoS changes from ThreadPilot; BattlEye (Arma + Reforger) accepts them. Other anti-cheats were not tested. + +## Proposals (not implemented) + +- **Dynamic release thresholds:** the measured timings match the design. On a 12900K "80 % of the game's CPUs" + means ≥ 12.8 busy logical processors out of 16 (8 cores with SMT), so a game using one thread per P-core (8 + busy threads) is never released, which is the intended behaviour. Call of Duty's shader compilation (~8.7 + CPUs busy) would not trigger a release either. No change proposed without frame-time data from CPU-bound games. +- **"One thread per P-core" option:** feasible as a CPU Set selection (`CoreIndex`-unique logical processors of + the top class). Not implemented: the only writable game tested did not benefit, and the game it would matter + for (Call of Duty) cannot be changed by ThreadPilot anyway. +- **Code signing:** Ricochet's decision appears to depend on the caller (a Microsoft-signed process got the same + calls accepted during diagnosis, an unsigned .NET executable got ERROR_ACCESS_DENIED). Whether a signed + ThreadPilot would be accepted is unknown and was not tried; it is not a workaround to pursue against the + anti-cheat's intent. +- **Isolation description:** the mode text mentions "CCD0" on Intel too; an Intel-specific sentence would be clearer. + +## Still open + +- CPU-bound gameplay (loaded saves) was not measured; no FPS claim is made either way. +- The Processes list showed 0.0 % CPU for `ArmaReforgerSteam` although .NET reads its CPU time; not investigated. +- The core mask picker keeps showing "All Cores" while a process has CPU Sets. +- Game Boost Activity messages are English (like the rest of the Activity log); only UI strings are localized. +- Balanced power plan comparison and Windows' own automatic EcoQoS decisions were not measured in depth. diff --git a/docs/validation/performance-audit-12900k.md b/docs/validation/performance-audit-12900k.md new file mode 100644 index 0000000..67c81ad --- /dev/null +++ b/docs/validation/performance-audit-12900k.md @@ -0,0 +1,77 @@ +# Performance audit on an i9-12900K (background cost, startup, Game Boost, sim racing) + +Measured on the same machine as `intel-hybrid-12900k.md` (i9-12900K, Windows 11 26H2, 153 processes running), +ThreadPilot 1.7.11 plus the commits on this branch. Tools: `dotnet-counters`, `dotnet-trace` (sampled thread time, +filtered to samples that are not parked in a wait), kernel CPU sampling with stacks (1 ms), process CPU time over +fixed windows. Single runs unless stated; differences under ~0.1 % of one core are within noise. + +## Background CPU + +| State | ThreadPilot CPU (one core = 100 %) | +|---|---| +| Started minimized to tray (autostart case), Game Boost off | 0.03–0.09 % | +| Started minimized, Game Boost on (3 s tick, no game) | 0.065 % (no measurable difference from off) | +| Game Boost session on Assetto Corsa Competizione, ThreadPilot in tray | 0.08 % | +| Main window open on the Processes page (5 s refresh) | 2.3 % | +| Window opened, then sent to the tray | 0.6–1.0 % (see below) | + +- **Process monitoring is already event-driven.** Process start/stop come from `Win32_ProcessStartTrace` / + `Win32_ProcessStopTrace` (extrinsic WMI events backed by kernel ETW, no `WITHIN` polling inside WMI). Polling only + runs as a fallback when WMI is degraded. Moving to raw ETW would not lower the idle cost measurably: it is already + below 0.1 % of one core. +- **Game Boost's 3 s tick costs nothing measurable** (it remembers a rejected foreground process for 30 s and otherwise + only reads the foreground process id and start time). A foreground-change hook would only shorten the time to start a + session from ≤ 3 s to ~0, which does not matter for games that take tens of seconds to load. Not changed. +- **Window open:** in the 2.3 % the managed work is WPF layout of the process list (rows re-measured because the + list is sorted by CPU use and re-orders every refresh) and `Process.MainWindowHandle`, which ran a full + `EnumWindows` for each of the ~150 processes. The latter is now one `EnumWindows` pass per refresh + (≈2 ms → 0.02 ms per refresh). The DataGrid already uses container recycling; the remaining layout cost comes with + a live sorted list. +- **Window opened, then hidden:** the refresh timers do stop (process list, tray status, power plans, performance + page) and almost no managed code runs (5 non-waiting samples in 60 s), but the UI thread keeps doing native + message-loop work (user32/win32k) and the WPF render thread wakes up. Mica backdrop accounts for part of it + (A/B, one run each: 0.91 % with Mica, 0.57 % with no backdrop). Root cause of the rest not found; Mica not removed + (design choice, small effect). + +## Memory + +| | Working set | Private bytes | GC heap | +|---|---|---|---| +| Single-file install, started minimized | ~182 MB | ~146 MB | ~28 MB | +| Folder (non-single-file) build, started minimized | ~180 MB | ~92 MB | – | +| Single-file install after the window was opened, hours later | ~400 MB | ~364 MB | ~28 MB | + +The managed heap is small; most private memory is the runtime/WPF image data of the self-contained single-file +publish, and the visual tree once the window has been shown. Publishing as a folder saves ~50 MB private at start; +that is an installer/packaging decision and was not changed here. + +## Startup + +From process start: main window initialized after **0.83 s**, process monitoring active after **1.0 s** (log +timestamps; ~1.3 s of CPU). No change proposed. Note for future measurements: `ThreadPilot.log` is flushed every +5 s, so the file's modification time is not a startup marker. + +## Assetto Corsa Competizione (no anti-cheat) + +- Existing rule (P-core CPU Sets + Above Normal) applied **2.2 s** after process start; Game Boost logged + "cores left to your rule", added high QoS and moved Steam, Steam web helpers and Edge to the E-cores. +- Priority stayed Above Normal for the full 120 s observation on the second launch. On the **first** launch it was + found back at Normal about a minute later although ThreadPilot had verified it at +1 s and +4 s and logged no + other priority write. **Fixed afterwards** with a late check at +90 s that shares the rule's single retry + (commit "Check a rule's priority once more 90 s after the process starts"). Verified live: priority forced back + to Normal at +21 s, the late check saw it at +94 s and the retry restored Above Normal at +98 s. +- ThreadPilot overhead during the session: 0.08 % of one core. +- Assetto Corsa Rally was not run (same rule shape as ACC). + +## Protected games + +See `docs/design/protected-processes.md`. Change made: a handle that is granted and then refused with +`ERROR_ACCESS_DENIED` is now reported as anti-cheat/anti-tamper protection instead of "may require administrator +rights" (verified live on Call of Duty). + +## Changes on this branch from the audit + +| Commit | Effect | +|---|---| +| Find main windows with one EnumWindows pass per process list refresh | ≈2 ms → 0.02 ms of window lookups per refresh | +| Report a refused granted handle as protection, not missing admin rights | correct message for Ricochet-protected games, in Activity too |