Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6570d1a2bd |
No files matched your search
@@ -19,6 +19,27 @@ GitHub release body, so a missing section will mean an empty release note.
|
||||
|
||||
### Added
|
||||
|
||||
- **P4 PR-2 — the "is Vulkan" fact, and the layer's registration following the ledger (2026-09-14).** The rule
|
||||
`12_BUILD` §The Vulkan layer is not registered at install time states — registered only while at least one
|
||||
Vulkan game has hooking enabled, unregistered when the last is disabled — had no way to know which game was
|
||||
Vulkan; the check was "any enabled game". Now the fact is static: `GameFileProbe` reads the executable's import
|
||||
and delay-load tables (`Infrastructure.Detection.PeImports`, bounded, read-only, no exception for a malformed
|
||||
file) and looks for `vulkan-1.dll` as an ASCII or UTF-16 string in the bounded scan (a `LoadLibraryW` loader —
|
||||
`hook-harness --vulkan`'s shape); `StaticDetectionResult.UsesVulkan` is true / false / null, and the sweep
|
||||
stores a true as the id `vulkan` in `capability_flags` beside the rule ids ("Supports Vulkan" on the game page).
|
||||
`Application.Vulkan.VkLayerReconciler` over the new `IVkLayerRegistrar` port (`Infrastructure.Vulkan.VkLayerRegistrar`,
|
||||
the same manifest and HKCU value `--register-vklayer` writes) computes the desired registration from the consent
|
||||
store's enabled games joined to their flags and moves the registration to it — after the pipe handler's stamp,
|
||||
revoke and guard block, after the console `consent grant` / `revoke`, and after every detection sweep, so the
|
||||
crash policy's auto-disable and a fact that arrives after the consent converge within one interval; not staged
|
||||
= nothing to do. `--register-vklayer` runs the reconciler and refuses when no hook-enabled game references the
|
||||
loader; Settings' Register button follows the same rule (`HookedGameViewModel.UsesVulkan`). An Agent off the
|
||||
profile ledger (`--data-dir`) gets an inert registrar: a test or developer ledger never touches HKCU. Tests:
|
||||
`VkLayerReconcilerTests` (first Vulkan game registers, last disables, a D3D game does not, idempotent, not
|
||||
staged), `PeImportsTests` (a synthetic PE32+: both directories, the wide literal through the probe, a malformed
|
||||
file, a non-PE reads as unknown), `DetectionSweepTests` and `StaticGameDetectorTests` (the three-valued fact).
|
||||
`Settings_VkLayer_Note` reworded en/vi/ja. Docs: `17_HOOK_ENGINE` §Vulkan built note gap (1) closed,
|
||||
`12_BUILD` §The Vulkan layer…, `05_DETECTION` §Capability hints, `08_UI` §Settings, HANDOFF §P4.
|
||||
- **P4 PR-1 — the detection rules engine wired into the Agent, and the Supports row (2026-09-14).** The engine,
|
||||
schema, validator and fixture corpus existed since P0 with no production caller and no writer. Now:
|
||||
`Application.Detection.DetectionSweep` runs `StaticGameDetector` over the real `GameFileProbe` for every game in
|
||||
|
||||
@@ -171,6 +171,14 @@ Files shipped with a game tell us what it *supports*. These populate a **"Suppor
|
||||
- FSR `ffx_fsr2_*.dll`, `ffx_frameinterpolation_*.dll`, `amd_fidelityfx_*.dll`, `ffx_api*.dll` — a hint still, even though `amd_fidelityfx_dx12.dll` / `_upscaler_dx12.dll` / `_framegeneration_dx12.dll` are *hooked* since 2026-09-04: the measured chip comes from the dispatch, never from the file
|
||||
- XeSS `libxess.dll`, XeFG `libxess_fg.dll`
|
||||
- DXR-capable: `d3d12.dll` usage + RT-capable GPU (capability only — says nothing about the game)
|
||||
- **Vulkan (since P4 PR-2, 2026-09-14) — a code-level fact, not a rule.** The rules can only ask about files
|
||||
beside the executable, and the Vulkan loader is not one of them (`vulkan-1.dll` lives in System32). So
|
||||
`GameFileProbe` reads the executable's import and delay-load tables (`Infrastructure.Detection.PeImports`,
|
||||
bounded and read-only) and looks for the loader's name as an ASCII or UTF-16 string in the bounded scan;
|
||||
`StaticDetectionResult.UsesVulkan` is true / false / null (could not read), and the sweep stores a true as the
|
||||
id `vulkan` in `capability_flags` beside the rule ids. It is what `17_HOOK_ENGINE` §Vulkan's register-on-consent
|
||||
automation keys on, and what the game page shows as "Supports Vulkan". Never a claim about what a session
|
||||
presented — that is `sessions.api`, measured.
|
||||
|
||||
The UI wording is deliberate: **"Supports DLSS-G"** (capability, from files) versus **"Frame Generation: DLSS-G ×1.9"** (measured, from this session). Users conflating these is exactly the confusion the old design created.
|
||||
|
||||
|
||||
+4
-1
@@ -262,7 +262,10 @@ Agent section: elevation state with a plain explanation of what elevation *optio
|
||||
> `FrameLedger.Agent.exe --register-vklayer` / `--unregister-vklayer` / `--install-task` / `--uninstall-task`)
|
||||
> and then re-reads the machine (`IMaintenanceState`: the HKCU key, Task Scheduler) — the text shown is what the
|
||||
> machine holds, never what the button assumed. Register is enabled only while the layer DLL is staged, the
|
||||
> registration is absent and a game has hooking on (the same rule the Agent's flag enforces); Repair appears
|
||||
> registration is absent and ~~a game has hooking on~~ **a hook-enabled game references the Vulkan loader (P4 PR-2,
|
||||
> 2026-09-14: `HookedGameViewModel.UsesVulkan` from `capability_flags`)** (the same rule the Agent's reconciler
|
||||
> enforces on its own after every consent change and every sweep — the button is the repair tool, `12_BUILD`
|
||||
> §The Vulkan layer is not registered at install time); Repair appears
|
||||
> when the task's action names another path (a moved install). "Minimize to tray on close" is honoured.
|
||||
|
||||
### First-run flow
|
||||
|
||||
@@ -128,6 +128,13 @@ the `--register-vklayer` Agent flag (§Agent flags — a manual repair tool, not
|
||||
normal path), and the Settings button (`08_UI` §Settings — it reflects and
|
||||
repairs state, it does not grant machine-wide reach on its own).
|
||||
|
||||
> **Enforced 2026-09-14 (P4 PR-2).** "A Vulkan game" is a static fact of the executable — it imports or
|
||||
> `LoadLibrary`s `vulkan-1.dll` — read by the Agent's detection sweep into `capability_flags` as `vulkan`
|
||||
> (`17_HOOK_ENGINE` §Vulkan built note). `Application.Vulkan.VkLayerReconciler` registers when the first
|
||||
> hook-enabled game carries it and unregisters when the last one is disabled, after every consent change and
|
||||
> after every sweep; the flag and the button run the same rule. The uninstall hook is still the updater's
|
||||
> (P4, Velopack).
|
||||
|
||||
## Publish & package
|
||||
|
||||
```
|
||||
|
||||
+18
-2
@@ -399,9 +399,25 @@ is not something this loader supports.
|
||||
> (`%LOCALAPPDATA%\FrameLedger\vklayer\VkLayer_FRAMELEDGER_overlay.json`, written by the same code the launch
|
||||
> path uses); the Agent's `--register-vklayer` refuses unless a game has hooking enabled, `--unregister-vklayer`
|
||||
> also removes a stale value naming our manifest elsewhere, and `HelloAck.vulkanLayerRegistered` reads the key
|
||||
> at the Agent's start. Two things this build does **not** do, stated rather than implied: (1) the automatic
|
||||
> at the Agent's start. Two things this build does **not** do, stated rather than implied: ~~(1) the automatic
|
||||
> register-on-first-enable / unregister-on-last-disable needs to know which enabled game is a *Vulkan* title,
|
||||
> and the ledger does not hold that fact until P4's capability flags — so the check is "any enabled game"; (2)
|
||||
> and the ledger does not hold that fact until P4's capability flags — so the check is "any enabled game"~~
|
||||
> **— closed 2026-09-14 (P4 PR-2).** The fact is static and lives in `capability_flags` under the id `vulkan`:
|
||||
> `GameFileProbe` reads the executable's import and delay-load tables (`Infrastructure.Detection.PeImports`, bounded,
|
||||
> read-only) and looks for `vulkan-1.dll` as an ASCII or UTF-16 string in the bounded scan (a `LoadLibraryW`
|
||||
> loader — the harness's shape and many titles'); null when the file could not be read, never "no". A static
|
||||
> fact was chosen over the runtime one on purpose: the NVIDIA ICD maps `dxgi.dll` + `d3d12.dll` itself (the
|
||||
> 2026-09-06 note above), so runtime module presence is the weaker discriminator, and the automation has to act
|
||||
> at consent time, before the title ever runs. `Application.Vulkan.VkLayerReconciler` computes the desired
|
||||
> registration from the ledger — hook-enabled games whose flags carry `vulkan` — and moves the HKCU value to it,
|
||||
> called after every consent change the pipe handler and the console verbs make and after every detection
|
||||
> sweep (so a guard block, the crash policy's auto-disable, and a Vulkan fact that arrives after the consent all
|
||||
> converge within one 15 s interval). `--register-vklayer` runs the same reconciler and refuses when it finds no
|
||||
> such game; the Settings button follows the same rule (`HookedGameViewModel.UsesVulkan`). Not staged = nothing
|
||||
> to do — and **an Agent off the profile ledger (`--data-dir`) gets an inert registrar**, so the e2e suites'
|
||||
> consent for `hook-harness` (which `LoadLibraryW`s the loader and therefore reads as Vulkan) never reaches the
|
||||
> developer's HKCU (D17's shape). `VkLayerReconcilerTests`, `PeImportsTests` (a synthetic PE32+, both directories, the wide
|
||||
> literal, a malformed file). (2)
|
||||
> a registration buys nothing today: the layer gates on `FRAMELEDGER_ENABLE_VK_LAYER=1`, which only a launch
|
||||
> sets, and a launch already reaches the layer through `VK_ADD_IMPLICIT_LAYER_PATH`. Registration becomes
|
||||
> useful the day background capture sets the variable for a tracked Vulkan title started elsewhere, and not
|
||||
|
||||
+5
-2
@@ -1229,8 +1229,11 @@ filled — status in `CHANGELOG.md`, the decisions in `05_DETECTION` §Caching's
|
||||
itch.io — the first-run flow's step 4 and File ▸ Import library both say "later build"), ~~the
|
||||
capability-vs-measured separation in the UI (the game page's Supports row is empty until this)~~ **(PR-1)**, Velopack +
|
||||
the updater (`11_UPDATER`; the Settings channel row is stored and unused), the bug-report flow's steps 3–5
|
||||
(`10_LOGGING`: the preview dialog, the GitHub issue link — step 2's bundle exists), the "is Vulkan" fact the
|
||||
layer's register/unregister-on-consent automation needs (`17_HOOK_ENGINE` §Vulkan built note), the Help menu's
|
||||
(`10_LOGGING`: the preview dialog, the GitHub issue link — step 2's bundle exists), ~~the "is Vulkan" fact the
|
||||
layer's register/unregister-on-consent automation needs (`17_HOOK_ENGINE` §Vulkan built note)~~ **LANDED
|
||||
2026-09-14 (P4 PR-2): a static PE fact (`PeImports` + the bounded scan) stored as `vulkan` in `capability_flags`,
|
||||
and `VkLayerReconciler` moving the HKCU registration after every consent change and sweep — the built note
|
||||
carries it**, the Help menu's
|
||||
Documentation / Check for updates / Report a bug items, and `legal/licenses/` populated by the license-gathering
|
||||
script. Decisions that live only here: D11–D17 below still hold; nothing in P4 may add a third writer to
|
||||
`ledger.db` or a message that carries a safety fact over the pipe.
|
||||
|
||||
@@ -13,6 +13,13 @@ internal sealed record AgentPaths(string DataDirectory)
|
||||
{
|
||||
public static AgentPaths Default => new(LedgerPaths.DefaultDirectory);
|
||||
|
||||
/// <summary>
|
||||
/// The profile ledger (<c>%LOCALAPPDATA%\FrameLedger</c>) rather than a <c>--data-dir</c>: machine-wide side effects —
|
||||
/// the Vulkan layer's HKCU registration (P4 PR-2) — are taken only here, so a test or developer ledger never
|
||||
/// reaches the user's registry (HANDOFF D6/D17's shape).
|
||||
/// </summary>
|
||||
public bool IsProfile => string.Equals(Path.GetFullPath(DataDirectory), Path.GetFullPath(LedgerPaths.DefaultDirectory), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public string Database => Path.Combine(DataDirectory, LedgerPaths.DatabaseFileName);
|
||||
|
||||
public string Tmp => Path.Combine(DataDirectory, "tmp");
|
||||
|
||||
@@ -3,6 +3,7 @@ using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Vulkan;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Domain.AntiCheat;
|
||||
using FrameLedger.Domain.Consent;
|
||||
@@ -101,6 +102,11 @@ internal sealed class ConsoleVerbs(IServiceProvider services, AgentPaths paths)
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
AgentConsole.Line($"consent: {outcome}");
|
||||
if (outcome == ConsentWriteOutcome.Written)
|
||||
{
|
||||
_ = await Get<VkLayerReconciler>().ReconcileAsync().ConfigureAwait(false); // P4 PR-2: the developer path follows the same layer rule
|
||||
}
|
||||
|
||||
return outcome == ConsentWriteOutcome.Written ? _exitOk : _exitRefused;
|
||||
}
|
||||
|
||||
@@ -110,6 +116,7 @@ internal sealed class ConsoleVerbs(IServiceProvider services, AgentPaths paths)
|
||||
.RevokeAsync(ExecutableIdentity.Normalise(exePath))
|
||||
.ConfigureAwait(false);
|
||||
AgentConsole.Line($"revoke: {outcome}");
|
||||
_ = await Get<VkLayerReconciler>().ReconcileAsync().ConfigureAwait(false);
|
||||
return outcome is ConsentWriteOutcome.Written or ConsentWriteOutcome.NotFound ? _exitOk : _exitRefused;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Application.Vulkan;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
using FrameLedger.Infrastructure.Startup;
|
||||
using FrameLedger.Infrastructure.Vulkan;
|
||||
@@ -41,16 +41,24 @@ internal sealed class MaintenanceVerbs(LedgerDatabase db, AgentPaths paths)
|
||||
return _exitUsage;
|
||||
}
|
||||
|
||||
IReadOnlyList<GameConsentRecord> enabled = await new SqliteGameConsentStore(db).ListEnabledAsync().ConfigureAwait(false);
|
||||
if (enabled.Count == 0)
|
||||
// The same rule the Agent applies on its own (P4 PR-2, VkLayerReconciler): registered only while a hook-enabled
|
||||
// game references the Vulkan loader. The flag is the repair tool for that state, never a way past it.
|
||||
IVkLayerRegistrar registrar = Composition.AgentServices.Registrar(paths);
|
||||
var reconciler = new VkLayerReconciler(new SqliteGameConsentStore(db), new SqliteGameRepository(db), registrar, AgentConsole.Line);
|
||||
VkLayerReconcileOutcome outcome = await reconciler.ReconcileAsync().ConfigureAwait(false);
|
||||
if (!outcome.Staged)
|
||||
{
|
||||
AgentConsole.Problem("vklayer: refused — no game has hooking enabled, and the layer is registered only while one does (12_BUILD §The Vulkan layer is not registered at install time)");
|
||||
AgentConsole.Problem("vklayer: refused — this Agent does not run over the profile ledger (--data-dir), and a test or developer ledger never registers anything in HKCU");
|
||||
return _exitRefused;
|
||||
}
|
||||
|
||||
string manifest = VkLayerLaunchEnvironment.WriteManifest(paths.VkLayerDirectory, AgentPaths.VkLayerDll);
|
||||
new VkLayerRegistration().Register(manifest);
|
||||
AgentConsole.Line($"vklayer: registered {manifest} under HKCU\\{VkLayerRegistration.DefaultKeyPath} (this user; inert in any process without {VkLayerLaunchEnvironment.EnableVariable}=1)");
|
||||
if (!outcome.Desired)
|
||||
{
|
||||
AgentConsole.Problem("vklayer: refused — no hook-enabled game references the Vulkan loader, and the layer is registered only while one does (12_BUILD §The Vulkan layer is not registered at install time)");
|
||||
return _exitRefused;
|
||||
}
|
||||
|
||||
AgentConsole.Line($"vklayer: registered {ManifestPath} under HKCU\\{VkLayerRegistration.DefaultKeyPath} (this user; inert in any process without {VkLayerLaunchEnvironment.EnableVariable}=1){(outcome.Changed ? string.Empty : " — already was")}");
|
||||
return _exitOk;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Rules;
|
||||
using FrameLedger.Application.Settings;
|
||||
using FrameLedger.Application.Vulkan;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Infrastructure.AntiCheat;
|
||||
using FrameLedger.Infrastructure.Blobs;
|
||||
@@ -19,6 +20,7 @@ using FrameLedger.Infrastructure.Recording;
|
||||
using FrameLedger.Infrastructure.Rules;
|
||||
using FrameLedger.Infrastructure.Settings;
|
||||
using FrameLedger.Infrastructure.Telemetry;
|
||||
using FrameLedger.Infrastructure.Vulkan;
|
||||
using FrameLedger.Infrastructure.Watch;
|
||||
using FrameLedger.Shared.Ipc;
|
||||
using FrameLedger.Shared.Safety;
|
||||
@@ -94,7 +96,7 @@ internal static class AgentServices
|
||||
services.AddSingleton<IProcessSnapshotSource, ToolhelpProcessSnapshotSource>();
|
||||
services.AddSingleton<IExecutableIdentitySource, ExecutableIdentitySource>();
|
||||
|
||||
AddDetection(services);
|
||||
AddDetection(services, paths);
|
||||
services.AddSingleton<ISessionRecorder>(static sp => sp.GetRequiredService<AgentRecording>().Recorder(seconds: 0, launcher: null));
|
||||
|
||||
AddPipe(services, pipeName);
|
||||
@@ -103,7 +105,7 @@ internal static class AgentServices
|
||||
}
|
||||
|
||||
/// <summary>The static detection sweep (P4 PR-1, <c>05_DETECTION</c> §Caching): hosted under <c>--serve</c> only, composed and inert under <c>--console</c>.</summary>
|
||||
private static void AddDetection(IServiceCollection services)
|
||||
private static void AddDetection(IServiceCollection services, AgentPaths paths)
|
||||
{
|
||||
// The static detection sweep (P4 PR-1, 05_DETECTION §Caching): the rules file RulesSeeder seeds (the two
|
||||
// paths agree, RulesPathAgreementTests), the real probe, and the sweep over the games table. Hosted under
|
||||
@@ -116,8 +118,23 @@ internal static class AgentServices
|
||||
sp.GetRequiredService<IGameFileProbe>(),
|
||||
sp.GetRequiredService<IExecutableIdentitySource>(),
|
||||
static line => Serilog.Log.Information("{Line}", line)));
|
||||
|
||||
// The layer's registration follows the ledger (P4 PR-2, 12_BUILD §The Vulkan layer is not registered at
|
||||
// install time): the same manifest and key --register-vklayer writes, reconciled after every consent change
|
||||
// the handler makes and after every sweep.
|
||||
// Inert off the profile ledger: a --data-dir Agent (tests, developers) never touches the user's HKCU.
|
||||
services.AddSingleton<IVkLayerRegistrar>(_ => Registrar(paths));
|
||||
services.AddSingleton(static sp => new VkLayerReconciler(
|
||||
sp.GetRequiredService<IGameConsentStore>(),
|
||||
sp.GetRequiredService<IGameRepository>(),
|
||||
sp.GetRequiredService<IVkLayerRegistrar>(),
|
||||
static line => Serilog.Log.Information("{Line}", line)));
|
||||
}
|
||||
|
||||
/// <summary>The layer registrar for <paramref name="paths"/>: the real HKCU one over the profile ledger, inert anywhere else (P4 PR-2).</summary>
|
||||
internal static IVkLayerRegistrar Registrar(AgentPaths paths) =>
|
||||
paths.IsProfile ? new VkLayerRegistrar(paths.VkLayerDirectory, AgentPaths.VkLayerDll) : new InertVkLayerRegistrar();
|
||||
|
||||
/// <summary>
|
||||
/// The pipe, read half (P3 PR-1, <c>07_IPC</c> §C, HANDOFF §P3 D11–D13). Events leave through <c>SessionEventPublisher</c>,
|
||||
/// the recorder's observer; requests are answered by <c>AgentRequestHandler</c>; the server itself is started by
|
||||
@@ -150,7 +167,8 @@ internal static class AgentServices
|
||||
},
|
||||
// P3 PR-4 (D14): the reviewed disclosure this Agent stamps against, and its own clock for the stamp.
|
||||
SafetyDisclosure.Version,
|
||||
TimeProvider.System));
|
||||
TimeProvider.System,
|
||||
sp.GetRequiredService<VkLayerReconciler>()));
|
||||
services.AddSingleton<IIpcRequestHandler>(static sp => new AgentRequestHandler(
|
||||
AgentIdentityFactory.OfThisProcess(sp.GetRequiredService<AgentPaths>().VkLayerDirectory),
|
||||
TelemetryDescriptor(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using FrameLedger.Application.Detection;
|
||||
using FrameLedger.Application.Vulkan;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Serilog;
|
||||
|
||||
@@ -16,7 +17,7 @@ namespace FrameLedger.Agent.Hosting;
|
||||
/// A sweep that throws is logged and retried on the next tick rather than ending the service — a game's
|
||||
/// directory going away mid-walk is ordinary, and one bad game must not stop the scan of the rest.
|
||||
/// </remarks>
|
||||
internal sealed class DetectionHostedService(DetectionSweep sweep) : BackgroundService
|
||||
internal sealed class DetectionHostedService(DetectionSweep sweep, VkLayerReconciler layer) : BackgroundService
|
||||
{
|
||||
/// <summary>The idle cadence. A game the App just added is seen within this; a rules update wakes the loop at once.</summary>
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromSeconds(15);
|
||||
@@ -34,6 +35,10 @@ internal sealed class DetectionHostedService(DetectionSweep sweep) : BackgroundS
|
||||
Log.Information("detect: sweep scanned {Scanned}, current {Current}, unreadable {Unreadable}{Rules}",
|
||||
r.Scanned, r.Current, r.Unreadable, r.RulesUnusable ? ", rules unusable" : string.Empty);
|
||||
}
|
||||
|
||||
// The layer follows the ledger after every sweep (P4 PR-2): a Vulkan fact that arrived after the
|
||||
// consent, and the crash policy's auto-disable, both converge here within one interval.
|
||||
_ = await layer.ReconcileAsync(stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
|
||||
@@ -1674,7 +1674,7 @@
|
||||
<comment>review</comment>
|
||||
</data>
|
||||
<data name="Settings_VkLayer_Note" xml:space="preserve">
|
||||
<value>登録すると、このユーザーのすべての Vulkan プロセスにレイヤーが読み込まれますが、FrameLedger が起動したプロセス以外では何もしません。FrameLedger からの起動には登録は不要です。ボタンは状態を修復するもので、フックが有効なゲームがある間のみ使用できます。</value>
|
||||
<value>登録すると、このユーザーのすべての Vulkan プロセスにレイヤーが読み込まれますが、FrameLedger が起動したプロセス以外では無効のままです。FrameLedger からの起動に登録は不要です。フック有効なゲームが Vulkan ローダーを参照している間はキャプチャエージェントが自動で登録し、最後の 1 本が無効化されると解除します。ボタンはその状態を修復するもので、同じ規則の下でのみ使えます。</value>
|
||||
<comment>review</comment>
|
||||
</data>
|
||||
<data name="Settings_VkLayer_Register" xml:space="preserve">
|
||||
|
||||
@@ -1261,7 +1261,7 @@
|
||||
<value>The layer DLL is not beside the capture agent; there is nothing to register.</value>
|
||||
</data>
|
||||
<data name="Settings_VkLayer_Note" xml:space="preserve">
|
||||
<value>Registration puts the layer into every Vulkan process of this user, where it stays inert unless FrameLedger launched that process. Launching from FrameLedger needs no registration; the buttons repair state and are allowed only while a game has hooking on.</value>
|
||||
<value>Registration puts the layer into every Vulkan process of this user, where it stays inert unless FrameLedger launched that process. Launching from FrameLedger needs no registration. The capture agent registers the layer on its own while a hook-enabled game references the Vulkan loader and removes it when the last one is disabled; the buttons repair that state and are allowed only under the same rule.</value>
|
||||
</data>
|
||||
<data name="Settings_VkLayer_Register" xml:space="preserve">
|
||||
<value>Register</value>
|
||||
|
||||
@@ -1256,7 +1256,7 @@
|
||||
<value>Không có DLL lớp bên cạnh capture agent; không có gì để đăng ký.</value>
|
||||
</data>
|
||||
<data name="Settings_VkLayer_Note" xml:space="preserve">
|
||||
<value>Đăng ký đưa lớp vào mọi tiến trình Vulkan của người dùng này, ở đó nó bất hoạt trừ khi FrameLedger khởi chạy tiến trình đó. Khởi chạy từ FrameLedger không cần đăng ký; các nút chỉ sửa trạng thái và chỉ được phép khi có game đang bật hooking.</value>
|
||||
<value>Đăng ký đưa lớp vào mọi tiến trình Vulkan của người dùng này, ở đó nó bất hoạt trừ khi FrameLedger khởi chạy tiến trình đó. Khởi chạy từ FrameLedger không cần đăng ký. Agent ghi tự đăng ký lớp khi có game bật hooking tham chiếu bộ nạp Vulkan và gỡ khi game cuối cùng bị tắt; các nút chỉ sửa lại trạng thái đó và chỉ được phép theo cùng quy tắc.</value>
|
||||
</data>
|
||||
<data name="Settings_VkLayer_Register" xml:space="preserve">
|
||||
<value>Đăng ký</value>
|
||||
|
||||
@@ -566,6 +566,7 @@ public sealed partial class GameDetailViewModel : ObservableObject
|
||||
"dlssg" or "dlss_g" => "DLSS-G",
|
||||
"dlssd" or "dlss_rr" => "DLSS Ray Reconstruction",
|
||||
"streamline" => "Streamline",
|
||||
"vulkan" => "Vulkan",
|
||||
"fsr" => "FSR",
|
||||
"fsrfg" => "FSR Frame Generation",
|
||||
"xess" => "XeSS",
|
||||
|
||||
@@ -3,10 +3,13 @@ using CommunityToolkit.Mvvm.Input;
|
||||
namespace FrameLedger.App.ViewModels;
|
||||
|
||||
/// <summary>One row of the Settings page's "games with hooking on" list (FR-10): the name and the per-game revoke.</summary>
|
||||
public sealed partial class HookedGameViewModel(long gameId, string name, Func<HookedGameViewModel, Task> revoke)
|
||||
public sealed partial class HookedGameViewModel(long gameId, string name, Func<HookedGameViewModel, Task> revoke, bool usesVulkan = false)
|
||||
{
|
||||
public long GameId { get; } = gameId;
|
||||
|
||||
/// <summary>The row's <c>capability_flags</c> carries <c>vulkan</c> (P4 PR-2): the layer is this game's capture side, and its registration follows this.</summary>
|
||||
public bool UsesVulkan { get; } = usesVulkan;
|
||||
|
||||
public string Name { get; } = name ?? throw new ArgumentNullException(nameof(name));
|
||||
|
||||
[RelayCommand]
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.IO;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using FrameLedger.App.Services;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Settings;
|
||||
using FrameLedger.Infrastructure.Startup;
|
||||
|
||||
@@ -171,8 +172,8 @@ public sealed partial class SettingsViewModel : ObservableObject
|
||||
|
||||
public string KillSwitchState => KillSwitch ? Strings.Settings_KillSwitch_On : Strings.Settings_KillSwitch_Off;
|
||||
|
||||
/// <summary>12_BUILD: the registration exists only while a game has hooking on — the button follows the same rule as the Agent's flag.</summary>
|
||||
public bool CanRegisterLayer => MaintenanceSnapshot.LayerStaged && !MaintenanceSnapshot.LayerRegistered && HookedGames.Count > 0;
|
||||
/// <summary>12_BUILD: the registration exists only while a hook-enabled game references the Vulkan loader (P4 PR-2) — the button follows the same rule as the Agent's reconciler.</summary>
|
||||
public bool CanRegisterLayer => MaintenanceSnapshot.LayerStaged && !MaintenanceSnapshot.LayerRegistered && HookedGames.Any(static g => g.UsesVulkan);
|
||||
|
||||
public bool CanUnregisterLayer => MaintenanceSnapshot.LayerRegistered;
|
||||
|
||||
@@ -346,7 +347,7 @@ public sealed partial class SettingsViewModel : ObservableObject
|
||||
HookedGames.Clear();
|
||||
foreach (GameCard card in cards.Where(static c => c.Row.HookEnabled && c.Row.InLibrary).OrderBy(static c => c.Row.Name, StringComparer.CurrentCultureIgnoreCase))
|
||||
{
|
||||
HookedGames.Add(new HookedGameViewModel(card.Row.Id, card.Row.Name, RevokeAsync));
|
||||
HookedGames.Add(new HookedGameViewModel(card.Row.Id, card.Row.Name, RevokeAsync, CapabilityFlags.Contains(card.Row.CapabilityFlagsJson, "vulkan")));
|
||||
}
|
||||
|
||||
Shared.Ipc.HelloAck? hello = _agent.Hello;
|
||||
|
||||
@@ -100,12 +100,17 @@ public sealed class DetectionSweep : IDisposable
|
||||
}
|
||||
|
||||
StaticDetectionResult r = await _detector.DetectAsync(game.Fingerprint.ExePath, ct).ConfigureAwait(false);
|
||||
// The Vulkan fact rides in capability_flags under its own id (P4 PR-2): not a rule id, stored beside them
|
||||
// so one column says what the game ships AND whether the layer is its capture side.
|
||||
IReadOnlyList<string> capabilities = r.UsesVulkan == true
|
||||
? [.. r.CapabilityIds, StaticDetectionResult.VulkanCapabilityId]
|
||||
: r.CapabilityIds;
|
||||
var write = new DetectionWrite
|
||||
{
|
||||
EngineId = r.EngineId,
|
||||
EngineVersion = r.EngineVersion,
|
||||
PlatformId = r.PlatformId,
|
||||
CapabilityIds = r.CapabilityIds,
|
||||
CapabilityIds = capabilities,
|
||||
RulesVersion = r.RulesVersion,
|
||||
ExeSizeBytes = onDisk.SizeBytes,
|
||||
ExeMtimeMs = onDisk.MtimeUnixMs,
|
||||
@@ -115,7 +120,7 @@ public sealed class DetectionSweep : IDisposable
|
||||
scanned++;
|
||||
_log($"detect: {game.Name} — engine={r.EngineId ?? (r.EngineUndetermined ? "undetermined" : "none")}"
|
||||
+ $"{(r.EngineVersion is null ? string.Empty : " " + r.EngineVersion)} platform={r.PlatformId ?? (r.PlatformUndetermined ? "undetermined" : "none")}"
|
||||
+ $" capabilities=[{string.Join(",", r.CapabilityIds)}] rules={r.RulesVersion}");
|
||||
+ $" capabilities=[{string.Join(",", capabilities)}] vulkan={(r.UsesVulkan is { } v ? (v ? "yes" : "no") : "unknown")} rules={r.RulesVersion}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ public sealed class StaticGameDetector(IDetectionRulesSource rulesSource, IGameF
|
||||
PlatformUndetermined = platformUndetermined,
|
||||
CapabilityIds = [.. evaluator.MatchCapabilities(snapshot).Select(c => c.Id)],
|
||||
RulesVersion = rules.RulesVersion,
|
||||
UsesVulkan = snapshot.VulkanLoaderReferenced,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Vulkan;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Domain.AntiCheat;
|
||||
using FrameLedger.Domain.Consent;
|
||||
@@ -31,6 +32,7 @@ public sealed class AgentCommandHandler
|
||||
private readonly Func<CancellationToken, ValueTask<string>> _updateRules;
|
||||
private readonly string? _disclosureVersion;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly VkLayerReconciler? _layer;
|
||||
|
||||
/// <summary>
|
||||
/// <c>disclosureVersion</c> is the version of FR-2.1's reviewed disclosure this Agent carries
|
||||
@@ -39,9 +41,12 @@ public sealed class AgentCommandHandler
|
||||
/// </summary>
|
||||
public AgentCommandHandler(IGameRepository games, IGameConsentStore consent, IAntiCheatGuard guard, IExecutableIdentitySource identity,
|
||||
CaptureOrchestrator orchestrator, CapturePause pause, IAgentLifetime lifetime, Func<CancellationToken, ValueTask<string>> updateRules,
|
||||
string? disclosureVersion = null, TimeProvider? clock = null)
|
||||
string? disclosureVersion = null, TimeProvider? clock = null, VkLayerReconciler? layer = null)
|
||||
{
|
||||
_clock = clock ?? TimeProvider.System;
|
||||
// P4 PR-2: the layer's registration follows every consent change this handler makes (12_BUILD §The Vulkan
|
||||
// layer is not registered at install time); null in tests that do not care, and the sweep reconciles anyway.
|
||||
_layer = layer;
|
||||
_games = games ?? throw new ArgumentNullException(nameof(games));
|
||||
_consent = consent ?? throw new ArgumentNullException(nameof(consent));
|
||||
_guard = guard ?? throw new ArgumentNullException(nameof(guard));
|
||||
@@ -143,6 +148,7 @@ public sealed class AgentCommandHandler
|
||||
if (!payload.Enabled)
|
||||
{
|
||||
ConsentWriteOutcome revoked = await _consent.RevokeAsync(path, ct).ConfigureAwait(false);
|
||||
await ReconcileLayerAsync(ct).ConfigureAwait(false);
|
||||
return IpcCodec.Encode(IpcMessageType.HookEnabledAck, request.Id, new HookEnabledAck(game.Id, Enabled: false, revoked.ToString(), Prescan: null));
|
||||
}
|
||||
|
||||
@@ -159,6 +165,7 @@ public sealed class AgentCommandHandler
|
||||
// A refusal, or a scan that reached no answer: the store records which (a default verdict is
|
||||
// "could not verify", never a block), and both are answered as a refusal to enable.
|
||||
await _consent.RecordGuardBlockAsync(fingerprint.Value, verdict, ct).ConfigureAwait(false);
|
||||
await ReconcileLayerAsync(ct).ConfigureAwait(false);
|
||||
string reason = verdict.Reason == AntiCheatRefusalReason.Allow ? "PreScanCouldNotVerify" : verdict.Reason.ToString();
|
||||
return IpcCodec.Encode(IpcMessageType.Refused, request.Id,
|
||||
new RefusedAck(game.Id, reason, NullIfEmpty(verdict.Family), NullIfEmpty(verdict.Signal)));
|
||||
@@ -196,10 +203,23 @@ public sealed class AgentCommandHandler
|
||||
AcknowledgedAt = _clock.GetUtcNow(),
|
||||
Provenance = ConsentProvenance.ConsentDialog,
|
||||
}, ct).ConfigureAwait(false);
|
||||
if (outcome == ConsentWriteOutcome.Written)
|
||||
{
|
||||
await ReconcileLayerAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return IpcCodec.Encode(IpcMessageType.HookEnabledAck, request.Id,
|
||||
new HookEnabledAck(game.Id, Enabled: outcome == ConsentWriteOutcome.Written, outcome.ToString(), Prescan: "clean"));
|
||||
}
|
||||
|
||||
private async ValueTask ReconcileLayerAsync(CancellationToken ct)
|
||||
{
|
||||
if (_layer is not null)
|
||||
{
|
||||
_ = await _layer.ReconcileAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] Stop(IpcEnvelope request)
|
||||
{
|
||||
StopSessionRequest? payload = IpcCodec.Payload<StopSessionRequest>(request);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace FrameLedger.Application.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Reads <c>games.capability_flags</c> (P4 PR-1: a JSON array of ids; older rows: an object of booleans) without a
|
||||
/// serializer context, for the one question the Agent asks of it: does the row carry a given id?
|
||||
/// </summary>
|
||||
public static class CapabilityFlags
|
||||
{
|
||||
/// <summary>True when <paramref name="json"/> names <paramref name="id"/> (an array member, or an object key set to true). Unreadable JSON is no.</summary>
|
||||
public static bool Contains(string? json, string id)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(id);
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement e in root.EnumerateArray())
|
||||
{
|
||||
if (e.ValueKind == JsonValueKind.String && string.Equals(e.GetString(), id, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return root.ValueKind == JsonValueKind.Object
|
||||
&& root.TryGetProperty(id, out JsonElement flag)
|
||||
&& flag.ValueKind == JsonValueKind.True;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace FrameLedger.Application.Vulkan;
|
||||
|
||||
/// <summary>
|
||||
/// The Vulkan layer's per-user registration (<c>17_HOOK_ENGINE</c> §Vulkan: the HKCU <c>ImplicitLayers</c> value),
|
||||
/// as a port so <see cref="VkLayerReconciler"/> can be tested without a registry. The adapter is
|
||||
/// <c>Infrastructure.Vulkan.VkLayerRegistrar</c>.
|
||||
/// </summary>
|
||||
public interface IVkLayerRegistrar
|
||||
{
|
||||
/// <summary>The layer DLL is beside the Agent; without it there is nothing to register and the reconciler does nothing.</summary>
|
||||
bool IsStaged { get; }
|
||||
|
||||
bool IsRegistered();
|
||||
|
||||
/// <summary>Write the manifest for the staged DLL and register it.</summary>
|
||||
void Register();
|
||||
|
||||
/// <summary>Remove the registration; true when something was removed.</summary>
|
||||
bool Unregister();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace FrameLedger.Application.Vulkan;
|
||||
|
||||
/// <summary>
|
||||
/// The registrar an Agent gets when it does not run over the profile ledger (<c>--data-dir</c>, the test and
|
||||
/// developer shape — HANDOFF D6/D17): a synthetic ledger's consents must never reach the user's HKCU, so the
|
||||
/// layer reads as not staged and the reconciler does nothing. The e2e suites grant consent to <c>hook-harness</c>,
|
||||
/// which references the Vulkan loader, and this is what keeps that grant off the developer's registry.
|
||||
/// </summary>
|
||||
public sealed class InertVkLayerRegistrar : IVkLayerRegistrar
|
||||
{
|
||||
public bool IsStaged => false;
|
||||
|
||||
public bool IsRegistered() => false;
|
||||
|
||||
public void Register()
|
||||
{
|
||||
}
|
||||
|
||||
public bool Unregister() => false;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace FrameLedger.Application.Vulkan;
|
||||
|
||||
/// <summary>What one pass found and did.</summary>
|
||||
/// <param name="Desired">Whether the ledger says the layer should be registered.</param>
|
||||
/// <param name="Registered">The registration after the pass.</param>
|
||||
/// <param name="Changed">Whether the pass registered or unregistered.</param>
|
||||
/// <param name="VulkanGamesEnabled">Hook-enabled games whose flags carry <c>vulkan</c>.</param>
|
||||
/// <param name="Staged">Whether the layer DLL is beside the Agent at all.</param>
|
||||
public sealed record VkLayerReconcileOutcome(bool Desired, bool Registered, bool Changed, int VulkanGamesEnabled, bool Staged);
|
||||
@@ -0,0 +1,67 @@
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Domain.Detection;
|
||||
|
||||
namespace FrameLedger.Application.Vulkan;
|
||||
|
||||
/// <summary>
|
||||
/// The rule <c>12_BUILD</c> §The Vulkan layer is not registered at install time states and nothing enforced until P4
|
||||
/// PR-2: the layer is registered <b>only while at least one hook-enabled game references the Vulkan loader</b>, and
|
||||
/// unregistered when the last such game is disabled. One idempotent pass computes the desired state from the
|
||||
/// ledger — the consent store's enabled games joined to their <c>capability_flags</c> — and moves the registration
|
||||
/// to it. Called after every consent change the Agent makes and after every detection sweep, so the three ways
|
||||
/// <c>hook_enabled</c> can drop (revoke, a guard block, the crash policy) and a Vulkan fact that arrives after the
|
||||
/// consent all converge within a sweep.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A game whose flags carry no <c>vulkan</c> id is not a Vulkan title as far as this rule can tell — never scanned
|
||||
/// yet reads the same as scanned-and-no. That is the fail-safe direction: the layer is machine-wide reach, and
|
||||
/// a launch reaches it without any registration (<c>VK_ADD_IMPLICIT_LAYER_PATH</c>), so an unregistered layer
|
||||
/// costs nothing that a launch needs.
|
||||
/// </remarks>
|
||||
public sealed class VkLayerReconciler(IGameConsentStore consent, IGameRepository games, IVkLayerRegistrar registrar, Action<string> log)
|
||||
{
|
||||
private readonly IGameConsentStore _consent = consent ?? throw new ArgumentNullException(nameof(consent));
|
||||
private readonly IGameRepository _games = games ?? throw new ArgumentNullException(nameof(games));
|
||||
private readonly IVkLayerRegistrar _registrar = registrar ?? throw new ArgumentNullException(nameof(registrar));
|
||||
private readonly Action<string> _log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
|
||||
public async ValueTask<VkLayerReconcileOutcome> ReconcileAsync(CancellationToken ct = default)
|
||||
{
|
||||
int vulkanEnabled = 0;
|
||||
foreach (GameConsentRecord record in await _consent.ListEnabledAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
GameRow? game = await _games.FindAsync(record.Fingerprint.ExePath, ct).ConfigureAwait(false);
|
||||
if (game is not null && CapabilityFlags.Contains(game.CapabilityFlagsJson, StaticDetectionResult.VulkanCapabilityId))
|
||||
{
|
||||
vulkanEnabled++;
|
||||
}
|
||||
}
|
||||
|
||||
bool desired = vulkanEnabled > 0;
|
||||
if (!_registrar.IsStaged)
|
||||
{
|
||||
return new VkLayerReconcileOutcome(desired, Registered: false, Changed: false, VulkanGamesEnabled: vulkanEnabled, Staged: false);
|
||||
}
|
||||
|
||||
bool registered = _registrar.IsRegistered();
|
||||
if (desired == registered)
|
||||
{
|
||||
return new VkLayerReconcileOutcome(desired, registered, Changed: false, vulkanEnabled, Staged: true);
|
||||
}
|
||||
|
||||
if (desired)
|
||||
{
|
||||
_registrar.Register();
|
||||
_log($"vklayer: registered — {vulkanEnabled} hook-enabled game(s) reference the Vulkan loader");
|
||||
}
|
||||
else
|
||||
{
|
||||
_registrar.Unregister();
|
||||
_log("vklayer: unregistered — no hook-enabled game references the Vulkan loader");
|
||||
}
|
||||
|
||||
return new VkLayerReconcileOutcome(desired, desired, Changed: true, vulkanEnabled, Staged: true);
|
||||
}
|
||||
}
|
||||
@@ -108,4 +108,14 @@ public sealed record GameFileSnapshot
|
||||
/// members say.
|
||||
/// </summary>
|
||||
public required IReadOnlySet<DetectionSignalType> UncollectedFacts { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether the executable references the Vulkan loader — <c>vulkan-1.dll</c> in its import or delay-import
|
||||
/// table, or as an ASCII / UTF-16 string in the bounded scan (a loader reached through <c>LoadLibrary</c>, the
|
||||
/// shape <c>hook-harness --vulkan</c> and many titles take). Null = the file could not be read for it. A static
|
||||
/// fact about the file, not a rule signal: the rules cannot express it (P4 PR-2, <c>05_DETECTION</c> §Capability
|
||||
/// hints), and it exists so the layer can be registered for a Vulkan title before it ever runs
|
||||
/// (<c>17_HOOK_ENGINE</c> §Vulkan).
|
||||
/// </summary>
|
||||
public bool? VulkanLoaderReferenced { get; init; }
|
||||
}
|
||||
@@ -40,6 +40,16 @@ public sealed record StaticDetectionResult
|
||||
/// <summary>The rules version this result was produced from — part of the cache key.</summary>
|
||||
public required string RulesVersion { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The executable references the Vulkan loader (<see cref="GameFileSnapshot.VulkanLoaderReferenced"/>): true,
|
||||
/// false, or null when the file could not be read for it. A static fact about the binary, never a claim
|
||||
/// about what it presented — the API a session ran on is <c>sessions.api</c>, measured (P4 PR-2).
|
||||
/// </summary>
|
||||
public bool? UsesVulkan { get; init; }
|
||||
|
||||
/// <summary>The capability id the sweep stores for <see cref="UsesVulkan"/>; not a rule id, and not in the rules file.</summary>
|
||||
public const string VulkanCapabilityId = "vulkan";
|
||||
|
||||
/// <summary>
|
||||
/// Whether a re-run may write <paramref name="detected"/> over a field whose
|
||||
/// current provenance is <paramref name="existing"/>.
|
||||
|
||||
@@ -75,9 +75,11 @@ public sealed class GameFileProbe : IGameFileProbe
|
||||
uncollected.Add(DetectionSignalType.PeProductContains);
|
||||
}
|
||||
|
||||
// One bounded read serves both the rules' strings questions and the Vulkan fact below.
|
||||
string? text = TryReadBounded(exePath);
|
||||
HashSet<string> needles = [];
|
||||
Dictionary<string, string> captures = new(StringComparer.Ordinal);
|
||||
if (!TryScanStrings(exePath, rules, needles, captures))
|
||||
if (!TryScanStrings(text, rules, needles, captures))
|
||||
{
|
||||
uncollected.Add(DetectionSignalType.StringsContains);
|
||||
}
|
||||
@@ -99,6 +101,7 @@ public sealed class GameFileProbe : IGameFileProbe
|
||||
StringsRegexCaptures = captures,
|
||||
ManifestFields = new Dictionary<string, string>(StringComparer.Ordinal),
|
||||
UncollectedFacts = uncollected,
|
||||
VulkanLoaderReferenced = ReferencesVulkanLoader(exePath, text),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -256,7 +259,7 @@ public sealed class GameFileProbe : IGameFileProbe
|
||||
/// is rules-dependent and the evaluator is not quite the pure function it
|
||||
/// would be nicer to have.
|
||||
/// </remarks>
|
||||
private static bool TryScanStrings(string exePath, DetectionRuleSet rules,
|
||||
private static bool TryScanStrings(string? text, DetectionRuleSet rules,
|
||||
HashSet<string> foundNeedles, Dictionary<string, string> captures)
|
||||
{
|
||||
List<string> needles = [.. rules.Engines
|
||||
@@ -277,7 +280,6 @@ public sealed class GameFileProbe : IGameFileProbe
|
||||
return true; // nothing asked, nothing to fail at
|
||||
}
|
||||
|
||||
string? text = TryReadBounded(exePath);
|
||||
if (text is null)
|
||||
{
|
||||
return false;
|
||||
@@ -303,6 +305,40 @@ public sealed class GameFileProbe : IGameFileProbe
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The "is Vulkan" fact (<c>17_HOOK_ENGINE</c> §Vulkan, P4 PR-2): the loader named in the import or delay-load
|
||||
/// table (a link-time import), or as an ASCII / UTF-16 string in the bounded scan (a <c>LoadLibrary</c> at run
|
||||
/// time — <c>hook-harness --vulkan</c>'s shape, and many titles'). Null when neither the PE nor the bytes could
|
||||
/// be read: the fact is then unknown, never "no".
|
||||
/// </summary>
|
||||
private static bool? ReferencesVulkanLoader(string exePath, string? text)
|
||||
{
|
||||
const string loader = "vulkan-1.dll";
|
||||
IReadOnlySet<string>? imports = PeImports.Read(exePath);
|
||||
if (imports is not null && imports.Contains(loader))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (text is not null)
|
||||
{
|
||||
if (text.Contains(loader, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// The Latin1 view of UTF-16LE text interleaves NULs: "v\0u\0l\0..." — a wide literal such as
|
||||
// LoadLibraryW(L"vulkan-1.dll"), which the ASCII search above cannot see.
|
||||
string wide = string.Join('\0', loader.ToCharArray());
|
||||
if (text.Contains(wide, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return imports is null && text is null ? null : false;
|
||||
}
|
||||
|
||||
private static string? TryReadBounded(string exePath)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Detection;
|
||||
|
||||
/// <summary>
|
||||
/// The module names an executable imports — its import directory and its delay-load directory — read from the
|
||||
/// file with bounded, read-only I/O (P4 PR-2). Null when the file is not a PE this reader understands or could not
|
||||
/// be read; an empty set when it is a PE that imports nothing. Names are returned as the file spells them, in a
|
||||
/// case-insensitive set.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This is the static half of the "is Vulkan" fact (<c>17_HOOK_ENGINE</c> §Vulkan): a title that links
|
||||
/// <c>vulkan-1.dll</c> at build time names it here. A title that reaches the loader through <c>LoadLibrary</c> does
|
||||
/// not, which is why <c>GameFileProbe</c> also looks for the name in the bounded strings scan.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Every offset is checked against the file length and every walk is capped, because a game's executable is
|
||||
/// untrusted input to this process (CLAUDE.md rule 4 is about game <em>memory</em>; a malformed file must
|
||||
/// likewise cost an answer, never the Agent). No exception leaves this class for a malformed file.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class PeImports
|
||||
{
|
||||
/// <summary>Descriptors walked per directory before the reader gives up: no real executable has this many.</summary>
|
||||
public const int MaxDescriptors = 4096;
|
||||
|
||||
private const int _maxNameBytes = 260;
|
||||
|
||||
public static IReadOnlySet<string>? Read(string path)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
try
|
||||
{
|
||||
using FileStream fs = File.OpenRead(path);
|
||||
return Read(fs);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The same over an open stream (tests hand in a synthetic PE).</summary>
|
||||
public static IReadOnlySet<string>? Read(Stream file)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
if (!file.CanSeek || !file.CanRead)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
byte[] directories = new byte[16 * 8];
|
||||
List<Section>? sections = ReadHeaders(file, directories);
|
||||
if (sections is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
// Directory 1: imports (IMAGE_IMPORT_DESCRIPTOR, 20 bytes, name at +12); directory 13: delay-load
|
||||
// (IMAGE_DELAYLOAD_DESCRIPTOR, 32 bytes, name at +4). Both end at an all-zero descriptor.
|
||||
if (!WalkNames(file, sections, directories, 1, descriptorSize: 20, nameAt: 12, names)
|
||||
|| !WalkNames(file, sections, directories, 13, descriptorSize: 32, nameAt: 4, names))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
/// <summary>DOS header → PE signature → optional header (PE32 or PE32+) → the 16 data directories and the section table. Null when any step does not read as a PE.</summary>
|
||||
private static List<Section>? ReadHeaders(Stream file, Span<byte> directories)
|
||||
{
|
||||
Span<byte> dos = stackalloc byte[64];
|
||||
if (!ReadAt(file, 0, dos) || dos[0] != (byte)'M' || dos[1] != (byte)'Z')
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
long peOffset = BinaryPrimitives.ReadUInt32LittleEndian(dos[60..]);
|
||||
Span<byte> sig = stackalloc byte[4 + 20]; // "PE\0\0" + IMAGE_FILE_HEADER
|
||||
if (!ReadAt(file, peOffset, sig) || sig[0] != (byte)'P' || sig[1] != (byte)'E' || sig[2] != 0 || sig[3] != 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
int sectionCount = BinaryPrimitives.ReadUInt16LittleEndian(sig[6..]);
|
||||
int optionalSize = BinaryPrimitives.ReadUInt16LittleEndian(sig[20..]);
|
||||
long optionalOffset = peOffset + 24;
|
||||
Span<byte> optional = stackalloc byte[2];
|
||||
if (optionalSize < 2 || !ReadAt(file, optionalOffset, optional))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
int directoriesAt = BinaryPrimitives.ReadUInt16LittleEndian(optional) switch
|
||||
{
|
||||
0x10B => 96, // PE32
|
||||
0x20B => 112, // PE32+
|
||||
_ => -1,
|
||||
};
|
||||
if (directoriesAt < 0 || optionalSize < directoriesAt + directories.Length || !ReadAt(file, optionalOffset + directoriesAt, directories))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return ReadSections(file, optionalOffset + optionalSize, sectionCount);
|
||||
}
|
||||
|
||||
private static bool WalkNames(Stream file, List<Section> sections, ReadOnlySpan<byte> directories, int index, int descriptorSize, int nameAt, HashSet<string> names)
|
||||
{
|
||||
uint rva = BinaryPrimitives.ReadUInt32LittleEndian(directories[(index * 8)..]);
|
||||
uint size = BinaryPrimitives.ReadUInt32LittleEndian(directories[(index * 8 + 4)..]);
|
||||
if (rva == 0 || size == 0)
|
||||
{
|
||||
return true; // no such directory: a PE that imports nothing that way
|
||||
}
|
||||
|
||||
Span<byte> descriptor = stackalloc byte[32];
|
||||
Span<byte> nameBuffer = stackalloc byte[_maxNameBytes];
|
||||
for (int i = 0; i < MaxDescriptors; i++)
|
||||
{
|
||||
long at = ToOffset(sections, rva + (uint)(i * descriptorSize));
|
||||
if (at < 0 || !ReadAt(file, at, descriptor[..descriptorSize]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (IsZero(descriptor[..descriptorSize]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
uint nameRva = BinaryPrimitives.ReadUInt32LittleEndian(descriptor[nameAt..]);
|
||||
long nameOffset = ToOffset(sections, nameRva);
|
||||
if (nameOffset < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int n = ReadUpTo(file, nameOffset, nameBuffer);
|
||||
int end = nameBuffer[..n].IndexOf((byte)0);
|
||||
if (end <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
names.Add(Encoding.ASCII.GetString(nameBuffer[..end]));
|
||||
}
|
||||
|
||||
return false; // more descriptors than any real binary carries: malformed
|
||||
}
|
||||
|
||||
private static List<Section>? ReadSections(Stream file, long tableOffset, int count)
|
||||
{
|
||||
if (count is <= 0 or > 96)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var sections = new List<Section>(count);
|
||||
Span<byte> header = stackalloc byte[40];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (!ReadAt(file, tableOffset + i * 40L, header))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
sections.Add(new Section(
|
||||
VirtualAddress: BinaryPrimitives.ReadUInt32LittleEndian(header[12..]),
|
||||
VirtualSize: BinaryPrimitives.ReadUInt32LittleEndian(header[8..]),
|
||||
RawPointer: BinaryPrimitives.ReadUInt32LittleEndian(header[20..]),
|
||||
RawSize: BinaryPrimitives.ReadUInt32LittleEndian(header[16..])));
|
||||
}
|
||||
|
||||
return sections;
|
||||
}
|
||||
|
||||
/// <summary>RVA → file offset through the section that contains it; -1 when none does.</summary>
|
||||
private static long ToOffset(List<Section> sections, uint rva)
|
||||
{
|
||||
foreach (Section s in sections)
|
||||
{
|
||||
uint span = Math.Max(s.VirtualSize, s.RawSize);
|
||||
if (rva >= s.VirtualAddress && rva < s.VirtualAddress + span)
|
||||
{
|
||||
return s.RawPointer + (rva - s.VirtualAddress);
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static bool ReadAt(Stream file, long offset, Span<byte> into)
|
||||
{
|
||||
if (offset < 0 || offset + into.Length > file.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
file.Position = offset;
|
||||
return file.ReadAtLeast(into, into.Length, throwOnEndOfStream: false) == into.Length;
|
||||
}
|
||||
|
||||
private static int ReadUpTo(Stream file, long offset, Span<byte> into)
|
||||
{
|
||||
if (offset < 0 || offset >= file.Length)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
file.Position = offset;
|
||||
int take = (int)Math.Min(into.Length, file.Length - offset);
|
||||
return file.ReadAtLeast(into[..take], take, throwOnEndOfStream: false);
|
||||
}
|
||||
|
||||
private static bool IsZero(ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
foreach (byte b in bytes)
|
||||
{
|
||||
if (b != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private readonly record struct Section(uint VirtualAddress, uint VirtualSize, uint RawPointer, uint RawSize);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using FrameLedger.Application.Vulkan;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Vulkan;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IVkLayerRegistrar"/> over <see cref="VkLayerRegistration"/> and the manifest writer, for the product
|
||||
/// directory: the layer DLL beside the Agent, the manifest under <c>%LOCALAPPDATA%\FrameLedger\vklayer</c>
|
||||
/// (P4 PR-2). The same two calls <c>--register-vklayer</c> / <c>--unregister-vklayer</c> make, so the automatic
|
||||
/// path and the repair tool cannot disagree about what "registered" means.
|
||||
/// </summary>
|
||||
public sealed class VkLayerRegistrar(string layerDirectory, string layerDllPath, string keyPath = VkLayerRegistration.DefaultKeyPath) : IVkLayerRegistrar
|
||||
{
|
||||
private readonly string _layerDirectory = layerDirectory ?? throw new ArgumentNullException(nameof(layerDirectory));
|
||||
private readonly string _layerDllPath = layerDllPath ?? throw new ArgumentNullException(nameof(layerDllPath));
|
||||
private readonly VkLayerRegistration _registration = new(keyPath);
|
||||
|
||||
public string ManifestPath => Path.Combine(_layerDirectory, VkLayerLaunchEnvironment.ManifestFileName);
|
||||
|
||||
public bool IsStaged => File.Exists(_layerDllPath);
|
||||
|
||||
public bool IsRegistered() => _registration.IsRegistered(ManifestPath);
|
||||
|
||||
public void Register() => _registration.Register(VkLayerLaunchEnvironment.WriteManifest(_layerDirectory, _layerDllPath));
|
||||
|
||||
public bool Unregister() => _registration.Unregister(ManifestPath);
|
||||
}
|
||||
@@ -276,6 +276,37 @@ public sealed class SettingsViewModelTests
|
||||
h.Strip.Shown.Should().ContainSingle().Which.Kind.Should().Be("success");
|
||||
}
|
||||
|
||||
/// <summary>P4 PR-2: the Register button follows the reconciler's rule — a hook-enabled game must reference the Vulkan loader.</summary>
|
||||
[Fact]
|
||||
public async Task RegisterIsOfferedOnlyWhenAHookEnabledGameReferencesTheVulkanLoader()
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
GameRow d3d = await s.GameAsync("Direct");
|
||||
GameRow vk = await s.GameAsync("Vulkanic");
|
||||
var consent = new SqliteGameConsentStore(s.Db);
|
||||
foreach (GameRow g in new[] { d3d, vk })
|
||||
{
|
||||
await consent.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
|
||||
{
|
||||
Fingerprint = g.Fingerprint,
|
||||
DisclosureVersion = SafetyDisclosure.Version,
|
||||
AcknowledgedAt = DateTimeOffset.UtcNow,
|
||||
Provenance = ConsentProvenance.ConsentDialog,
|
||||
}, Ct);
|
||||
}
|
||||
|
||||
await s.Games.ApplyDetectionAsync(d3d.Id, new DetectionWrite { CapabilityIds = ["dlss"], RulesVersion = "r", ExeSizeBytes = 1, ExeMtimeMs = 1 }, Ct);
|
||||
var maintenance = new FakeMaintenance { Snapshot = new MaintenanceSnapshot(true, false, LogonTaskState.NotInstalled) };
|
||||
Harness before = await OpenAsync(s, maintenance: maintenance);
|
||||
before.Vm.HookedGames.Should().HaveCount(2);
|
||||
before.Vm.CanRegisterLayer.Should().BeFalse("two hook-enabled games, neither references the Vulkan loader");
|
||||
|
||||
await s.Games.ApplyDetectionAsync(vk.Id, new DetectionWrite { CapabilityIds = ["vulkan"], RulesVersion = "r", ExeSizeBytes = 1, ExeMtimeMs = 1 }, Ct);
|
||||
Harness after = await OpenAsync(s, maintenance: maintenance);
|
||||
after.Vm.HookedGames.Should().ContainSingle(static g => g.UsesVulkan).Which.Name.Should().Be("Vulkanic");
|
||||
after.Vm.CanRegisterLayer.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheTaskButtonsFollowTaskSchedulersAnswerAndAFailureIsSaid()
|
||||
{
|
||||
|
||||
@@ -41,11 +41,14 @@ public sealed class DetectionSweepTests
|
||||
{
|
||||
public int Calls { get; private set; }
|
||||
|
||||
public bool? VulkanLoaderReferenced { get; set; }
|
||||
|
||||
public ValueTask<GameFileSnapshot> SnapshotAsync(string exePath, DetectionRuleSet rules, CancellationToken ct = default)
|
||||
{
|
||||
Calls++;
|
||||
return ValueTask.FromResult(new GameFileSnapshot
|
||||
{
|
||||
VulkanLoaderReferenced = VulkanLoaderReferenced,
|
||||
ExePath = exePath,
|
||||
ExeNameWithoutExtension = "game",
|
||||
GameDirectory = "C:/Games/Title",
|
||||
@@ -158,6 +161,24 @@ public sealed class DetectionSweepTests
|
||||
(await waiting).Should().BeTrue("a waiter is woken early");
|
||||
}
|
||||
|
||||
/// <summary>The Vulkan fact rides in <c>capability_flags</c> under its own id (P4 PR-2): appended when the probe saw the loader, absent when it did not or could not look.</summary>
|
||||
[Fact]
|
||||
public async Task TheVulkanFactIsStoredAsACapabilityIdOnlyWhenTheLoaderWasSeen()
|
||||
{
|
||||
(DetectionSweep sweep, FakeGameRepository games, _, ScriptedProbe probe, _, List<string> log) = await BuildAsync();
|
||||
|
||||
probe.VulkanLoaderReferenced = true;
|
||||
await sweep.SweepOnceAsync(Ct);
|
||||
games.Detections[^1].Write.CapabilityIds.Should().Equal("dlss", "vulkan");
|
||||
log[^1].Should().Contain("vulkan=yes");
|
||||
|
||||
probe.VulkanLoaderReferenced = null;
|
||||
games.Rows[_exe] = games.Rows[_exe] with { DetectionRulesVersion = null }; // stale again
|
||||
await sweep.SweepOnceAsync(Ct);
|
||||
games.Detections[^1].Write.CapabilityIds.Should().Equal("dlss");
|
||||
log[^1].Should().Contain("vulkan=unknown", "could not look is not \"no\", and it is not stored as a fact either way");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StalenessIsTheCacheKeyFieldByField()
|
||||
{
|
||||
|
||||
@@ -59,6 +59,18 @@ public sealed class StaticGameDetectorTests
|
||||
],
|
||||
};
|
||||
|
||||
/// <summary>The Vulkan fact passes through untouched (P4 PR-2): true, false, or null — the detector claims nothing the probe did not see.</summary>
|
||||
[Fact]
|
||||
public async Task TheVulkanFactIsTheProbesThreeValuedAnswer()
|
||||
{
|
||||
foreach (bool? seen in new bool?[] { true, false, null })
|
||||
{
|
||||
var detector = new StaticGameDetector(new ScriptedRules(Rules()), new ScriptedProbe(Snapshot("UnityPlayer.dll") with { VulkanLoaderReferenced = seen }));
|
||||
StaticDetectionResult r = await detector.DetectAsync(@"C:\Games\Example\Game.exe", TestContext.Current.CancellationToken);
|
||||
r.UsesVulkan.Should().Be(seen);
|
||||
}
|
||||
}
|
||||
|
||||
private static GameFileSnapshot Snapshot(params string[] files) => new()
|
||||
{
|
||||
ExePath = "C:/Games/Example/Game.exe",
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Tests.Recording;
|
||||
using FrameLedger.Application.Vulkan;
|
||||
using FrameLedger.Domain.AntiCheat;
|
||||
using FrameLedger.Domain.Consent;
|
||||
|
||||
namespace FrameLedger.Application.Tests.Vulkan;
|
||||
|
||||
/// <summary>
|
||||
/// <c>12_BUILD</c> §The Vulkan layer is not registered at install time, enforced (P4 PR-2): registered only while a
|
||||
/// hook-enabled game references the Vulkan loader, unregistered when the last such game is disabled, nothing when
|
||||
/// the layer is not staged, and idempotent.
|
||||
/// </summary>
|
||||
public sealed class VkLayerReconcilerTests
|
||||
{
|
||||
private const string _vulkanGame = @"C:\Games\V\v.exe";
|
||||
private const string _d3dGame = @"C:\Games\D\d.exe";
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private sealed class FakeConsent : IGameConsentStore
|
||||
{
|
||||
public HashSet<string> Enabled { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public ValueTask<GameConsentRecord> FindAsync(string normalisedExePath, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
|
||||
public ValueTask<IReadOnlyList<GameConsentRecord>> ListEnabledAsync(CancellationToken ct = default) =>
|
||||
ValueTask.FromResult<IReadOnlyList<GameConsentRecord>>([.. Enabled.Select(static p => GameConsentRecord.Stored(
|
||||
new ExecutableFingerprint { ExePath = p, SizeBytes = 1, MtimeUnixMs = 1 }, hookEnabled: true, DateTimeOffset.UnixEpoch,
|
||||
ConsentProvenance.ConsentDialog, "consent-dialog/1", null, false, DateTimeOffset.UnixEpoch))]);
|
||||
|
||||
public ValueTask<ConsentWriteOutcome> RecordOperatorAcknowledgementAsync(OperatorAcknowledgement acknowledgement, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
|
||||
public ValueTask<ConsentWriteOutcome> RevokeAsync(string normalisedExePath, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
|
||||
public ValueTask<ConsentWriteOutcome> RecordGuardBlockAsync(ExecutableFingerprint fingerprint, AntiCheatVerdict verdict, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
private sealed class FakeRegistrar : IVkLayerRegistrar
|
||||
{
|
||||
public bool IsStaged { get; set; } = true;
|
||||
|
||||
public bool Registered { get; set; }
|
||||
|
||||
public List<string> Calls { get; } = [];
|
||||
|
||||
public bool IsRegistered() => Registered;
|
||||
|
||||
public void Register()
|
||||
{
|
||||
Calls.Add("register");
|
||||
Registered = true;
|
||||
}
|
||||
|
||||
public bool Unregister()
|
||||
{
|
||||
Calls.Add("unregister");
|
||||
bool was = Registered;
|
||||
Registered = false;
|
||||
return was;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<(VkLayerReconciler Reconciler, FakeConsent Consent, FakeRegistrar Registrar, List<string> Log)> BuildAsync()
|
||||
{
|
||||
var games = new FakeGameRepository();
|
||||
GameRow v = await games.EnsureAsync(new ExecutableFingerprint { ExePath = _vulkanGame, SizeBytes = 1, MtimeUnixMs = 1 }, "V", Ct).ConfigureAwait(false);
|
||||
await games.ApplyDetectionAsync(v.Id, new DetectionWrite { CapabilityIds = ["dlss", "vulkan"], RulesVersion = "r", ExeSizeBytes = 1, ExeMtimeMs = 1 }, Ct).ConfigureAwait(false);
|
||||
GameRow d = await games.EnsureAsync(new ExecutableFingerprint { ExePath = _d3dGame, SizeBytes = 1, MtimeUnixMs = 1 }, "D", Ct).ConfigureAwait(false);
|
||||
await games.ApplyDetectionAsync(d.Id, new DetectionWrite { CapabilityIds = ["dlss"], RulesVersion = "r", ExeSizeBytes = 1, ExeMtimeMs = 1 }, Ct).ConfigureAwait(false);
|
||||
var consent = new FakeConsent();
|
||||
var registrar = new FakeRegistrar();
|
||||
List<string> log = [];
|
||||
return (new VkLayerReconciler(consent, games, registrar, log.Add), consent, registrar, log);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheLayerIsRegisteredForTheFirstVulkanGameAndUnregisteredAfterTheLast()
|
||||
{
|
||||
(VkLayerReconciler r, FakeConsent consent, FakeRegistrar reg, List<string> log) = await BuildAsync();
|
||||
|
||||
VkLayerReconcileOutcome none = await r.ReconcileAsync(Ct);
|
||||
none.Desired.Should().BeFalse();
|
||||
none.Changed.Should().BeFalse();
|
||||
reg.Calls.Should().BeEmpty("nothing enabled, nothing registered, nothing to do");
|
||||
|
||||
consent.Enabled.Add(_d3dGame);
|
||||
(await r.ReconcileAsync(Ct)).Desired.Should().BeFalse("a hook-enabled game that does not reference the loader is not a Vulkan title");
|
||||
reg.Calls.Should().BeEmpty();
|
||||
|
||||
consent.Enabled.Add(_vulkanGame);
|
||||
VkLayerReconcileOutcome on = await r.ReconcileAsync(Ct);
|
||||
on.Should().Be(new VkLayerReconcileOutcome(Desired: true, Registered: true, Changed: true, VulkanGamesEnabled: 1, Staged: true));
|
||||
reg.Calls.Should().Equal("register");
|
||||
log.Should().ContainSingle(static l => l.Contains("registered", StringComparison.Ordinal));
|
||||
|
||||
(await r.ReconcileAsync(Ct)).Changed.Should().BeFalse("idempotent: the state already matches");
|
||||
reg.Calls.Should().Equal("register");
|
||||
|
||||
consent.Enabled.Remove(_vulkanGame);
|
||||
VkLayerReconcileOutcome off = await r.ReconcileAsync(Ct);
|
||||
off.Desired.Should().BeFalse();
|
||||
off.Registered.Should().BeFalse();
|
||||
off.Changed.Should().BeTrue();
|
||||
reg.Calls.Should().Equal("register", "unregister");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NothingHappensWhenTheLayerIsNotStaged()
|
||||
{
|
||||
(VkLayerReconciler r, FakeConsent consent, FakeRegistrar reg, _) = await BuildAsync();
|
||||
consent.Enabled.Add(_vulkanGame);
|
||||
reg.IsStaged = false;
|
||||
|
||||
VkLayerReconcileOutcome o = await r.ReconcileAsync(Ct);
|
||||
o.Desired.Should().BeTrue("the ledger wants it");
|
||||
o.Staged.Should().BeFalse();
|
||||
o.Changed.Should().BeFalse();
|
||||
reg.Calls.Should().BeEmpty("there is no DLL to point a manifest at");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CapabilityFlagsReadBothShapesAndRefuseGarbage()
|
||||
{
|
||||
CapabilityFlags.Contains("[\"dlss\",\"vulkan\"]", "vulkan").Should().BeTrue();
|
||||
CapabilityFlags.Contains("[\"dlss\"]", "vulkan").Should().BeFalse();
|
||||
CapabilityFlags.Contains("{\"vulkan\":true}", "vulkan").Should().BeTrue();
|
||||
CapabilityFlags.Contains("{\"vulkan\":false}", "vulkan").Should().BeFalse();
|
||||
CapabilityFlags.Contains("not json", "vulkan").Should().BeFalse();
|
||||
CapabilityFlags.Contains(null, "vulkan").Should().BeFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Domain.Detection;
|
||||
using FrameLedger.Infrastructure.Detection;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests.Detection;
|
||||
|
||||
/// <summary>
|
||||
/// The import-table reader behind the "is Vulkan" fact (P4 PR-2), driven by synthetic PEs built in memory: a
|
||||
/// link-time import is read from the import directory and the delay-load directory, a <c>LoadLibraryW</c> wide
|
||||
/// literal is found by the probe's strings pass, a malformed file costs an answer and never an exception, and a
|
||||
/// file that is not a PE reads as unknown rather than "no".
|
||||
/// </summary>
|
||||
public sealed class PeImportsTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
[Fact]
|
||||
public void ALinkTimeImportIsReadFromTheImportDirectory()
|
||||
{
|
||||
using var pe = new MemoryStream(SyntheticPe.Build(imports: ["KERNEL32.dll", "vulkan-1.dll"], delayImports: []));
|
||||
IReadOnlySet<string>? names = PeImports.Read(pe);
|
||||
names.Should().NotBeNull();
|
||||
names!.Count.Should().Be(2);
|
||||
names.Contains("VULKAN-1.DLL").Should().BeTrue("the set is case-insensitive: the file's spelling is kept, the lookup does not care");
|
||||
names.Contains("kernel32.dll").Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADelayLoadImportCountsToo()
|
||||
{
|
||||
using var pe = new MemoryStream(SyntheticPe.Build(imports: ["KERNEL32.dll"], delayImports: ["vulkan-1.dll"]));
|
||||
PeImports.Read(pe)!.Contains("vulkan-1.dll").Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotAPeReadsAsUnknownAndAMalformedPeCostsAnAnswerNotAnException()
|
||||
{
|
||||
using var text = new MemoryStream(Encoding.ASCII.GetBytes("this is not a portable executable"));
|
||||
PeImports.Read(text).Should().BeNull();
|
||||
|
||||
byte[] good = SyntheticPe.Build(imports: ["vulkan-1.dll"], delayImports: []);
|
||||
// Point the import directory past the end of the file: the walk must refuse rather than throw.
|
||||
byte[] truncated = good[..(good.Length / 2)];
|
||||
using var bad = new MemoryStream(truncated);
|
||||
Func<IReadOnlySet<string>?> read = () => PeImports.Read(bad);
|
||||
read.Should().NotThrow().Which.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheProbeReportsTheLoaderFromAnImportOrAWideLiteralAndUnknownForAnUnreadableFile()
|
||||
{
|
||||
string dir = Path.Combine(Path.GetTempPath(), "fl-pe-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
var probe = new GameFileProbe();
|
||||
var rules = new DetectionRuleSet { SchemaVersion = 2, RulesVersion = "t", Engines = [], Platforms = [], Capabilities = [] };
|
||||
|
||||
string linked = Path.Combine(dir, "linked.exe");
|
||||
await File.WriteAllBytesAsync(linked, SyntheticPe.Build(imports: ["vulkan-1.dll"], delayImports: []), Ct);
|
||||
(await probe.SnapshotAsync(linked, rules, Ct)).VulkanLoaderReferenced.Should().BeTrue("a link-time import");
|
||||
|
||||
string wide = Path.Combine(dir, "wide.exe");
|
||||
await File.WriteAllBytesAsync(wide, SyntheticPe.Build(imports: ["KERNEL32.dll"], delayImports: [], trailing: Encoding.Unicode.GetBytes("vulkan-1.dll")), Ct);
|
||||
(await probe.SnapshotAsync(wide, rules, Ct)).VulkanLoaderReferenced.Should().BeTrue("LoadLibraryW(L\"vulkan-1.dll\") — the harness's shape, seen through the UTF-16 view");
|
||||
|
||||
string d3d = Path.Combine(dir, "d3d.exe");
|
||||
await File.WriteAllBytesAsync(d3d, SyntheticPe.Build(imports: ["d3d11.dll", "dxgi.dll"], delayImports: []), Ct);
|
||||
(await probe.SnapshotAsync(d3d, rules, Ct)).VulkanLoaderReferenced.Should().BeFalse("a readable PE that names no loader anywhere");
|
||||
|
||||
string missing = Path.Combine(dir, "gone.exe");
|
||||
(await probe.SnapshotAsync(missing, rules, Ct)).VulkanLoaderReferenced.Should().BeNull("could not look is not \"no\"");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(dir, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The smallest PE32+ this reader accepts: one section holding the import and delay-load directories and their names.</summary>
|
||||
private static class SyntheticPe
|
||||
{
|
||||
public static byte[] Build(IReadOnlyList<string> imports, IReadOnlyList<string> delayImports, byte[]? trailing = null)
|
||||
{
|
||||
const uint sectionRva = 0x1000;
|
||||
const uint sectionRaw = 0x400;
|
||||
const int importDescriptorSize = 20;
|
||||
const int delayDescriptorSize = 32;
|
||||
|
||||
// Section layout: import descriptors, delay descriptors, then the name strings, then any trailing bytes.
|
||||
int importsBytes = (imports.Count + 1) * importDescriptorSize;
|
||||
int delayBytes = (delayImports.Count + 1) * delayDescriptorSize;
|
||||
var names = new List<(string Name, int Offset)>();
|
||||
int cursor = importsBytes + delayBytes;
|
||||
foreach (string n in imports.Concat(delayImports))
|
||||
{
|
||||
names.Add((n, cursor));
|
||||
cursor += n.Length + 1;
|
||||
}
|
||||
|
||||
int trailingAt = cursor;
|
||||
int sectionSize = cursor + (trailing?.Length ?? 0);
|
||||
byte[] section = new byte[sectionSize];
|
||||
for (int i = 0; i < imports.Count; i++)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(i * importDescriptorSize + 12), sectionRva + (uint)names[i].Offset);
|
||||
}
|
||||
|
||||
for (int i = 0; i < delayImports.Count; i++)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(section.AsSpan(importsBytes + i * delayDescriptorSize + 4), sectionRva + (uint)names[imports.Count + i].Offset);
|
||||
}
|
||||
|
||||
foreach ((string name, int offset) in names)
|
||||
{
|
||||
Encoding.ASCII.GetBytes(name).CopyTo(section, offset);
|
||||
}
|
||||
|
||||
trailing?.CopyTo(section, trailingAt);
|
||||
|
||||
byte[] file = new byte[sectionRaw + sectionSize];
|
||||
WriteHeaders(file, sectionRva, sectionRaw, sectionSize, importsBytes, delayImports.Count > 0 ? delayBytes : 0);
|
||||
section.CopyTo(file, (int)sectionRaw);
|
||||
return file;
|
||||
}
|
||||
|
||||
/// <summary>DOS header, PE signature, a PE32+ optional header whose directories 1 and 13 point into the one section, and that section's header.</summary>
|
||||
private static void WriteHeaders(byte[] file, uint sectionRva, uint sectionRaw, int sectionSize, int importsBytes, int delayBytes)
|
||||
{
|
||||
// DOS header: "MZ", e_lfanew at 60 → 0x80.
|
||||
file[0] = (byte)'M';
|
||||
file[1] = (byte)'Z';
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(60), 0x80);
|
||||
// PE signature + file header: 1 section, optional header size 240 (PE32+).
|
||||
file[0x80] = (byte)'P';
|
||||
file[0x81] = (byte)'E';
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(file.AsSpan(0x84 + 2), 1);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(file.AsSpan(0x84 + 16), 240);
|
||||
int optional = 0x84 + 20;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(file.AsSpan(optional), 0x20B);
|
||||
int directories = optional + 112;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(directories + 1 * 8), sectionRva);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(directories + 1 * 8 + 4), (uint)importsBytes);
|
||||
if (delayBytes > 0)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(directories + 13 * 8), sectionRva + (uint)importsBytes);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(directories + 13 * 8 + 4), (uint)delayBytes);
|
||||
}
|
||||
|
||||
// One section header right after the optional header.
|
||||
int sectionHeader = optional + 240;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(sectionHeader + 8), (uint)sectionSize);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(sectionHeader + 12), sectionRva);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(sectionHeader + 16), (uint)sectionSize);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(sectionHeader + 20), sectionRaw);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user