diff --git a/.gitignore b/.gitignore index 6c1088b..97871b1 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,4 @@ installer/Releases/ # Process Monitor / debug log dumps (session junk) *.PML Logfile*.XML +out/ diff --git a/BUILD.md b/BUILD.md index 0f5b1f0..43fae17 100644 --- a/BUILD.md +++ b/BUILD.md @@ -9,6 +9,35 @@ RynthCore is the injection framework. RynthSuite (separate repo) contains the pl - Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads (required by the NativeAOT ILC linker) - Asheron's Call client installed +## The unloadable engine (the default since 2026-09-29) + +The engine now runs on CoreCLR, and a hot reload really frees the old engine and its plugins +(`docs/UNLOADABLE_ENGINE_PLAN.md`, Status section). What ships and deploys: + +``` +C:\Games\RynthCore\Runtime\ +├── RynthCore.Loader.dll ← native loader (native\Loader, C/cl.exe): injection target, hosts CoreCLR once +├── RynthCore.Shim.dll ← the only RynthCore code in CoreCLR's default context +├── RynthCore.Engine.dll(+pdb)← the engine, a managed assembly (-p:EngineHost=coreclr, ReadyToRun) +├── Avalonia.*, ImGui.NET ... ← the engine's own dependencies (load and unload with each engine) +├── cimgui, minhook, Skia ... ← native libraries (loaded once) +└── dotnet\ ← the app-local x86 .NET runtime (from the NuGet runtime pack) +C:\Games\RynthSuite\\ ← each plugin as a managed assembly + its dependency DLLs +``` + +| Task | Command | +|---|---| +| Full local deploy (engine, loader, managed plugins, launcher) | `scripts\Deploy-RynthCore.ps1` (close every client first; `-SkipLauncher` while the launcher runs) | +| Engine change, clients running | `scripts\Publish-EngineCoreClr.ps1 -EngineOnly` — each running client hot-reloads onto it by itself | +| Loader/Shim change, clients running | `scripts\Publish-EngineCoreClr.ps1` — the in-use copies are renamed aside; new launches get the new ones | +| Installer | `installer\Build-Installer.ps1` (release plugins stay NativeAOT: the new engine loads them) | +| Hot-reload test on a local server | `scripts\Test-ClrWorld.ps1 -Reloads 3` (see its header) | +| Why didn't a generation unload? | `tools\AlcRoots ` (build it: `dotnet build tools\AlcRoots -c Release`) | + +`-NativeAot` on `Deploy-RynthCore.ps1` and `Build-Installer.ps1` builds the old NativeAOT engine, +loader and plugins; the sections below describe that path. The engine and plugins use the same +source either way. Rules that keep an engine or plugin unloadable are in `CLAUDE.md` ("Unloadable engine"). + ## Projects | Project | Type | Output | @@ -92,7 +121,7 @@ C:\Games\RynthCore\ ├── RynthCore.Loader.dll ← Loader (NativeAOT x86) — injection target ├── RynthCore.Engine.dll ← Engine (NativeAOT x86) ├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint - ├── cimgui.dll ← ImGui C bindings (x86, docking branch) + ├── cimgui.dll ← ImGui C bindings (x86, docking branch; our build) └── Plugins\ └── *.dll ← Built-in plugin directory @@ -162,7 +191,7 @@ If AC is already running, click **RL** on the RynthCore overlay bar to hot-reloa | `Runtime\RynthCore.Loader.dll` | small (~1–2 MB) | NativeAOT didn't run — check for `Generating native code` in build output | | `Runtime\RynthCore.Engine.dll` | ~26 MB | NativeAOT didn't run — same diagnosis | | `RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | ~7 MB | Built `dotnet build` instead of `dotnet publish` | -| `Runtime\cimgui.dll` | ~1.5 MB | Must match ImGui.NET 1.91.6.1 | +| `Runtime\cimgui.dll` | ~1.2 MB | Must be our build (`scripts\Build-Cimgui.ps1`); with ImGui on, the log shows `ImGuiSelfTest: OK` | To confirm NativeAOT actually ran, check that `.lib` and `.exp` files exist alongside the DLL in the publish output's `native\` directory. @@ -235,6 +264,7 @@ If your AC client ever gets a real-world patch, apply it to both copies (or `rob - **Clean before plugin publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every plugin publish to guarantee a fresh compile. - **Engine deploy path is `Runtime\`**, not `C:\Games\RynthCore\` directly. The injector resolves `Runtime\RynthCore.Loader.dll` (preferred) and `Runtime\RynthCore.Engine.dll` (legacy) by default. - **Close AC before redeploying Loader or Engine.** Both are loaded into `acclient.exe` and locked while the game is running. Plugins are shadow-copied so they can be hot-swapped without closing AC. -- **cimgui.dll version must match ImGui.NET NuGet.** Post-1.90 struct layouts changed. A mismatched cimgui.dll causes `DisplaySize = <1, 1>` or font crashes on frame 2. +- **cimgui.dll is built by us, not taken from NuGet.** `scripts\Build-Cimgui.ps1` fetches cimgui 1.91.6dock into `native\cimgui\_src` (git-ignored), builds it with MSVC (VS 2022 Build Tools, C++ workload) and writes `src\RynthCore.Engine\Native\cimgui.dll`, which is committed. The stock NuGet x86 DLL does not match ImGui.NET's structs (64-bit `ImTextureID`); the engine's `ImGuiSelfTest` refuses it and any other non-matching build. Only rerun the script when changing the cimgui build itself. - **vswhere.exe must be on PATH** for the NativeAOT link step. Add `C:\Program Files (x86)\Microsoft Visual Studio\Installer` to PATH if missing. -- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm. +- **Decal.** `src\RynthCore.DecalBridge` (net48) builds with the solution when Decal is installed (an empty assembly and a warning otherwise); every installer stages it (`Build-Installer.ps1` fails without Decal; `-SkipDecalBridge` for a dev build). The launcher registers it only for accounts set to "Decal + RynthCore (experimental)"; their choice is kept in `%APPDATA%\RynthCore\decal-accounts.json`, never in the shared `appsettings.json`. Bridge mode and in-game ImGui under Decal: `docs/DECAL_BRIDGE_PLAN.md`. +- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe and neither bridge mode nor `DecalInGameImGui` applies, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm. diff --git a/README.md b/README.md index 04bca03..198e226 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ RynthCore is a modern .NET 10 modding host for Asheron's Call. It combines an x86 NativeAOT in-process engine, a hot-reload-capable loader, an injector, an Avalonia desktop launcher, and a plugin surface that replaces the legacy Decal + UBService + VTank stack with a self-contained RynthCore-native API. -The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://github.com/tombohar/RynthSuite). +The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://aelrynth.com/git/rynth/RynthSuite). ## What it does @@ -86,7 +86,7 @@ For full deploy details, the Inno Setup installer, and gotchas, see [`BUILD.md`] ## Repository notes - Local settings, machine-specific files, generated `bin/`, `obj/`, `.vs/`, `.dotnet-home/` content, and launcher data (profiles, runtime state) are kept out of source control via `.gitignore` -- Plugin code lives in the [RynthSuite](https://github.com/tombohar/RynthSuite) repo as a sibling clone +- Plugin code lives in the [RynthSuite](https://aelrynth.com/git/rynth/RynthSuite) repo as a sibling clone ## Security and secrets diff --git a/RynthCore.sln b/RynthCore.sln index ab1ba16..971bb41 100644 --- a/RynthCore.sln +++ b/RynthCore.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -27,6 +27,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.Core EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.UI", "tools\HookResolver.UI\RynthCore.HookResolver.UI.csproj", "{C1A2B3D4-0009-0009-0009-000000000009}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DecalBridge", "src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj", "{44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 @@ -121,6 +123,18 @@ Global {C1A2B3D4-0007-0007-0007-000000000007}.Release|Any CPU.Build.0 = Release|Any CPU {C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.ActiveCfg = Release|Any CPU {C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU {C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.ActiveCfg = Debug|Any CPU {C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.Build.0 = Debug|Any CPU {C1A2B3D4-0008-0008-0008-000000000008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -145,18 +159,18 @@ Global {C1A2B3D4-0009-0009-0009-000000000009}.Release|Any CPU.Build.0 = Release|Any CPU {C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.ActiveCfg = Release|Any CPU {C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.Build.0 = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU - {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x86.ActiveCfg = Debug|x86 + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x86.Build.0 = Debug|x86 + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x64.ActiveCfg = Debug|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Debug|x64.Build.0 = Debug|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x86.ActiveCfg = Release|x86 + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x86.Build.0 = Release|x86 + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|Any CPU.Build.0 = Release|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x64.ActiveCfg = Release|Any CPU + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -168,5 +182,6 @@ Global {C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} {C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} + {44C8CF3A-3011-4C80-BDEE-1414B3D6CFAE} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection EndGlobal diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md new file mode 100644 index 0000000..0c72283 --- /dev/null +++ b/THIRD-PARTY-NOTICES.md @@ -0,0 +1,34 @@ +# Third-party notices + +RynthCore ships the following third-party material inside its own files. + +## Phosphor Icons + +- What: the Phosphor icon font (`Phosphor.ttf`, version 2.1, regular weight), used for the icons in the ImGui panels. +- Where: `src/RynthCore.Engine/Assets/Fonts/Phosphor.ttf`, embedded in `RynthCore.Engine.dll` as a resource. +- Source: https://phosphoricons.com (Tobias Fried and Helena Zhang) +- Licence: MIT, reproduced below and in `src/RynthCore.Engine/Assets/Fonts/Phosphor.LICENSE`. + +``` +MIT License + +Copyright (c) 2020-2021 Phosphor Icons + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index 12fe70a..307d515 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -5,12 +5,18 @@ .DESCRIPTION 1. Publishes the Avalonia launcher (self-contained, x86) - 2. Publishes RynthCore.Engine (NativeAOT, x86 -- ~2 min) - 3. Publishes RynthCore.Loader (NativeAOT, x86) -- the DLL the launcher injects - 4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86) + 2+3. The engine and the loader. By default the unloadable engine + (docs/UNLOADABLE_ENGINE_PLAN.md): scripts\Publish-EngineCoreClr.ps1 stages the native + loader (native\Loader), RynthCore.Shim, the CoreCLR engine (ReadyToRun) and the + app-local .NET runtime (Runtime\dotnet) straight into staging\app\Runtime. + -NativeAot builds the old NativeAOT engine + loader instead. + 4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86: the release plugins stay NativeAOT + - the CoreCLR engine loads them - until the update feed can carry a managed plugin's + dependency DLLs) 5. Publishes the Loot Editor 6. Stages all output under installer\staging\app\, plus the hand-built - RynthCore.SehTrampoline.dll, and checks every required runtime file is there + RynthCore.SehTrampoline.dll and the Decal bridge (DecalBridge\RynthCore.DecalBridge.dll, + built here against Decal's reference assemblies), and checks every required file is there 7. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup.exe .PARAMETER Configuration @@ -32,7 +38,19 @@ param( # Version string injected into the installer (e.g. "0.3"). When omitted, # the version defined in RynthCore.iss is used as-is. [string]$Version = "", - [switch]$SkipBuild + [switch]$SkipBuild, + # The old NativeAOT engine + loader (a hot reload leaks every engine generation). + [switch]$NativeAot, + # The Decal bridge (src\RynthCore.DecalBridge, docs/DECAL_BRIDGE_PLAN.md) is staged into + # {app}\DecalBridge by default: every release ships it (experimental, opt-in per account; + # nothing registers it unless the player picks "Decal + RynthCore"). Building it needs + # Decal installed (its public reference assemblies); without Decal this script fails. + # -SkipDecalBridge leaves it out (dev builds on a machine without Decal; never a release). + [switch]$SkipDecalBridge, + # Old opt-in switch, kept so existing command lines still work; the bridge is the default now. + [switch]$IncludeDecalBridge, + # Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0. + [string]$DecalDir = "" ) $ErrorActionPreference = "Stop" @@ -80,7 +98,7 @@ $LootEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\bin\$Configurat $StagingDir = "$ScriptDir\staging\app" # ── Validate projects ─────────────────────────────────────────────────────── -foreach ($p in @($LauncherProject, $EngineProject, $LoaderProject, $PluginProject, $LootEditorProject)) { +foreach ($p in @($LauncherProject, $EngineProject, $PluginProject, $LootEditorProject) + @(if ($NativeAot) { $LoaderProject })) { if (-not (Test-Path $p)) { throw "Project not found: $p`nUpdate paths in Build-Installer.ps1 if your repo layout differs." } @@ -93,17 +111,20 @@ if (-not $SkipBuild) { dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Launcher publish failed (exit $LASTEXITCODE)" } - # ── 2. Engine (NativeAOT — the slow one) ────────────────────────────────── - Write-Host "" - Write-Host "[2/5] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan - dotnet publish $EngineProject -c $Configuration @VersionArgs - if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" } + if ($NativeAot) { + # ── 2. Engine (NativeAOT — the slow one) ────────────────────────────── + Write-Host "" + Write-Host "[2/5] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan + dotnet publish $EngineProject -c $Configuration @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" } - # ── 3. Loader (NativeAOT, small) ────────────────────────────────────────── - Write-Host "" - Write-Host "[3/5] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan - dotnet publish $LoaderProject -c $Configuration @VersionArgs - if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" } + # ── 3. Loader (NativeAOT, small) ────────────────────────────────────── + Write-Host "" + Write-Host "[3/5] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan + dotnet publish $LoaderProject -c $Configuration @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" } + } + # (Default: the CoreCLR engine and native loader are built straight into staging below.) # ── 4. Plugin (NativeAOT) ───────────────────────────────────────────────── Write-Host "" @@ -143,18 +164,30 @@ foreach ($file in (Get-ChildItem "$LauncherPublish" -File)) { Copy-Item $file.FullName "$StagingDir\$destName" -Force } -# Engine runtime files (into Runtime\, skip .pdb) -foreach ($file in (Get-ChildItem "$EnginePublish" -File)) { - if ($file.Extension -eq '.pdb') { continue } - Copy-Item $file.FullName "$StagingDir\Runtime\$($file.Name)" -Force -} +if ($NativeAot) { + # Engine runtime files (into Runtime\, skip .pdb) + foreach ($file in (Get-ChildItem "$EnginePublish" -File)) { + if ($file.Extension -eq '.pdb') { continue } + Copy-Item $file.FullName "$StagingDir\Runtime\$($file.Name)" -Force + } -# Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it -# maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's -# launcher can't auto-find an engine to inject. -$loaderDll = "$LoaderPublish\RynthCore.Loader.dll" -if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" } -Copy-Item $loaderDll "$StagingDir\Runtime\" -Force + # Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it + # maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's + # launcher can't auto-find an engine to inject. + $loaderDll = "$LoaderPublish\RynthCore.Loader.dll" + if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" } + Copy-Item $loaderDll "$StagingDir\Runtime\" -Force +} else { + # The unloadable engine: native loader (same RynthCoreInit contract with the launcher's + # injector), RynthCore.Shim, the CoreCLR engine (ReadyToRun) + its dependencies, and + # Runtime\dotnet (the app-local x86 .NET runtime). Needs Visual Studio's C++ tools (cl.exe) + # for the loader, like the SEH trampoline. + Write-Host "" + Write-Host "[2+3/5] Building the unloadable engine + native loader into staging..." -ForegroundColor Cyan + & "$RepoRoot\scripts\Publish-EngineCoreClr.ps1" -Target "$StagingDir\Runtime" -Configuration $Configuration -MsBuildArgs $VersionArgs + # Keep the engine's pdb (its stack traces get line numbers); drop the loader's and shim's. + Remove-Item "$StagingDir\Runtime\RynthCore.Loader.pdb", "$StagingDir\Runtime\RynthCore.Shim.pdb" -Force -ErrorAction SilentlyContinue +} # SEH trampoline — hand-built native DLL (native\SehTrampoline\Build-SehTrampoline.ps1), # NOT part of the engine publish output. Without it SehTrampoline.IsAvailable stays @@ -169,8 +202,8 @@ if ((Test-Path $sehSrc) -and (Get-Item $sehSrc).LastWriteTime -gt (Get-Item $seh } Copy-Item $sehDll "$StagingDir\Runtime\" -Force -# Engine Native subfolder -if (Test-Path "$EnginePublish\Native") { +# Engine Native subfolder (NativeAOT layout) +if ($NativeAot -and (Test-Path "$EnginePublish\Native")) { foreach ($file in (Get-ChildItem "$EnginePublish\Native" -File)) { if ($file.Extension -eq '.pdb') { continue } Copy-Item $file.FullName "$StagingDir\Runtime\Native\$($file.Name)" -Force @@ -196,6 +229,38 @@ foreach ($dir in (Get-ChildItem "$LootEditorPublish" -Directory)) { Get-ChildItem "$StagingDir\Tools\LootEditor\$($dir.Name)" -Recurse -File -Filter '*.pdb' | Remove-Item -Force } +# Decal bridge (docs/DECAL_BRIDGE_PLAN.md, experimental): the net48 x86 Decal network filter +# goes to {app}\DecalBridge\, the folder the launcher registers for "Decal + RynthCore" +# accounts (and only for those). Built against Decal's public reference assemblies, so the +# build machine needs Decal; -p:RequireDecal=true turns "no Decal" into a build error rather +# than the empty assembly a plain solution build makes. Never ships any Decal file. +if ($SkipDecalBridge) { + Write-Warning "-SkipDecalBridge: this build has no Decal bridge; 'Decal + RynthCore' accounts can't launch with it. Not for a release." +} else { + Write-Host "" + Write-Host "Building the Decal bridge (net48 x86, against Decal's reference assemblies)..." -ForegroundColor Cyan + $bridgeProject = "$RepoRoot\src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj" + $bridgeDll = "$RepoRoot\src\RynthCore.DecalBridge\bin\$Configuration\RynthCore.DecalBridge.dll" + $decalArgs = @("-p:RequireDecal=true") + if ($DecalDir) { $decalArgs += "-p:DecalDir=$DecalDir" } + # A DLL left over from an earlier build must never be shipped in place of this one. + Remove-Item $bridgeDll -Force -ErrorAction SilentlyContinue + if (Test-Path $bridgeDll) { throw "Could not remove the old $bridgeDll (in use by a Decal client?)" } + dotnet build $bridgeProject -c $Configuration -nologo -v q @decalArgs @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Decal bridge build failed (exit $LASTEXITCODE). Is Decal 3.0 installed? (-DecalDir for another folder, -SkipDecalBridge for a dev build)" } + if (-not (Test-Path $bridgeDll)) { throw "Decal bridge not built at $bridgeDll" } + # The real bridge has its filter type; the no-Decal build is an empty assembly. + $bridgeBytes = [System.IO.File]::ReadAllBytes($bridgeDll) + if ([System.Text.Encoding]::ASCII.GetString($bridgeBytes).IndexOf("BridgeFilter") -lt 0) { + throw "$bridgeDll has no BridgeFilter type - it was built without Decal's reference assemblies." + } + New-Item -ItemType Directory -Path "$StagingDir\DecalBridge" -Force | Out-Null + Copy-Item $bridgeDll "$StagingDir\DecalBridge\" -Force + $staleDecal = @(Get-ChildItem "$StagingDir\DecalBridge" -File | Where-Object { $_.Name -ne "RynthCore.DecalBridge.dll" }) + if ($staleDecal.Count -gt 0) { throw "Unexpected files in the staged DecalBridge folder: $($staleDecal.Name -join ', ')" } + Write-Host " RynthCore.DecalBridge.dll $((Get-Item $bridgeDll).VersionInfo.FileVersion)" +} + # release.txt — which core release this install is ($release, from -Version at the top). Set-Content -Path "$StagingDir\release.txt" -Value @($release, $Version) -Encoding ASCII @@ -210,6 +275,16 @@ $required = @( "$StagingDir\Runtime\cimgui.dll", "$pluginStagingDir\RynthAi\RynthCore.Plugin.RynthAi.dll" ) +if (-not $NativeAot) { + $required += @( + "$StagingDir\Runtime\RynthCore.Shim.dll", + "$StagingDir\Runtime\dotnet\coreclr.dll", + "$StagingDir\Runtime\dotnet\System.Private.CoreLib.dll" + ) +} +if (-not $SkipDecalBridge) { + $required += "$StagingDir\DecalBridge\RynthCore.DecalBridge.dll" +} $missing = @($required | Where-Object { -not (Test-Path $_) }) if ($missing.Count -gt 0) { throw "Staging is missing required files:`n $($missing -join "`n ")" } diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index d2cb1db..e0c58f7 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -7,7 +7,8 @@ One command per release: 1. Refuses if the signing key isn't set up or isn't trusted by the launcher being shipped, if either repo has uncommitted changes, or if -Version isn't newer than the live feed. - 2. Builds the installer (Build-Installer.ps1 -Version) and the RynthSuite plugins into + 2. Builds the installer (Build-Installer.ps1 -Version; it includes the Decal bridge, so the + build machine needs Decal installed) and the RynthSuite plugins into installer\Releases\\ — never into the live C:\Games folders. 3. Writes the manifest (sizes + SHA-256 of every file), signs it with the DPAPI key (Sign-Update.ps1, no prompt) and checks the signature the way the launcher will. @@ -37,7 +38,12 @@ param( [string]$BaseUrl = "https://aelrynth.com/downloads/rynth", [string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"), [string]$RynthSuiteRoot = "", - [string]$TrustFile = "" # defaults to the launcher's UpdateTrust.cs; override for tests + [string]$TrustFile = "", # defaults to the launcher's UpdateTrust.cs; override for tests + # RynthNav's data shipped to launchers as the signed "navdata" archive: tiles (nav_XXXX.tile), + # portals.tsv and locations.json from this folder. Only re-uploaded when the set changes + # (its id is a hash of every file); otherwise the live feed's entry is carried over. + [string]$NavDataDir = "C:\Games\RynthCore\NavData", + [switch]$SkipNavData # leave navdata out of this feed (launchers then keep what they have) ) $ErrorActionPreference = "Stop" @@ -48,6 +54,7 @@ if (-not $TrustFile) { $TrustFile = Join-Path $RepoRoot "src\RynthCore.App.Avalo function Step($m) { Write-Host ""; Write-Host "== $m" -ForegroundColor Cyan } function Sha256([string]$path) { (Get-FileHash $path -Algorithm SHA256).Hash.ToLowerInvariant() } +function Sha256Text([string]$text) { [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($text))).ToLowerInvariant() } # Same check as RynthUpdater.VerifyEnvelope: any trusted key's signature over the payload bytes. function Test-Envelope([string]$path, [string[]]$keys) { @@ -99,9 +106,11 @@ if (-not $AllowDirty) { Write-Host " RynthCore $(git -C $RepoRoot rev-parse --short HEAD), RynthSuite $(git -C $RynthSuiteRoot rev-parse --short HEAD)" } +$liveManifest = $null try { $live = Invoke-RestMethod "$BaseUrl/update.json" -TimeoutSec 20 - $liveRelease = ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json).release + $liveManifest = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json + $liveRelease = $liveManifest.release if ($release -le $liveRelease) { throw "Release $release is not newer than the live feed's $liveRelease — bump -Version." } Write-Host " live feed is at $liveRelease; publishing $release" } catch [Microsoft.PowerShell.Commands.HttpResponseException] { @@ -116,10 +125,16 @@ New-Item -ItemType Directory -Force "$rel\plugins", "$rel\build" | Out-Null Step "Building the installer ($Version)" & (Join-Path $ScriptDir "Build-Installer.ps1") -Version $Version -RynthSuiteRoot $RynthSuiteRoot if (-not $?) { throw "Build-Installer.ps1 failed" } +# The Decal bridge ships in every release (experimental, opt-in per account): the installer +# carries it, so a launcher that updates through this feed gets it as a fresh install does. +# Build-Installer.ps1 fails without Decal; this guards against a -SkipDecalBridge staging. +$bridgeStaged = Join-Path $ScriptDir "staging\app\DecalBridge\RynthCore.DecalBridge.dll" +if (-not (Test-Path $bridgeStaged)) { throw "The installer was built without the Decal bridge ($bridgeStaged missing) - not publishing." } +Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionInfo.FileVersion)" Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup.exe") "$rel\RynthCore-Setup.exe" Copy-Item (Join-Path $ScriptDir "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\" -$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision" +$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory" foreach ($name in $suitePlugins) { Step "Building $name" $proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" @@ -134,11 +149,26 @@ $zipRoot = "$rel\build\zip" foreach ($name in $suitePlugins) { New-Item -ItemType Directory -Force "$zipRoot\RynthSuite\$name" | Out-Null Copy-Item "$rel\plugins\RynthCore.Plugin.$name.dll" "$zipRoot\RynthSuite\$name\" + # Third-party licence notices travel with the plugin (RynthOracle: Oracle of Dereth, MIT). + $notice = "$rel\build\$name\THIRD_PARTY_NOTICES.md" + if (Test-Path $notice) { Copy-Item $notice "$zipRoot\RynthSuite\$name\" } } -$navSrc = "C:\Games\RynthCore\NavData" +$navSrc = $NavDataDir New-Item -ItemType Directory -Force "$zipRoot\RynthCore\NavData" | Out-Null -Get-ChildItem $navSrc -File | Where-Object { $_.Extension -eq ".tile" -or $_.Name -eq "portals.tsv" } | +# The route planner's portals.tsv and the Atlas's locations.json (both made by +# tools\navdata\gen_locations.py from the world database), and the Town Network's townnet.json +# (tools\navdata\Build-TownNet.ps1: the world database plus the walks inside from the dats). +# Never the player's own files +# there (atlas.txt, recalls.txt, _player.txt). The tiles are no longer in this zip (the whole +# world is ~40,000 of them): the launcher installs them from the feed's navdata archive. +Get-ChildItem $navSrc -File | Where-Object { $_.Name -eq "portals.tsv" -or $_.Name -eq "locations.json" -or $_.Name -eq "townnet.json" } | Copy-Item -Destination "$zipRoot\RynthCore\NavData\" +if (-not (Test-Path "$navSrc\locations.json")) { + Write-Warning "NavData has no locations.json: RynthNav's Atlas ships empty. Run tools\navdata\gen_locations.py and copy its output there." +} +if (-not (Test-Path "$navSrc\townnet.json")) { + Write-Warning "NavData has no townnet.json: routes won't use the Town Network. Run tools\navdata\Build-TownNet.ps1 and copy its townnet.json there." +} @" RynthSuite plugins for RynthCore (Asheron's Call, retail client) - $Version @@ -147,28 +177,108 @@ Extract this zip into C:\Games - it creates: C:\Games\RynthSuite\RynthNav\ RynthNav plugin C:\Games\RynthSuite\RynthTracker\ RynthTracker plugin C:\Games\RynthSuite\RynthVision\ RynthVision plugin - C:\Games\RynthCore\NavData\ RynthNav's baked navmesh tiles + C:\Games\RynthSuite\RynthLua\ RynthLua plugin (Lua scripting; was part of RynthAi) + C:\Games\RynthSuite\RynthOracle\ RynthOracle plugin (quests, character, titles; based on Oracle of Dereth by Advis Eveldan) + C:\Games\RynthSuite\RynthInventory\ RynthInventory plugin (search every character's items) + C:\Games\RynthCore\NavData\ RynthNav's portals and Atlas Then, in the RynthCore launcher's Plugins tab, add the full path of each plugin DLL you want. Install RynthCore first (RynthCore-Setup.exe), which also installs RynthAi and the Loot Editor. After that the launcher keeps -the plugins up to date by itself. +the plugins up to date by itself, and once RynthNav is in the list it also +downloads RynthNav's navmesh tiles into C:\Games\RynthCore\NavData. MIT licensed. https://aelrynth.com/projects.html "@ -replace "`n", "`r`n" | Set-Content "$zipRoot\README.txt" -NoNewline Compress-Archive -Path "$zipRoot\*" -DestinationPath "$rel\RynthSuite-Plugins.zip" -CompressionLevel Optimal +# RynthNav's data for the launchers (RynthUpdater.NavData.cs): one archive, flat, only the file +# names RynthNav reads. Its id is a hash over every file's name and SHA-256, so an unchanged +# set reuses the live entry (and the archive already on the server) instead of re-uploading. +$navData = $null +$navZip = $null +if (-not $SkipNavData) { + Step "RynthNav data (tiles, route graph, portals, Atlas, Town Network) from $NavDataDir" + $navFiles = @(Get-ChildItem $NavDataDir -File | Where-Object { $_.Name -match '^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$' } | Sort-Object Name) + $tileCount = @($navFiles | Where-Object { $_.Extension -eq ".tile" }).Count + if ($tileCount -eq 0) { throw "$NavDataDir has no tiles. Pass -NavDataDir, or -SkipNavData to publish without them." } + # The long-range route graph (RynthNav.Baker --graph) must come from these very tiles: the + # plugin ignores a graph whose tiles don't match (long gotos then walk the straight line). + $graph = $navFiles | Where-Object { $_.Name -eq "navgraph.bin" } + $newestTile = ($navFiles | Where-Object { $_.Extension -eq ".tile" } | Measure-Object LastWriteTimeUtc -Maximum).Maximum + if (-not $graph) { Write-Warning "No navgraph.bin in ${NavDataDir}: long gotos will walk the straight line. Run: RynthNav.Baker --graph $NavDataDir" } + elseif ($graph.LastWriteTimeUtc -lt $newestTile) { Write-Warning "navgraph.bin is older than the newest tile: rebuild it (RynthNav.Baker --graph $NavDataDir), or RynthNav will ignore it." } + $idText = ($navFiles | ForEach-Object { "$($_.Name) $(Sha256 $_.FullName)" }) -join "`n" + $navId = (Sha256Text $idText).Substring(0, 32) + # [long]: Measure-Object's Sum is a double, which ConvertTo-Json writes as 1383002945.0, and the + # launcher reads "bytes" with GetInt64 - a ".0" failed every launcher's update check (2026.10.3.1/2). + $navBytes = [long](($navFiles | Measure-Object Length -Sum).Sum) + if ($liveManifest -and $liveManifest.navdata -and $liveManifest.navdata.id -eq $navId) { + $navData = $liveManifest.navdata + # Carried over from the live feed (ConvertFrom-Json): force the whole numbers back to integers. + $navData = [ordered]@{ + id = [string]$navData.id + release = [long]$navData.release + url = [string]$navData.url + size = [long]$navData.size + sha256 = [string]$navData.sha256 + files = [long]$navData.files + bytes = [long]$navData.bytes + } + Write-Host " unchanged ($($navFiles.Count) files, id $navId): the live archive from release $($navData.release) stays" + } else { + $navZip = "$rel\RynthNav-NavData.zip" + Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem + $fs = [IO.File]::Open($navZip, 'CreateNew') + try { + $za = New-Object IO.Compression.ZipArchive($fs, [IO.Compression.ZipArchiveMode]::Create) + foreach ($f in $navFiles) { + [void][IO.Compression.ZipFileExtensions]::CreateEntryFromFile($za, $f.FullName, $f.Name, [IO.Compression.CompressionLevel]::Optimal) + } + $za.Dispose() + } finally { $fs.Dispose() } + $zi = Get-Item $navZip + $navData = [ordered]@{ + id = $navId + release = $release + url = "$BaseUrl/releases/$release/RynthNav-NavData.zip" + size = $zi.Length + sha256 = Sha256 $zi.FullName + files = $navFiles.Count + bytes = $navBytes + } + Write-Host (" new set: {0} files ({1} tiles), {2:N0} MB packed into {3:N0} MB, id {4}" -f $navFiles.Count, $tileCount, ($navBytes / 1MB), ($zi.Length / 1MB), $navId) + } +} + # ── 3. Manifest + signature ────────────────────────────────────────────────── Step "Writing and signing the manifest" $setup = Get-Item "$rel\RynthCore-Setup.exe" +# One line per plugin for the launcher's Available plugins list (launchers from 2026.10.5 on; +# older ones ignore the field, and a plugin without one falls back to the launcher's own table +# in RynthUpdater.Available.cs). Plain English for players, no names. +$pluginDescriptions = @{ + RynthAi = "The bot: combat, buffs, looting, navigation routes and metas." + RynthChat = "A chat window that sorts messages into tabs." + RynthTracker = "Kills, experience and luminance per hour for each session." + RynthNav = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB)." + RynthVision = "Shows unclimbable slopes, impassable water and your radar range in the world." + RynthLua = "Lua scripting for metas and your own scripts." + RynthOracle = "Quests, character, titles and leaderboards." + RynthInventory = "Search every character's items." +} $plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Name) { - [ordered]@{ - name = $dll.BaseName -replace '^RynthCore\.Plugin\.', '' + $pluginName = $dll.BaseName -replace '^RynthCore\.Plugin\.', '' + $entry = [ordered]@{ + name = $pluginName file = $dll.Name url = "$BaseUrl/releases/$release/plugins/$($dll.Name)" size = $dll.Length sha256 = Sha256 $dll.FullName } + if ($pluginDescriptions[$pluginName]) { $entry.description = $pluginDescriptions[$pluginName] } + else { Write-Warning "No description for $pluginName - the launcher shows its own (or none). Add one to `$pluginDescriptions." } + $entry } $manifest = [ordered]@{ schema = 1 @@ -176,6 +286,9 @@ $manifest = [ordered]@{ version = $Version published = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") notes = $Notes + # The changes, one line each: the launcher's update card shows a few as "What's new" + # (signed with the rest; launchers before 2026.10.5 ignore it and show the notes). + changes = @($Changes) core = [ordered]@{ release = $release version = $Version @@ -185,6 +298,7 @@ $manifest = [ordered]@{ } plugins = @($plugins) } +if ($navData) { $manifest.navdata = $navData } Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM & (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath "$rel\update.payload.json" -OutPath "$rel\update.json" -KeyDir $KeyDir if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" } @@ -213,9 +327,16 @@ scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$remoteRel/RynthCore-Setup.exe" if ($LASTEXITCODE -ne 0) { throw "scp of the installer failed" } scp -q (Get-ChildItem "$rel\plugins\*.dll").FullName "${SshHost}:$remoteRel/plugins/" if ($LASTEXITCODE -ne 0) { throw "scp of the plugins failed" } +$navSum = "" +if ($navZip) { + scp -q $navZip "${SshHost}:$remoteRel/RynthNav-NavData.zip" + if ($LASTEXITCODE -ne 0) { throw "scp of the RynthNav data archive failed" } + $navSum = " RynthNav-NavData.zip" +} -$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll" +$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll$navSum" $expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256 } +if ($navZip) { $expect["RynthNav-NavData.zip"] = $navData.sha256 } foreach ($pl in $plugins) { $expect["plugins/$($pl.file)"] = $pl.sha256 } foreach ($line in $remoteSums) { $sum, $name = $line -split '\s+', 2 diff --git a/installer/RynthCore.iss b/installer/RynthCore.iss index 907de00..31f65c1 100644 --- a/installer/RynthCore.iss +++ b/installer/RynthCore.iss @@ -13,7 +13,7 @@ AppId={{A8B4C2D1-E3F5-4678-9ABC-DEF012345678} AppName=RynthCore AppVersion=0.0.0 AppPublisher=RynthCore -AppPublisherURL=https://github.com/tombohar/RynthCore +AppPublisherURL=https://aelrynth.com/git/rynth/RynthCore DefaultDirName=C:\Games\RynthCore DisableDirPage=no DefaultGroupName=RynthCore @@ -79,6 +79,16 @@ Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Description: "Launch Rynth ; bring it back when the upgrade is done. Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser; Check: CmdLineParamExists('/RELAUNCH') +[UninstallRun] +; Decal + RynthCore (experimental): remove the Decal bridge's registration, only +; what the launcher added (see docs/DECAL_BRIDGE_PLAN.md). Every release ships the bridge +; ({app}\DecalBridge, staged by Build-Installer.ps1), so this always runs; with nothing +; registered it changes nothing. Runs before the files are removed. It removes both entries +; the installer writes (see RegisterDecalBridge in [Code]): the per-user one, and the +; machine-wide one - directly when the uninstaller is elevated, otherwise after Windows' +; administrator prompt, which appears only when a machine-wide entry exists. +Filename: "{app}\RynthCore.exe"; Parameters: "--decal-bridge-unregister"; Flags: runhidden waituntilterminated; RunOnceId: "RynthCoreDecalBridgeUnregister" + [Code] function CmdLineParamExists(const Value: string): Boolean; var @@ -92,3 +102,106 @@ begin Exit; end; end; + +(* ------------------------------------------------------------------------------------- + Decal + RynthCore (experimental): register the RynthCore Decal bridge on every install + AND every update (the launcher's updater runs this installer with /SILENT), in BOTH + places a Decal client can read its filter list from: + + 1. Machine-wide: HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters\{5B3E0D57-...} + (32-bit view). An elevated AC (RynthCore or AC run as administrator), or any AC when + UAC or its registry virtualization is off, reads ONLY this key - the per-user entry + is invisible to it (a player's Decal + RynthCore client never loaded the bridge, + 2026-10-03). A non-elevated AC without a per-user copy reads it too. + 2. Per-user: this user's VirtualStore copy of that key, ONLY if the copy already exists. + A non-elevated AC is virtualized and, once a copy exists, reads nothing but the copy. + A missing copy is never created: it would hide every HKLM filter added later from + this user's non-elevated clients. + + Both entries are harmless while no account uses Decal + RynthCore: every Decal client + loads the bridge, which stays idle (no hooks, no threads) unless the RynthCore loader is + in the same client. Uninstall removes both ([UninstallRun] --decal-bridge-unregister). + + Rights. This installer runs with the lowest privileges (PrivilegesRequired=lowest; the + updater starts it without elevation). Writing HKLM needs administrator rights, so: + - Setup already elevated (installed "for all users", or started by an elevated + launcher): written directly, no prompt. + - Not elevated: Windows' administrator prompt is shown ONCE - only when Decal is + installed, the machine-wide entry is missing or points at another folder, and this + user has a Decal + RynthCore account (decal-accounts.json). Saying no is harmless: + the launcher checks before every Decal + RynthCore launch and repairs it (writing it + directly when it runs elevated, the case that needs it). + The commands are RynthCore.exe's own (Program.cs): --decal-bridge-register-machine and + --decal-bridge-install-user, so the installer and the launcher write identical entries. + ------------------------------------------------------------------------------------- *) +const + BridgeEntryKey = 'SOFTWARE\Decal\NetworkFilters\{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}'; + BridgeObject = 'RynthCore.DecalBridge.BridgeFilter'; + +function DecalInstalled: Boolean; +begin + Result := RegKeyExists(HKLM32, 'SOFTWARE\Decal\Agent'); +end; + +function BridgeDir: String; +begin + Result := ExpandConstant('{app}\DecalBridge'); +end; + +function MachineBridgeEntryCurrent: Boolean; +var + P, O: String; + E: Cardinal; +begin + Result := RegQueryStringValue(HKLM32, BridgeEntryKey, 'Path', P) and + (CompareText(RemoveBackslashUnlessRoot(P), BridgeDir) = 0) and + RegQueryStringValue(HKLM32, BridgeEntryKey, 'Object', O) and (O = BridgeObject) and + RegQueryDWordValue(HKLM32, BridgeEntryKey, 'Enabled', E) and (E = 1); +end; + +function UsesDecalBridge: Boolean; +begin + Result := FileExists(ExpandConstant('{userappdata}\RynthCore\decal-accounts.json')); +end; + +procedure RegisterDecalBridge; +var + Exe, Params: String; + Code: Integer; +begin + if not DecalInstalled then Exit; + if not FileExists(BridgeDir + '\RynthCore.DecalBridge.dll') then Exit; + Exe := ExpandConstant('{app}\RynthCore.exe'); + Params := '--decal-bridge-register-machine "' + BridgeDir + '"'; + if not MachineBridgeEntryCurrent then + begin + if IsAdmin then + begin + if not Exec(Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then + Log('Decal bridge: machine-wide registration did not start: ' + SysErrorMessage(Code)) + else + Log('Decal bridge: machine-wide registration exit code ' + IntToStr(Code)); + end + else if UsesDecalBridge then + begin + if not ShellExec('runas', Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then + Log('Decal bridge: elevated machine-wide registration not done (declined or failed): ' + SysErrorMessage(Code)) + else + Log('Decal bridge: elevated machine-wide registration exit code ' + IntToStr(Code)); + end + else + Log('Decal bridge: machine-wide entry missing; not elevated and no Decal + RynthCore account - left to the launcher.'); + end; + { Per-user half, as the user who started Setup (the same user unless Setup was elevated + with other credentials). } + if not ExecAsOriginalUser(Exe, '--decal-bridge-install-user "' + BridgeDir + '"', ExpandConstant('{app}'), + SW_HIDE, ewWaitUntilTerminated, Code) then + Log('Decal bridge: per-user step did not start: ' + SysErrorMessage(Code)); +end; + +procedure CurStepChanged(CurStep: TSetupStep); +begin + { After the files, before [Run] (which relaunches the launcher after an update). } + if CurStep = ssPostInstall then + RegisterDecalBridge; +end; diff --git a/native/Loader/Build-Loader.ps1 b/native/Loader/Build-Loader.ps1 new file mode 100644 index 0000000..89d22c9 --- /dev/null +++ b/native/Loader/Build-Loader.ps1 @@ -0,0 +1,36 @@ +# Build-Loader.ps1 +# Compiles the native RynthCore.Loader.dll (x86 MSVC) into native\Loader\bin. +# Does not deploy: copy it to Runtime\ yourself (a running client keeps the old loader +# until it restarts; the loader is injected once per process). + +$ErrorActionPreference = "Stop" + +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" ` + -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 ` + -property installationPath 2>$null +if (-not $vsPath) { Write-Error "Visual Studio with C++ tools not found."; exit 1 } + +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$cl = "$vcBase\bin\Hostx86\x86\cl.exe" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" + +$src = $PSScriptRoot +$out = Join-Path $src "bin" +$obj = Join-Path $out "obj" +New-Item -ItemType Directory -Path $out, $obj -Force | Out-Null + +Write-Host "Compiling RynthCore.Loader.dll (MSVC $vcVer, x86)..." +Push-Location $obj +try { + & $cl /nologo /O2 /MT /GS /W4 /wd4100 /LD /Zi "$src\Loader.c" "$src\Hooks.c" "$src\Clr.c" "$src\Services.c" user32.lib ` + /link /MACHINE:X86 /DEF:"$src\Loader.def" /DEBUG /OPT:REF /OUT:"$out\RynthCore.Loader.dll" /PDB:"$out\RynthCore.Loader.pdb" + if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE } +} finally { Pop-Location } + +$size = (Get-Item "$out\RynthCore.Loader.dll").Length +Write-Host "Built: $out\RynthCore.Loader.dll ($size bytes)" diff --git a/native/Loader/Clr.c b/native/Loader/Clr.c new file mode 100644 index 0000000..3db0e30 --- /dev/null +++ b/native/Loader/Clr.c @@ -0,0 +1,175 @@ +// ============================================================================ +// Clr.c - hosts CoreCLR once, from the app-local runtime in Runtime\dotnet\, and +// talks to RynthCore.Shim.dll (default ALC), which owns the collectible +// AssemblyLoadContext each engine generation lives in. +// +// The raw coreclr_* API is used (no hostfxr, runtimeconfig.json or deps.json): the +// TPA list is every managed DLL in Runtime\dotnet\ plus the Shim. The engine and its +// own dependencies (Avalonia, ImGui.NET, ...) are NOT on the TPA list: the Shim loads +// them into the engine's collectible ALC, so they go away with it. +// ============================================================================ + +#include "Loader.h" +#include + +typedef int (__stdcall *coreclr_initialize_fn)(const char* exePath, const char* appDomainFriendlyName, + int propertyCount, const char** propertyKeys, const char** propertyValues, + void** hostHandle, unsigned int* domainId); +typedef int (__stdcall *coreclr_create_delegate_fn)(void* hostHandle, unsigned int domainId, + const char* assemblyName, const char* typeName, const char* methodName, void** fn); + +// Shared with RynthCore.Shim (ShimHost.cs): keep the layouts in step. +typedef struct LoaderApi { + int size; + void (__stdcall *log)(const char* level, const char* utf8); + int (__stdcall *freeMb)(int* largestMb); + const char* loaderDir; + int (__stdcall *hookCount)(void); +} LoaderApi; + +typedef struct ShimApi { + int size; + int (__stdcall *loadEngine)(int generation, const char* stagedPathUtf8); + int (__stdcall *unloadEngine)(void); // 1 = the ALC was freed + void* (__stdcall *engineExport)(const char* nameUtf8); +} ShimApi; + +typedef int (__stdcall *shim_init_fn)(LoaderApi* api, ShimApi* out); + +static LoaderApi g_loaderApi; +static ShimApi g_shim; +static int g_started; + +int __stdcall RcHooks_Count(void); + +static void __stdcall ShimLog(const char* level, const char* utf8) { LoaderLog(level ? level : "INF", "[shim] %s", utf8); } +static int __stdcall ShimFreeMb(int* largestMb) +{ + long largest; + long free = LoaderFreeAddressSpaceMb(&largest); + if (largestMb) *largestMb = (int)largest; + return (int)free; +} + +static int IsNativeRuntimeFile(const char* n) +{ + static const char* natives[] = { + "coreclr.dll", "clrjit.dll", "clrgc.dll", "clrgcexp.dll", "hostfxr.dll", "hostpolicy.dll", + "mscordaccore.dll", "mscordbi.dll", "mscorrc.dll", "clretwrc.dll", "msquic.dll", + "System.IO.Compression.Native.dll", "Microsoft.DiaSymReader.Native.x86.dll", + }; + for (int i = 0; i < (int)(sizeof natives / sizeof natives[0]); i++) + if (!_stricmp(n, natives[i])) return 1; + return !_strnicmp(n, "mscordaccore_", 13); +} + +static int AppendDlls(char* tpa, size_t cap, const char* dir) +{ + char pattern[MAX_PATH]; + _snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\*.dll", dir); + WIN32_FIND_DATAA fd; + HANDLE h = FindFirstFileA(pattern, &fd); + if (h == INVALID_HANDLE_VALUE) return 0; + int n = 0; + do { + if (IsNativeRuntimeFile(fd.cFileName)) continue; + strcat_s(tpa, cap, dir); + strcat_s(tpa, cap, "\\"); + strcat_s(tpa, cap, fd.cFileName); + strcat_s(tpa, cap, ";"); + n++; + } while (FindNextFileA(h, &fd)); + FindClose(h); + return n; +} + +int ClrStart(const char* loaderDir) +{ + if (g_started) return 0; + char runtimeDir[MAX_PATH], coreclrPath[MAX_PATH], shimPath[MAX_PATH]; + _snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\dotnet", loaderDir); + _snprintf_s(coreclrPath, sizeof coreclrPath, _TRUNCATE, "%s\\coreclr.dll", runtimeDir); + _snprintf_s(shimPath, sizeof shimPath, _TRUNCATE, "%s\\RynthCore.Shim.dll", loaderDir); + if (GetFileAttributesA(shimPath) == INVALID_FILE_ATTRIBUTES) { + LoaderLog("ERR", "CLR: %s is missing", shimPath); + return 1; + } + + long free0 = LoaderFreeAddressSpaceMb(NULL); + DWORD t0 = GetTickCount(); + HMODULE clr = LoadLibraryExA(coreclrPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + if (!clr) { + LoaderLog("ERR", "CLR: LoadLibrary %s failed (error %lu)", coreclrPath, GetLastError()); + return 2; + } + coreclr_initialize_fn init = (coreclr_initialize_fn)GetProcAddress(clr, "coreclr_initialize"); + coreclr_create_delegate_fn create = (coreclr_create_delegate_fn)GetProcAddress(clr, "coreclr_create_delegate"); + if (!init || !create) return 3; + + static char tpa[128 * 1024]; + tpa[0] = 0; + int count = AppendDlls(tpa, sizeof tpa, runtimeDir); + strcat_s(tpa, sizeof tpa, shimPath); + strcat_s(tpa, sizeof tpa, ";"); + + char nativeDirs[2 * MAX_PATH + 4], baseDir[MAX_PATH + 2]; + _snprintf_s(nativeDirs, sizeof nativeDirs, _TRUNCATE, "%s;%s;", loaderDir, runtimeDir); + _snprintf_s(baseDir, sizeof baseDir, _TRUNCATE, "%s\\", loaderDir); + const char* keys[] = { + "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "APP_CONTEXT_BASE_DIRECTORY", + "System.GC.Server", "System.GC.Concurrent", "System.Globalization.Invariant", "System.GC.RetainVM", + }; + // Concurrent (background) GC on: the engine and the managed plugins share this one GC, + // and with it off every gen2 (~every 10 s, driven by large allocations) was a fully + // blocking 55-66 ms pause that AC's main thread hit whenever it was in managed code. + const char* values[] = { + tpa, "", nativeDirs, baseDir, + "false", "true", "true", "false", + }; + char exePath[MAX_PATH]; + GetModuleFileNameA(NULL, exePath, MAX_PATH); + void* hostHandle = NULL; + unsigned int domainId = 0; + int hr = init(exePath, "RynthCore", (int)(sizeof keys / sizeof keys[0]), keys, values, &hostHandle, &domainId); + if (hr < 0) { + LoaderLog("ERR", "CLR: coreclr_initialize failed 0x%08x", hr); + return 4; + } + + shim_init_fn shimInit = NULL; + hr = create(hostHandle, domainId, "RynthCore.Shim", "RynthCore.Shim.ShimHost", "Init", (void**)&shimInit); + if (hr < 0 || !shimInit) { + LoaderLog("ERR", "CLR: RynthCore.Shim.ShimHost.Init not found (0x%08x)", hr); + return 5; + } + g_loaderApi.size = sizeof g_loaderApi; + g_loaderApi.log = ShimLog; + g_loaderApi.freeMb = ShimFreeMb; + g_loaderApi.loaderDir = LoaderDirectory(); + g_loaderApi.hookCount = RcHooks_Count; + g_shim.size = sizeof g_shim; + int rc = shimInit(&g_loaderApi, &g_shim); + if (rc != 0 || !g_shim.loadEngine || !g_shim.unloadEngine || !g_shim.engineExport) { + LoaderLog("ERR", "CLR: Shim init failed (rc=%d)", rc); + return 6; + } + g_started = 1; + LoaderLog("INF", "CLR: CoreCLR up in %lu ms from %s (%d framework assemblies), %ld MB of address space used.", + GetTickCount() - t0, runtimeDir, count, free0 - LoaderFreeAddressSpaceMb(NULL)); + return 0; +} + +int ClrLoadEngine(int generation, const char* stagedPath) +{ + return g_started ? g_shim.loadEngine(generation, stagedPath) : -1; +} + +void ClrUnloadEngine(void) +{ + if (g_started) g_shim.unloadEngine(); +} + +void* ClrEngineExport(const char* name) +{ + return g_started ? g_shim.engineExport(name) : NULL; +} diff --git a/native/Loader/Hooks.c b/native/Loader/Hooks.c new file mode 100644 index 0000000..2f0afce --- /dev/null +++ b/native/Loader/Hooks.c @@ -0,0 +1,332 @@ +// ============================================================================ +// Hooks.c - MinHook facade with permanent stubs +// +// Exports MinHook's API (MH_Initialize, MH_CreateHook, MH_EnableHook, ...) with the +// same signatures and status codes, so the engine's Hooking/MinHook.cs can call either +// this facade or minhook.x86.dll. +// +// The difference: nothing native ever points at engine code directly. For every target +// the facade allocates a permanent 6-byte stub, `jmp dword ptr [slot]`, and installs the +// real MinHook hook once, with the stub as the detour. The slot holds either the +// engine's detour (hook enabled) or MinHook's trampoline (hook disabled: a transparent +// pass-through to the original, whatever the calling convention). A reload only +// re-points slots, so an engine generation can be unloaded as soon as no thread is +// inside its code, and the next generation's MH_CreateHook for the same target reuses +// the same stub and gets the same trampoline back. +// +// Hooks are "owned" by the generation that created them: MH_CreateHook on a target +// created by an earlier generation succeeds (no MH_ERROR_ALREADY_CREATED), and +// HooksPassThroughAll() (every reload) turns every slot back into a pass-through and +// takes the patch out of the target (MinHook disable: original bytes back), so the next +// generation's pattern scans see AC's real prologues; its MH_CreateHook puts it back. +// The stub and trampoline are never freed, so a thread still returning through them is +// safe. +// +// Patching is batched. Every MinHook enable/disable freezes all the process's threads +// (a system-wide thread snapshot, ~100 ms here), and an engine installs ~60 hooks: one +// freeze each made up ~7 s of every reload. The facade records which targets should be +// patched and applies them in one queued MinHook freeze: straight after the engine's +// init export returns (HooksFlush; on a first launch AC's main thread is still suspended +// then), on every reload, and ~20 ms after the last change otherwise (a background +// flusher). A hook's slot is set at once; its patch follows within that window. +// ============================================================================ + +#include "Loader.h" +#include + +#define MH_OK 0 +#define MH_ERROR_ALREADY_INITIALIZED 1 +#define MH_ERROR_NOT_INITIALIZED 2 +#define MH_ERROR_ALREADY_CREATED 3 +#define MH_ERROR_NOT_CREATED 4 +#define MH_ERROR_ENABLED 5 +#define MH_ERROR_DISABLED 6 +#define MH_ERROR_MEMORY_ALLOC 9 +#define MH_UNKNOWN -1 + +#define MAX_HOOKS 1024 +#define STUB_SIZE 8 + +typedef int (__stdcall *mh_init_fn)(void); +typedef int (__stdcall *mh_create_fn)(void* target, void* detour, void** original); +typedef int (__stdcall *mh_target_fn)(void* target); +typedef const char* (__stdcall *mh_status_fn)(int status); + +typedef struct HookEntry { + void* target; + void* trampoline; // MinHook's call-the-original trampoline (never freed) + void* detour; // the owning generation's detour, or NULL once removed + int generation; // generation that last created it + int created; // created (and not removed) by `generation` + int enabled; // slot == detour + int patched; // MinHook's jump is in the target + int want; // it should be (applied by the next flush) +} HookEntry; + +static CRITICAL_SECTION g_lock; +static int g_ready; +static int g_generation; +static HMODULE g_minhook; +static mh_init_fn p_init; +static mh_create_fn p_create; +static mh_target_fn p_enable; +static mh_target_fn p_disable; +static mh_target_fn p_queueDisable; +static mh_target_fn p_queueEnable; +static mh_init_fn p_applyQueued; +static mh_status_fn p_status; + +static HookEntry g_hooks[MAX_HOOKS]; +static void* volatile g_slots[MAX_HOOKS]; +static unsigned char* g_stubs; +static int g_count; +static HANDLE g_dirtyEvent; +static volatile DWORD g_lastChange; + +static void FlushLocked(const char* why); + +static DWORD WINAPI Flusher(LPVOID unused) +{ + (void)unused; + for (;;) { + WaitForSingleObject(g_dirtyEvent, INFINITE); + do Sleep(20); while (GetTickCount() - g_lastChange < 20); // settle: one freeze per burst + EnterCriticalSection(&g_lock); + FlushLocked("batched"); + LeaveCriticalSection(&g_lock); + } +} + +int HooksInit(const char* loaderDir) +{ + InitializeCriticalSection(&g_lock); + char path[MAX_PATH]; + _snprintf_s(path, sizeof path, _TRUNCATE, "%s\\minhook.x86.dll", loaderDir); + g_minhook = LoadLibraryA(path); + if (!g_minhook) g_minhook = LoadLibraryA("minhook.x86.dll"); + if (!g_minhook) return 0; + p_init = (mh_init_fn)GetProcAddress(g_minhook, "MH_Initialize"); + p_create = (mh_create_fn)GetProcAddress(g_minhook, "MH_CreateHook"); + p_enable = (mh_target_fn)GetProcAddress(g_minhook, "MH_EnableHook"); + p_disable = (mh_target_fn)GetProcAddress(g_minhook, "MH_DisableHook"); + p_queueDisable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueDisableHook"); + p_queueEnable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueEnableHook"); + p_applyQueued = (mh_init_fn)GetProcAddress(g_minhook, "MH_ApplyQueued"); + p_status = (mh_status_fn)GetProcAddress(g_minhook, "MH_StatusToString"); + if (!p_init || !p_create || !p_enable || !p_disable) return 0; + int st = p_init(); + if (st != MH_OK && st != MH_ERROR_ALREADY_INITIALIZED) { + LoaderLog("ERR", "Hooks: MH_Initialize = %d", st); + return 0; + } + g_stubs = (unsigned char*)VirtualAlloc(NULL, MAX_HOOKS * STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (!g_stubs) return 0; + g_dirtyEvent = CreateEventA(NULL, FALSE, FALSE, NULL); + if (p_queueEnable && p_queueDisable && p_applyQueued && g_dirtyEvent) { + HANDLE t = CreateThread(NULL, 0, Flusher, NULL, 0, NULL); + if (t) CloseHandle(t); + } + g_ready = 1; + LoaderLog("INF", "Hooks: MinHook facade ready (%s, %d stub slots, %s patching).", path, MAX_HOOKS, + p_queueEnable ? "batched" : "per-hook"); + return 1; +} + +void HooksBeginGeneration(int generation) +{ + EnterCriticalSection(&g_lock); + g_generation = generation; + LeaveCriticalSection(&g_lock); +} + +static void SetPatched(int i, int patched) +{ + HookEntry* e = &g_hooks[i]; + if (e->patched == patched) return; + int st = patched ? p_enable(e->target) : p_disable(e->target); + if (st == MH_OK) e->patched = patched; + else LoaderLog("ERR", "Hooks: MinHook %s %p failed: %d", patched ? "enable" : "disable", e->target, st); +} + +// Records whether target i should be patched; the next flush applies it. (Caller holds g_lock.) +static void Want(int i, int patched) +{ + HookEntry* e = &g_hooks[i]; + e->want = patched; + if (e->want == e->patched) return; + if (!p_queueEnable || !p_queueDisable || !p_applyQueued || !g_dirtyEvent) { + SetPatched(i, patched); // no queue in this MinHook: one at a time + return; + } + g_lastChange = GetTickCount(); + SetEvent(g_dirtyEvent); +} + +// Applies every pending patch/unpatch in one MinHook freeze. (Caller holds g_lock.) +static void FlushLocked(const char* why) +{ + static int queued[MAX_HOOKS]; + int n = 0; + for (int i = 0; i < g_count; i++) { + HookEntry* e = &g_hooks[i]; + if (e->want == e->patched) continue; + int st = e->want ? p_queueEnable(e->target) : p_queueDisable(e->target); + if (st == MH_OK) queued[n++] = i; + else SetPatched(i, e->want); + } + if (n == 0) return; + DWORD t0 = GetTickCount(); + int st = p_applyQueued(); + if (st == MH_OK) { + for (int k = 0; k < n; k++) g_hooks[queued[k]].patched = g_hooks[queued[k]].want; + LoaderLog("INF", "Hooks: %d patch(es) applied in one freeze (%lu ms, %s).", n, GetTickCount() - t0, why); + } else { + LoaderLog("ERR", "Hooks: MH_ApplyQueued (%d, %s) = %d; applying one at a time.", n, why, st); + for (int k = 0; k < n; k++) SetPatched(queued[k], g_hooks[queued[k]].want); + } +} + +void HooksFlush(void) +{ + if (!g_ready) return; + EnterCriticalSection(&g_lock); + FlushLocked("engine init"); + LeaveCriticalSection(&g_lock); +} + +static void SetSlot(int i, int enabled) +{ + HookEntry* e = &g_hooks[i]; + e->enabled = enabled; + InterlockedExchangePointer((PVOID volatile*)&g_slots[i], enabled ? e->detour : e->trampoline); +} + +void HooksPassThroughAll(void) +{ + if (!g_ready) return; + EnterCriticalSection(&g_lock); + int live = 0; + for (int i = 0; i < g_count; i++) { + if (g_hooks[i].enabled) live++; + SetSlot(i, 0); + Want(i, 0); + g_hooks[i].created = 0; + g_hooks[i].detour = NULL; + } + FlushLocked("reload"); // AC's own prologues back, now + LeaveCriticalSection(&g_lock); + LoaderLog("INF", "Hooks: %d hook(s) now pass straight through (%d were still enabled).", g_count, live); +} + +static int Find(void* target) +{ + for (int i = 0; i < g_count; i++) + if (g_hooks[i].target == target) return i; + return -1; +} + +// --- MinHook API ------------------------------------------------------------ + +int __stdcall MH_Initialize(void) { return g_ready ? MH_ERROR_ALREADY_INITIALIZED : MH_ERROR_NOT_INITIALIZED; } + +// Hooks outlive every engine generation; "uninitialize" only turns them into pass-throughs. +int __stdcall MH_Uninitialize(void) { HooksPassThroughAll(); return MH_OK; } + +int __stdcall MH_CreateHook(void* target, void* detour, void** original) +{ + if (!g_ready) return MH_ERROR_NOT_INITIALIZED; + int st = MH_OK; + EnterCriticalSection(&g_lock); + int i = Find(target); + if (i >= 0) { + HookEntry* e = &g_hooks[i]; + if (e->created && e->generation == g_generation) { + st = MH_ERROR_ALREADY_CREATED; + } else { + e->detour = detour; + e->generation = g_generation; + e->created = 1; + SetSlot(i, 0); + Want(i, 1); + if (original) *original = e->trampoline; + } + } else if (g_count >= MAX_HOOKS) { + st = MH_ERROR_MEMORY_ALLOC; + } else { + i = g_count; + unsigned char* stub = g_stubs + i * STUB_SIZE; + void* volatile* slot = &g_slots[i]; + stub[0] = 0xFF; stub[1] = 0x25; // jmp dword ptr [slot] + *(void* volatile**)(stub + 2) = slot; + stub[6] = 0xCC; stub[7] = 0xCC; + FlushInstructionCache(GetCurrentProcess(), stub, STUB_SIZE); + + void* tramp = NULL; + st = p_create(target, stub, &tramp); + if (st == MH_OK) { + HookEntry* e = &g_hooks[i]; + e->target = target; + e->trampoline = tramp; + e->detour = detour; + e->generation = g_generation; + e->created = 1; + e->enabled = 0; + *slot = tramp; // pass-through until the engine enables it + g_count++; + e->patched = 0; + Want(i, 1); // the patch goes in (slot passes through) + st = MH_OK; + if (original) *original = tramp; + } + } + LeaveCriticalSection(&g_lock); + return st; +} + +int __stdcall MH_RemoveHook(void* target) +{ + if (!g_ready) return MH_ERROR_NOT_INITIALIZED; + int st = MH_OK; + EnterCriticalSection(&g_lock); + int i = Find(target); + if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED; + else { + SetSlot(i, 0); + Want(i, 0); // original bytes back, like MinHook's remove + g_hooks[i].created = 0; + g_hooks[i].detour = NULL; + } + LeaveCriticalSection(&g_lock); + return st; +} + +static int SetEnabled(void* target, int enable) +{ + if (!g_ready) return MH_ERROR_NOT_INITIALIZED; + int st = MH_OK; + EnterCriticalSection(&g_lock); + if (target == NULL) { // MH_ALL_HOOKS + for (int i = 0; i < g_count; i++) + if (g_hooks[i].created && g_hooks[i].enabled != enable) SetSlot(i, enable); + } else { + int i = Find(target); + if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED; + else if (g_hooks[i].enabled == enable) st = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED; + else SetSlot(i, enable); + } + LeaveCriticalSection(&g_lock); + return st; +} + +int __stdcall MH_EnableHook(void* target) { return SetEnabled(target, 1); } +int __stdcall MH_DisableHook(void* target) { return SetEnabled(target, 0); } + +const char* __stdcall MH_StatusToString(int status) +{ + if (p_status) return p_status(status); + return status == MH_OK ? "MH_OK" : "MH_UNKNOWN"; +} + +// Lets the engine tell this facade from minhook.x86.dll (and an old NativeAOT loader). +int __stdcall RcHooks_Version(void) { return 1; } +int __stdcall RcHooks_Count(void) { return g_count; } diff --git a/native/Loader/Loader.c b/native/Loader/Loader.c new file mode 100644 index 0000000..a9dd57b --- /dev/null +++ b/native/Loader/Loader.c @@ -0,0 +1,407 @@ +// ============================================================================ +// RynthCore.Loader.dll - native loader (docs/UNLOADABLE_ENGINE_PLAN.md, Phase 1) +// +// Injected into acclient.exe by RynthCore.Injector / the launcher, which call the +// RynthCoreInit export on a remote thread (same contract as the old NativeAOT loader). +// +// Two engine hosts, chosen by looking at Runtime\RynthCore.Engine.dll: +// - NativeAOT engine (a native DLL exporting RynthCoreEngineInit): staged to +// .engine_loads\, LoadLibrary'd, never freed. Today's behaviour. +// - Managed engine (a PE with a CLR header): the loader starts CoreCLR once from +// Runtime\dotnet\ and hands the engine to RynthCore.Shim.dll (default ALC), which +// loads each generation into a collectible AssemblyLoadContext and unloads it on +// reload, so a reload gives its memory back. +// +// Either way the loader owns the reload event, the file watcher, the address-space +// guard and a MinHook facade (Hooks.c): every hook is installed once, through a +// permanent stub, and a reload only re-points the stub. +// ============================================================================ + +#include "Loader.h" + +#include +#include + +#define ENGINE_DLL_NAME "RynthCore.Engine.dll" +#define ENGINE_INIT_EXPORT "RynthCoreEngineInit" +#define ENGINE_SHUTDOWN_EXPORT "RynthCoreShutdown" +#define ENGINE_REFUSED_EXPORT "RynthCoreReloadRefused" +#define LOG_DIR "C:\\Games\\RynthCore\\Logs" +#define STAGING_SUBDIR ".engine_loads" +#define MIN_RELOAD_INTERVAL_MS 1500 +// A managed engine gives its memory back on reload, so the guard only has to keep +// room for one more generation; the NativeAOT engine leaks every generation. +#define MIN_FREE_MB_AOT 1200 +#define MIN_FREE_MB_CLR 500 + +typedef unsigned int (__stdcall *engine_u32_fn)(void* param); +typedef unsigned int (__stdcall *engine_refused_fn)(int freeMb); + +static volatile LONG g_initialized; +static char g_loaderDir[MAX_PATH]; +static char g_enginePath[MAX_PATH]; +static int g_engineIsManaged; +static HMODULE g_engineModule; // NativeAOT host only +static int g_initCount; +static HANDLE g_reloadEvent; +static FILETIME g_canonicalWrite; +static volatile LONG g_reloadInFlight; +static volatile ULONGLONG g_lastReloadDone; +static CRITICAL_SECTION g_logLock; + +// --------------------------------------------------------------------------- +// Logging: same per-client file and line format as the engine (LogPaths.cs). +// --------------------------------------------------------------------------- + +void LoaderLog(const char* level, const char* fmt, ...) +{ + char msg[3072]; + va_list ap; + va_start(ap, fmt); + _vsnprintf_s(msg, sizeof msg, _TRUNCATE, fmt, ap); + va_end(ap); + + SYSTEMTIME t; + GetLocalTime(&t); + char line[3300]; + int n = _snprintf_s(line, sizeof line, _TRUNCATE, "[%02d:%02d:%02d.%03d] [pid:%lu] [%s] [loader] %s\r\n", + t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, GetCurrentProcessId(), level, msg); + if (n < 0) n = (int)strlen(line); + + char path[MAX_PATH]; + _snprintf_s(path, sizeof path, _TRUNCATE, LOG_DIR "\\RynthCore.%lu.log", GetCurrentProcessId()); + EnterCriticalSection(&g_logLock); + CreateDirectoryA("C:\\Games\\RynthCore", NULL); + CreateDirectoryA(LOG_DIR, NULL); + for (int attempt = 0; attempt < 4; attempt++) { + HANDLE h = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (h != INVALID_HANDLE_VALUE) { + DWORD written; + WriteFile(h, line, (DWORD)n, &written, NULL); + CloseHandle(h); + break; + } + Sleep(5); + } + LeaveCriticalSection(&g_logLock); + OutputDebugStringA(line); +} + +// --------------------------------------------------------------------------- +// Address space +// --------------------------------------------------------------------------- + +long LoaderFreeAddressSpaceMb(long* largestMb) +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress; + unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress; + unsigned long long total = 0, largest = 0; + MEMORY_BASIC_INFORMATION mbi; + while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) { + if (mbi.RegionSize == 0) break; + if (mbi.State == MEM_FREE) { + total += mbi.RegionSize; + if (mbi.RegionSize > largest) largest = mbi.RegionSize; + } + p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize; + } + if (largestMb) *largestMb = (long)(largest / (1024 * 1024)); + return (long)(total / (1024 * 1024)); +} + +// --------------------------------------------------------------------------- +// Engine file: staging and kind +// --------------------------------------------------------------------------- + +static int FileLastWrite(const char* path, FILETIME* out) +{ + WIN32_FILE_ATTRIBUTE_DATA d; + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &d)) return 0; + *out = d.ftLastWriteTime; + return 1; +} + +// 1 = the file is a .NET assembly (PE with a CLR header), 0 = native, -1 = unreadable. +static int IsManagedPe(const char* path) +{ + HANDLE h = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (h == INVALID_HANDLE_VALUE) return -1; + unsigned char buf[4096]; + DWORD read = 0; + BOOL ok = ReadFile(h, buf, sizeof buf, &read, NULL); + CloseHandle(h); + if (!ok || read < sizeof(IMAGE_DOS_HEADER)) return -1; + IMAGE_DOS_HEADER* dos = (IMAGE_DOS_HEADER*)buf; + if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew <= 0 || + (DWORD)dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32) > read) return -1; + IMAGE_NT_HEADERS32* nt = (IMAGE_NT_HEADERS32*)(buf + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE) return -1; + if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0; + if (nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR) return 0; + return nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress != 0; +} + +static void CleanStaleStagingFiles(const char* stagingDir) +{ + char pattern[MAX_PATH]; + _snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\RynthCore.Engine.p*.gen*.*", stagingDir); // .dll + .pdb + WIN32_FIND_DATAA fd; + HANDLE f = FindFirstFileA(pattern, &fd); + if (f == INVALID_HANDLE_VALUE) return; + do { + char p[MAX_PATH]; + _snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", stagingDir, fd.cFileName); + DeleteFileA(p); // fails for files a live process still maps: fine + } while (FindNextFileA(f, &fd)); + FindClose(f); +} + +// Copies the canonical engine to .engine_loads\RynthCore.Engine.p.gen.dll so the +// canonical file is never locked (a developer can copy over it) and every generation is +// a distinct module/assembly path. +static int StageEngine(int generation, char* stagedPath, size_t cap) +{ + char stagingDir[MAX_PATH]; + _snprintf_s(stagingDir, sizeof stagingDir, _TRUNCATE, "%s\\" STAGING_SUBDIR, g_loaderDir); + CreateDirectoryA(stagingDir, NULL); + CleanStaleStagingFiles(stagingDir); + _snprintf_s(stagedPath, cap, _TRUNCATE, "%s\\RynthCore.Engine.p%lu.gen%d.dll", + stagingDir, GetCurrentProcessId(), generation); + if (!CopyFileA(g_enginePath, stagedPath, FALSE)) { + LoaderLog("ERR", "StageEngine: copy to %s failed (error %lu)", stagedPath, GetLastError()); + return 0; + } + if (g_engineIsManaged) { + // The debug symbols travel with the assembly so stack traces keep line numbers. + char srcPdb[MAX_PATH], dstPdb[MAX_PATH]; + _snprintf_s(srcPdb, sizeof srcPdb, _TRUNCATE, "%s\\RynthCore.Engine.pdb", g_loaderDir); + _snprintf_s(dstPdb, sizeof dstPdb, _TRUNCATE, "%.*s.pdb", (int)(strlen(stagedPath) - 4), stagedPath); + CopyFileA(srcPdb, dstPdb, FALSE); + } + LoaderLog("INF", "Staged engine for gen %d at %s", generation, stagedPath); + return 1; +} + +// --------------------------------------------------------------------------- +// Engine calls, whichever host +// --------------------------------------------------------------------------- + +static void* EngineExport(const char* name) +{ + if (g_engineIsManaged) return ClrEngineExport(name); + return g_engineModule ? (void*)GetProcAddress(g_engineModule, name) : NULL; +} + +static unsigned int LoadAndInitEngine(void) +{ + g_initCount++; + HooksBeginGeneration(g_initCount); + + char staged[MAX_PATH]; + if (!StageEngine(g_initCount, staged, sizeof staged)) return 11; + if (!FileLastWrite(g_enginePath, &g_canonicalWrite)) GetSystemTimeAsFileTime(&g_canonicalWrite); + + if (g_engineIsManaged) { + int rc = ClrLoadEngine(g_initCount, staged); + if (rc != 0) { + LoaderLog("ERR", "Managed engine gen %d failed to load (rc=%d)", g_initCount, rc); + return 4; + } + } else { + HMODULE m = LoadLibraryA(staged); + if (!m) { + LoaderLog("ERR", "LoadLibrary failed for engine (path=%s, error %lu)", staged, GetLastError()); + return 4; + } + g_engineModule = m; + LoaderLog("INF", "Engine module loaded at 0x%08p from %s", (void*)m, staged); + } + + engine_u32_fn init = (engine_u32_fn)EngineExport(ENGINE_INIT_EXPORT); + if (!init) { + LoaderLog("ERR", "Engine missing export '%s'", ENGINE_INIT_EXPORT); + return 5; + } + unsigned int rc = init((void*)(INT_PTR)g_initCount); + // The hooks the engine installed during init go in now, in one freeze, before the + // injector resumes AC's main thread (first launch) or the new generation runs. + HooksFlush(); + LoaderLog("INF", ENGINE_INIT_EXPORT "(initCount=%d) returned %u.", g_initCount, rc); + return rc; +} + +static void Reload(void) +{ + long largest; + long freeBefore = LoaderFreeAddressSpaceMb(&largest); + LoaderLog("INF", "Reload requested (gen %d, %ld MB free, largest %ld MB).", g_initCount, freeBefore, largest); + + engine_u32_fn shutdown = (engine_u32_fn)EngineExport(ENGINE_SHUTDOWN_EXPORT); + if (shutdown) { + unsigned int rc = shutdown(NULL); + LoaderLog("INF", ENGINE_SHUTDOWN_EXPORT " returned %u.", rc); + } else { + LoaderLog("WRN", "Engine has no '%s' export; skipping graceful shutdown.", ENGINE_SHUTDOWN_EXPORT); + } + + // Whatever the engine left enabled now passes straight through to AC. + HooksPassThroughAll(); + ServicesReleaseAll(); + Sleep(150); + + if (g_engineIsManaged) { + ClrUnloadEngine(); + } else if (g_engineModule) { + // A NativeAOT module can't be freed (its runtime keeps threads with frames in it). + LoaderLog("INF", "Reload: NativeAOT engine 0x%08p left mapped (can't unload).", (void*)g_engineModule); + g_engineModule = NULL; + } + + unsigned int rc = LoadAndInitEngine(); + long freeAfter = LoaderFreeAddressSpaceMb(&largest); + LoaderLog(rc == 0 ? "INF" : "ERR", "Reload: %s (gen %d, %ld MB free, %+ld MB vs before the reload).", + rc == 0 ? "complete" : "re-init FAILED", g_initCount, freeAfter, freeAfter - freeBefore); +} + +// --------------------------------------------------------------------------- +// Reload triggers: the engine's named event, and the canonical DLL changing on disk +// --------------------------------------------------------------------------- + +static DWORD WINAPI ReloadWatcher(LPVOID unused) +{ + (void)unused; + for (;;) { + if (WaitForSingleObject(g_reloadEvent, INFINITE) != WAIT_OBJECT_0) { Sleep(100); continue; } + + ULONGLONG last = g_lastReloadDone; + if (last != 0 && GetTickCount64() - last < MIN_RELOAD_INTERVAL_MS) { + LoaderLog("INF", "ReloadWatcher: signal %llu ms after the last reload; coalesced.", GetTickCount64() - last); + continue; + } + + long minFree = g_engineIsManaged ? MIN_FREE_MB_CLR : MIN_FREE_MB_AOT; + long freeMb = LoaderFreeAddressSpaceMb(NULL); + if (freeMb < minFree) { + LoaderLog("WRN", "ReloadWatcher: reload REFUSED - only %ld MB of address space free (need %ld MB). " + "Restart the client to load the new engine.", freeMb, minFree); + engine_refused_fn refused = (engine_refused_fn)EngineExport(ENGINE_REFUSED_EXPORT); + if (refused) refused((int)freeMb); + continue; + } + + if (InterlockedCompareExchange(&g_reloadInFlight, 1, 0) != 0) { + LoaderLog("INF", "ReloadWatcher: reload already in flight; coalesced."); + continue; + } + Reload(); + g_lastReloadDone = GetTickCount64(); + InterlockedExchange(&g_reloadInFlight, 0); + + int drained = 0; + while (WaitForSingleObject(g_reloadEvent, 0) == WAIT_OBJECT_0) drained++; + if (drained) LoaderLog("INF", "ReloadWatcher: drained %d signal(s) received during the reload.", drained); + } +} + +static DWORD WINAPI FileWatcher(LPVOID unused) +{ + (void)unused; + for (;;) { + Sleep(1000); + FILETIME now; + if (!FileLastWrite(g_enginePath, &now) || CompareFileTime(&now, &g_canonicalWrite) <= 0) continue; + // Let the writer (cp, dotnet publish) finish before staging from it. + Sleep(500); + FILETIME stable; + if (!FileLastWrite(g_enginePath, &stable) || CompareFileTime(&stable, &now) != 0) continue; + LoaderLog("INF", "FileWatcher: %s changed; signaling reload.", g_enginePath); + g_canonicalWrite = stable; + SetEvent(g_reloadEvent); + } +} + +// --------------------------------------------------------------------------- +// Exports +// --------------------------------------------------------------------------- + +const char* LoaderDirectory(void) { return g_loaderDir; } +int LoaderGeneration(void) { return g_initCount; } + +unsigned int __stdcall RynthCoreInit(void* param) +{ + (void)param; + if (InterlockedCompareExchange(&g_initialized, 1, 0) != 0) { + LoaderLog("WRN", "RynthCoreInit called twice; ignoring the second call."); + return 1; + } + + HMODULE self = NULL; + GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCSTR)&RynthCoreInit, &self); + GetModuleFileNameA(self, g_loaderDir, MAX_PATH); + char* slash = strrchr(g_loaderDir, '\\'); + if (slash) *slash = 0; + + LoaderLog("INF", "RynthCoreInit (native loader %s) starting in %s.", LOADER_VERSION, g_loaderDir); + { + // Test clients (tools\TestClient, scripts\Test-Clr*.ps1) say so first, so monitors can skip them. + char tag[128]; + if (GetEnvironmentVariableA("RYNTHCORE_TEST_CLIENT", tag, sizeof tag) > 0) + LoaderLog("INF", "TestClient: %s", tag); + } + + _snprintf_s(g_enginePath, sizeof g_enginePath, _TRUNCATE, "%s\\" ENGINE_DLL_NAME, g_loaderDir); + int managed = IsManagedPe(g_enginePath); + if (managed < 0) { + LoaderLog("ERR", "FATAL: engine DLL not found or unreadable at %s", g_enginePath); + return 3; + } + g_engineIsManaged = managed; + long largest; + long freeMb = LoaderFreeAddressSpaceMb(&largest); + LoaderLog("INF", "Engine is %s; %ld MB of address space free (largest %ld MB).", + managed ? "a managed assembly: hosting CoreCLR" : "NativeAOT", freeMb, largest); + + if (!HooksInit(g_loaderDir)) { + LoaderLog("ERR", "FATAL: MinHook could not be loaded from %s", g_loaderDir); + return 6; + } + if (managed) { + int rc = ClrStart(g_loaderDir); + if (rc != 0) { + LoaderLog("ERR", "FATAL: CoreCLR did not start (rc=%d)", rc); + return 7; + } + } + + unsigned int rc = LoadAndInitEngine(); + if (rc != 0) return rc; + + char eventName[128]; + _snprintf_s(eventName, sizeof eventName, _TRUNCATE, "Local\\RynthCore.Engine.RequestReload.p%lu", GetCurrentProcessId()); + g_reloadEvent = CreateEventA(NULL, FALSE, FALSE, eventName); + if (!g_reloadEvent) { + LoaderLog("WRN", "CreateEvent failed (error %lu); reload disabled.", GetLastError()); + return 0; + } + HANDLE t = CreateThread(NULL, 0, ReloadWatcher, NULL, 0, NULL); + if (t) CloseHandle(t); + t = CreateThread(NULL, 0, FileWatcher, NULL, 0, NULL); + if (t) CloseHandle(t); + LoaderLog("INF", "Reload watcher armed on '%s'; file watcher on '%s' (poll 1 s).", eventName, g_enginePath); + return 0; +} + +BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved) +{ + (void)h; (void)reserved; + if (reason == DLL_PROCESS_ATTACH) { + InitializeCriticalSection(&g_logLock); + DisableThreadLibraryCalls(h); + } + return TRUE; +} diff --git a/native/Loader/Loader.def b/native/Loader/Loader.def new file mode 100644 index 0000000..ae7afd2 --- /dev/null +++ b/native/Loader/Loader.def @@ -0,0 +1,16 @@ +LIBRARY "RynthCore.Loader.dll" +EXPORTS + RynthCoreInit + MH_Initialize + MH_Uninitialize + MH_CreateHook + MH_RemoveHook + MH_EnableHook + MH_DisableHook + MH_StatusToString + RcHooks_Version + RcHooks_Count + RcSubclass_Install + RcSubclass_Release + RcApiStub + RcServices_Version diff --git a/native/Loader/Loader.h b/native/Loader/Loader.h new file mode 100644 index 0000000..f233b78 --- /dev/null +++ b/native/Loader/Loader.h @@ -0,0 +1,26 @@ +#pragma once +#define WIN32_LEAN_AND_MEAN +#include + +#define LOADER_VERSION "2.0" + +// Loader.c +void LoaderLog(const char* level, const char* fmt, ...); +long LoaderFreeAddressSpaceMb(long* largestMb); +const char* LoaderDirectory(void); +int LoaderGeneration(void); + +// Hooks.c: MinHook facade (see the header comment there) +int HooksInit(const char* loaderDir); +void HooksBeginGeneration(int generation); +void HooksPassThroughAll(void); +void HooksFlush(void); + +// Services.c: permanent window subclass + plugin API stubs +void ServicesReleaseAll(void); + +// Clr.c: CoreCLR host for a managed engine +int ClrStart(const char* loaderDir); +int ClrLoadEngine(int generation, const char* stagedPath); +void ClrUnloadEngine(void); +void* ClrEngineExport(const char* name); diff --git a/native/Loader/Services.c b/native/Loader/Services.c new file mode 100644 index 0000000..d740329 --- /dev/null +++ b/native/Loader/Services.c @@ -0,0 +1,176 @@ +// ============================================================================ +// Services.c - the other native entry points the engine hands out, made permanent +// (docs/UNLOADABLE_ENGINE_PLAN.md: "nothing native points into collectible code"). +// +// 1. Window subclass: RcSubclass_Install puts the loader's own WndProc on a window, +// once for the life of the process, and forwards to the current engine's handler. +// RcSubclass_Release (and every reload) makes it a pure pass-through to the window's +// previous proc. The engine never has to unhook, so a foreign subclasser stacked on +// top of us (Decal, DirectInput) can never be ripped out of the chain, and nothing +// in the chain ever points at an unloaded engine. +// +// 2. Plugin API stubs: RcApiStub(index, fn) returns a permanent stub for table slot +// `index` that jumps to `fn`. Plugins copy the table and can't give it back; after a +// reload the slots are empty until the next engine fills them, and a plugin thread +// that calls one in between waits (any calling convention: registers and stack are +// untouched) and then runs the new engine's function. +// ============================================================================ + +#include "Loader.h" + +// --- 1. window subclass -------------------------------------------------------- + +#define MAX_SUBCLASSED 16 + +typedef LRESULT (CALLBACK *wndproc_fn)(HWND, UINT, WPARAM, LPARAM); + +typedef struct Subclass { + HWND hwnd; + WNDPROC previous; // the proc we replaced (AC's, or whoever was there) + wndproc_fn volatile handler; // current engine's handler, or NULL = pass-through +} Subclass; + +static Subclass g_subclassed[MAX_SUBCLASSED]; +static volatile LONG g_subclassCount; +static CRITICAL_SECTION g_servicesLock; +static int g_servicesReady; + +static void EnsureServices(void) +{ + if (!g_servicesReady) { + InitializeCriticalSection(&g_servicesLock); + g_servicesReady = 1; + } +} + +static Subclass* FindSubclass(HWND hwnd) +{ + LONG n = g_subclassCount; + for (LONG i = 0; i < n; i++) + if (g_subclassed[i].hwnd == hwnd) return &g_subclassed[i]; + return NULL; +} + +static LRESULT CALLBACK LoaderWndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l) +{ + Subclass* s = FindSubclass(hwnd); + if (!s) return DefWindowProcA(hwnd, msg, w, l); + wndproc_fn h = s->handler; + if (h) return h(hwnd, msg, w, l); + return CallWindowProcA(s->previous, hwnd, msg, w, l); +} + +// Returns 1 and the window's previous proc (what the engine's handler must forward to). +int __stdcall RcSubclass_Install(HWND hwnd, void* handler, void** previousOut) +{ + EnsureServices(); + int ok = 1; + EnterCriticalSection(&g_servicesLock); + Subclass* s = FindSubclass(hwnd); + if (!s) { + if (g_subclassCount >= MAX_SUBCLASSED) ok = 0; + else { + s = &g_subclassed[g_subclassCount]; + s->hwnd = hwnd; + s->handler = NULL; + SetLastError(0); + s->previous = (WNDPROC)SetWindowLongA(hwnd, GWL_WNDPROC, (LONG)(LONG_PTR)LoaderWndProc); + if (!s->previous) { + LoaderLog("ERR", "Subclass: SetWindowLong on 0x%p failed (error %lu)", (void*)hwnd, GetLastError()); + ok = 0; + } else { + InterlockedIncrement(&g_subclassCount); + LoaderLog("INF", "Subclass: 0x%p subclassed for good (previous proc 0x%p).", (void*)hwnd, (void*)s->previous); + } + } + } + if (ok) { + s->handler = (wndproc_fn)handler; + if (previousOut) *previousOut = (void*)s->previous; + } + LeaveCriticalSection(&g_servicesLock); + return ok; +} + +int __stdcall RcSubclass_Release(HWND hwnd) +{ + Subclass* s = FindSubclass(hwnd); + if (!s) return 0; + s->handler = NULL; + return 1; +} + +// --- 2. plugin API stubs -------------------------------------------------------- + +#define MAX_API_STUBS 512 +#define API_STUB_SIZE 32 + +static void* volatile g_apiSlots[MAX_API_STUBS]; +static unsigned char* g_apiStubs; +static volatile LONG g_apiWaitLogged; + +// Called from a stub whose slot is empty (between engine generations). Blocks until the +// next engine fills the table. stdcall, one argument; the stub saves every register. +static void __stdcall ApiWait(int index) +{ + DWORD start = GetTickCount(); + int logged = 0; + while (g_apiSlots[index] == NULL) { + Sleep(10); + if (!logged && GetTickCount() - start > 10000) { + logged = 1; + LoaderLog("WRN", "ApiStub: a plugin thread has waited 10 s for API slot %d (no engine loaded?).", index); + } + } +} + +static void BuildApiStub(int i) +{ + unsigned char* p = g_apiStubs + i * API_STUB_SIZE; + unsigned char* start = p; + void* volatile* slot = &g_apiSlots[i]; + *p++ = 0xA1; *(void* volatile**)p = slot; p += 4; // mov eax, [slot] + *p++ = 0x85; *p++ = 0xC0; // test eax, eax + *p++ = 0x74; *p++ = 0x02; // jz +2 (wait) + *p++ = 0xFF; *p++ = 0xE0; // jmp eax + *p++ = 0x60; // pushad + *p++ = 0x68; *(int*)p = i; p += 4; // push i + *p++ = 0xE8; *(int*)p = (int)((unsigned char*)ApiWait - (p + 4)); p += 4; // call ApiWait + *p++ = 0x61; // popad + *p++ = 0xE9; *(int*)p = (int)(start - (p + 4)); p += 4; // jmp start + while (p < start + API_STUB_SIZE) *p++ = 0xCC; +} + +void* __stdcall RcApiStub(int index, void* fn) +{ + EnsureServices(); + if (index < 0 || index >= MAX_API_STUBS) return fn; + EnterCriticalSection(&g_servicesLock); + if (!g_apiStubs) { + g_apiStubs = (unsigned char*)VirtualAlloc(NULL, MAX_API_STUBS * API_STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (g_apiStubs) { + for (int i = 0; i < MAX_API_STUBS; i++) BuildApiStub(i); + FlushInstructionCache(GetCurrentProcess(), g_apiStubs, MAX_API_STUBS * API_STUB_SIZE); + } + } + LeaveCriticalSection(&g_servicesLock); + if (!g_apiStubs) return fn; + // Already one of ours (a table wrapped twice): never point a slot at a stub. + if ((unsigned char*)fn >= g_apiStubs && (unsigned char*)fn < g_apiStubs + MAX_API_STUBS * API_STUB_SIZE) + return fn; + InterlockedExchangePointer((PVOID volatile*)&g_apiSlots[index], fn); + return g_apiStubs + index * API_STUB_SIZE; +} + +// Every reload: nothing we hand out may keep pointing into the old engine. +void ServicesReleaseAll(void) +{ + EnsureServices(); + EnterCriticalSection(&g_servicesLock); + for (LONG i = 0; i < g_subclassCount; i++) g_subclassed[i].handler = NULL; + for (int i = 0; i < MAX_API_STUBS; i++) g_apiSlots[i] = NULL; + LeaveCriticalSection(&g_servicesLock); + LoaderLog("INF", "Services: %ld window subclass(es) pass through, plugin API slots emptied until the next engine.", g_subclassCount); +} + +int __stdcall RcServices_Version(void) { return 1; } diff --git a/native/cimgui/.gitattributes b/native/cimgui/.gitattributes new file mode 100644 index 0000000..eaaa0b2 --- /dev/null +++ b/native/cimgui/.gitattributes @@ -0,0 +1,2 @@ +# Applied with git apply to an LF checkout: keep the bytes as committed. +*.patch -text diff --git a/native/cimgui/.gitignore b/native/cimgui/.gitignore new file mode 100644 index 0000000..fe0ee83 --- /dev/null +++ b/native/cimgui/.gitignore @@ -0,0 +1,3 @@ +_src/ +_build/ +_textedit/ diff --git a/native/cimgui/CMakeLists.txt b/native/cimgui/CMakeLists.txt new file mode 100644 index 0000000..ca30a0f --- /dev/null +++ b/native/cimgui/CMakeLists.txt @@ -0,0 +1,47 @@ +# RynthCore cimgui build: upstream cimgui 1.91.6dock (fetched into _src by +# scripts/Build-Cimgui.ps1) plus rynth_imconfig.h and rynth_cimgui_ext.cpp, +# and ImGuiColorTextEdit (fetched into _textedit, patched by +# textedit-rynth.patch) with its C exports in rynth_textedit_ext.cpp. +# Output: a 32-bit cimgui.dll whose structs match ImGui.NET 1.91.6.1. +cmake_minimum_required(VERSION 3.15) +cmake_policy(SET CMP0091 NEW) +project(rynth_cimgui CXX) + +set(CMAKE_CXX_STANDARD 17) +# Static CRT, like the stock ImGui.NET native build: no VC++ redistributable needed. +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + +set(SRC ${CMAKE_CURRENT_SOURCE_DIR}/_src) +set(TEXTEDIT ${CMAKE_CURRENT_SOURCE_DIR}/_textedit) + +add_library(cimgui SHARED + ${SRC}/cimgui.cpp + ${SRC}/imgui/imgui.cpp + ${SRC}/imgui/imgui_draw.cpp + ${SRC}/imgui/imgui_demo.cpp + ${SRC}/imgui/imgui_tables.cpp + ${SRC}/imgui/imgui_widgets.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rynth_cimgui_ext.cpp + ${TEXTEDIT}/TextEditor.cpp + ${TEXTEDIT}/LanguageDefinitions.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rynth_textedit_ext.cpp +) + +# Same defines as upstream cimgui's CMakeLists, except the user config. +target_compile_definitions(cimgui PRIVATE + IMGUI_USER_CONFIG=\"rynth_imconfig.h\" + IMGUI_DISABLE_OBSOLETE_FUNCTIONS=1 + "IMGUI_IMPL_API=extern \"C\" __declspec(dllexport)" +) +target_include_directories(cimgui PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + ${SRC} + ${SRC}/imgui + ${TEXTEDIT} + ${CMAKE_CURRENT_SOURCE_DIR}/textedit_shim +) +# ImGuiColorTextEdit uses std::string/printf-style code MSVC warns about. +set_source_files_properties(${TEXTEDIT}/TextEditor.cpp ${TEXTEDIT}/LanguageDefinitions.cpp + PROPERTIES COMPILE_OPTIONS "/wd4244;/wd4267;/wd4018;/wd4305") +set_target_properties(cimgui PROPERTIES PREFIX "") +target_link_libraries(cimgui imm32) diff --git a/native/cimgui/rynth_cimgui_ext.cpp b/native/cimgui/rynth_cimgui_ext.cpp new file mode 100644 index 0000000..3dc6e0e --- /dev/null +++ b/native/cimgui/rynth_cimgui_ext.cpp @@ -0,0 +1,118 @@ +// ============================================================================ +// RynthCore cimgui build - extra exports compiled into cimgui.dll. +// +// RynthImGui_BuildTag identifies this build (the engine refuses others). +// RynthImGui_GetLayout sizes/offsets/enum counts the engine compares +// against ImGui.NET's structs before creating a +// context (see ImGuiSelfTest.cs; same index order). +// RynthImGui_ReportAssert IM_ASSERT target (rynth_imconfig.h); records into +// a ring buffer the engine polls from AC's thread. +// ============================================================================ + +#include "imgui.h" +#include +#include +#include + +#define RYNTH_EXPORT extern "C" __declspec(dllexport) + +// ---- Build tag ------------------------------------------------------------- +// Bump the trailing number whenever the layout table or config changes. +RYNTH_EXPORT const char* RynthImGui_BuildTag(void) +{ + return "rynth-cimgui 1.91.6dock ImTextureID=void* soft-assert layout-1 textedit-264bee4"; +} + +// ---- Layout table ------------------------------------------------------------ +// Index order is a contract with ImGuiSelfTest.ExpectedLayout(); append only. +RYNTH_EXPORT int RynthImGui_GetLayout(int* out, int capacity) +{ + const int values[] = + { + 1, // 0 table version + (int)sizeof(ImTextureID), // 1 + (int)sizeof(ImWchar), // 2 + (int)sizeof(ImDrawIdx), // 3 + (int)sizeof(ImDrawVert), // 4 + (int)sizeof(ImDrawCmd), // 5 + (int)offsetof(ImDrawCmd, TextureId), // 6 + (int)offsetof(ImDrawCmd, VtxOffset), // 7 + (int)offsetof(ImDrawCmd, IdxOffset), // 8 + (int)offsetof(ImDrawCmd, ElemCount), // 9 + (int)offsetof(ImDrawCmd, UserCallback), // 10 + (int)sizeof(ImDrawList), // 11 + (int)offsetof(ImDrawList, VtxBuffer), // 12 + (int)sizeof(ImDrawData), // 13 + (int)offsetof(ImDrawData, CmdLists), // 14 + (int)offsetof(ImDrawData, DisplayPos), // 15 + (int)offsetof(ImDrawData, DisplaySize), // 16 + (int)sizeof(ImFontAtlas), // 17 + (int)offsetof(ImFontAtlas, TexID), // 18 + (int)sizeof(ImFont), // 19 + (int)sizeof(ImFontGlyph), // 20 + (int)sizeof(ImFontConfig), // 21 + (int)sizeof(ImGuiIO), // 22 + (int)offsetof(ImGuiIO, Fonts), // 23 + (int)offsetof(ImGuiIO, WantCaptureMouse), // 24 + (int)offsetof(ImGuiIO, WantTextInput), // 25 + (int)sizeof(ImGuiStyle), // 26 + (int)sizeof(ImGuiViewport), // 27 + (int)sizeof(ImGuiPlatformIO), // 28 + (int)sizeof(ImGuiInputTextCallbackData), // 29 + (int)sizeof(ImGuiListClipper), // 30 + (int)sizeof(ImGuiPayload), // 31 + (int)sizeof(ImGuiTableSortSpecs), // 32 + (int)sizeof(ImGuiTableColumnSortSpecs), // 33 + (int)sizeof(ImGuiStorage), // 34 + (int)sizeof(ImGuiWindowClass), // 35 + (int)sizeof(ImGuiSizeCallbackData), // 36 + (int)ImGuiCol_COUNT, // 37 + (int)ImGuiKey_NamedKey_END, // 38 + (int)ImGuiStyleVar_COUNT, // 39 + (int)ImGuiMouseCursor_COUNT, // 40 + }; + const int count = (int)(sizeof(values) / sizeof(values[0])); + if (out != NULL) + for (int i = 0; i < count && i < capacity; i++) + out[i] = values[i]; + return count; +} + +// ---- Soft asserts ------------------------------------------------------------ +// ImGui runs on one thread (AC's render thread); the engine polls on the same +// thread, so plain statics are enough. The ring keeps the last 16 failures. +static const int kAssertSlots = 16; +static const int kAssertTextLen = 256; +static int g_assertCount; +static char g_assertText[kAssertSlots][kAssertTextLen]; + +extern "C" void RynthImGui_ReportAssert(const char* expr, const char* file, int line) +{ + const char* base = file; + for (const char* p = file; *p; p++) + if (*p == '\\' || *p == '/') + base = p + 1; + char* slot = g_assertText[g_assertCount % kAssertSlots]; + _snprintf_s(slot, kAssertTextLen, _TRUNCATE, "%s:%d: %s", base, line, expr); + g_assertCount++; +} + +// Total failures since load (monotonic; wraps only after 2^31). +RYNTH_EXPORT int RynthImGui_GetAssertCount(void) +{ + return g_assertCount; +} + +// Copies failure number `index` (0-based, < count) into buf. Returns the +// length copied, or -1 when that entry was already overwritten or not yet made. +RYNTH_EXPORT int RynthImGui_GetAssertText(int index, char* buf, int capacity) +{ + if (buf == NULL || capacity <= 0 || index < 0 || index >= g_assertCount || index < g_assertCount - kAssertSlots) + return -1; + const char* src = g_assertText[index % kAssertSlots]; + int len = (int)strnlen(src, kAssertTextLen); + if (len >= capacity) len = capacity - 1; + memcpy(buf, src, (size_t)len); + buf[len] = '\0'; + return len; +} diff --git a/native/cimgui/rynth_imconfig.h b/native/cimgui/rynth_imconfig.h new file mode 100644 index 0000000..ea07092 --- /dev/null +++ b/native/cimgui/rynth_imconfig.h @@ -0,0 +1,26 @@ +// ============================================================================ +// RynthCore cimgui build - Dear ImGui user config (IMGUI_USER_CONFIG). +// Replaces upstream cimgui's cimconfig.h (which only did #undef NDEBUG). +// ============================================================================ +#pragma once + +// ImGui.NET 1.91.6.1 declares ImTextureID as IntPtr (pointer-sized). Dear ImGui +// 1.91.4+ defaults it to ImU64, which on x86 makes ImDrawCmd, ImDrawList and +// ImFontAtlas wider than ImGui.NET's structs and shifts every by-value texture +// argument (SetTexID, Image, AddImage, ...). This is why the stock NuGet x86 +// cimgui.dll does not match its own wrapper. A named typedef (not a bare +// "void*" macro) keeps functional casts like ImTextureID() valid. +typedef void* RynthImTextureID; +#define ImTextureID RynthImTextureID + +// Soft asserts. A failed IM_ASSERT is recorded in a small native ring buffer +// (rynth_cimgui_ext.cpp) that the engine polls and logs; control flow then +// continues exactly as in a release build with asserts compiled out. The +// handler never calls into managed code (a managed exception inside a native +// frame fail-fasts the process). +#ifdef __cplusplus +extern "C" +#endif +void RynthImGui_ReportAssert(const char* expr, const char* file, int line); + +#define IM_ASSERT(_EXPR) do { if (!(_EXPR)) RynthImGui_ReportAssert(#_EXPR, __FILE__, __LINE__); } while (0) diff --git a/native/cimgui/rynth_textedit_ext.cpp b/native/cimgui/rynth_textedit_ext.cpp new file mode 100644 index 0000000..20b85a1 --- /dev/null +++ b/native/cimgui/rynth_textedit_ext.cpp @@ -0,0 +1,308 @@ +// ============================================================================ +// RynthCore cimgui build - C exports for ImGuiColorTextEdit (santaclose fork, +// fetched into _textedit and patched by textedit-rynth.patch). +// +// The engine P/Invokes these by hand (ImGui/TextEditorNative.cs). Every call +// is made on AC's render thread inside an ImGui frame (Create reads the style, +// so it needs a current context too). Strings are UTF-8; returned pointers +// stay valid until the next call of the same export. +// +// Languages: 1 = Meta (.af source: coloured by the tokenizer below from the +// vocabulary the engine passes in), 2 = Lua (the fork's own definition). +// ============================================================================ + +#include +#include +#include +#include "TextEditor.h" + +#define RYNTH_EXPORT extern "C" __declspec(dllexport) + +struct RynthTextEditAccess +{ + typedef TextEditor::PaletteIndex PI; + + static std::unordered_set& StructWords() { static std::unordered_set s; return s; } + static std::unordered_set& ConditionWords() { static std::unordered_set s; return s; } + static std::unordered_set& ActionWords() { static std::unordered_set s; return s; } + + static bool IsWordStart(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; } + static bool IsDigit(char c) { return c >= '0' && c <= '9'; } + static bool IsWordChar(char c) { return IsWordStart(c) || IsDigit(c); } + + // Mirrors MetaSourceEditor.MetaColorizer: "~~" comments to the end of the + // line, braces, numbers (hex and signed too), STATE:/IF:/DO:/NAV: (the + // colon included), condition keywords, action keywords. + static bool TokenizeMeta(const char* in_begin, const char* in_end, const char*& out_begin, const char*& out_end, PI& color) + { + while (in_begin < in_end && (*in_begin == ' ' || *in_begin == '\t')) + in_begin++; + if (in_begin == in_end) + { + out_begin = out_end = in_end; + color = PI::Default; + return true; + } + + const char* p = in_begin; + out_begin = p; + char c = *p; + + if (c == '~' && p + 1 < in_end && p[1] == '~') + { + out_end = in_end; + color = PI::Comment; + return true; + } + if (c == '{' || c == '}') + { + out_end = p + 1; + color = PI::Punctuation; + return true; + } + if (IsDigit(c) || (c == '-' && p + 1 < in_end && IsDigit(p[1]))) + { + p++; + while (p < in_end && (IsWordChar(*p) || *p == '.')) + p++; + out_end = p; + color = PI::Number; + return true; + } + if (IsWordStart(c)) + { + p++; + while (p < in_end && IsWordChar(*p)) + p++; + std::string word(in_begin, p); + std::transform(word.begin(), word.end(), word.begin(), [](char ch) { return (char)::toupper((unsigned char)ch); }); + color = PI::Default; + if (p < in_end && *p == ':' && StructWords().count(word) != 0) + { + p++; + color = PI::Keyword; + } + else if (ConditionWords().count(word) != 0) + color = PI::KnownIdentifier; + else if (ActionWords().count(word) != 0) + color = PI::PreprocIdentifier; + out_end = p; + return true; + } + + // Anything else (punctuation, UTF-8 bytes): one byte, default colour. + out_end = p + 1; + color = PI::Default; + return true; + } + + static const TextEditor::LanguageDefinition& MetaLanguage() + { + static TextEditor::LanguageDefinition def; + static bool built = false; + if (!built) + { + built = true; + def.mName = "Meta"; + def.mTokenize = &TokenizeMeta; + def.mSingleLineComment = "~~"; // Ctrl+/ toggles "~~" + // An empty block-comment start matches everywhere in ColorizeInternal, + // so give it one that never occurs in text. + def.mCommentStart = "\x01\x02"; + def.mCommentEnd = "\x02\x01"; + def.mPreprocChar = '\x01'; + def.mCaseSensitive = false; + def.mTokenizerOwnsComments = true; // TokenizeMeta colours "~~" itself + } + return def; + } + + static void SetLanguage(TextEditor* ed, int language) + { + if (language == 1) + { + ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::None); + ed->mLanguageDefinition = &MetaLanguage(); + ed->Colorize(); + } + else if (language == 2) + ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::Lua); + else + ed->SetLanguageDefinition(TextEditor::LanguageDefinitionId::None); + } + + static void SetPalette(TextEditor* ed, const ImU32* colors, int count) + { + int n = std::min(count, (int)PI::Max); + for (int i = 0; i < n; i++) + ed->mPalette[i] = colors[i]; + } + + static void CursorScreenPos(TextEditor* ed, float* x, float* y) + { + TextEditor::Coordinates at = ed->GetSanitizedCursorCoordinates(); + *x = ed->mTextOrigin.x + ed->mTextStart + ed->TextDistanceToLineStart(at); + *y = ed->mTextOrigin.y + (at.mLine + 1) * ed->mCharAdvance.y; + } + + static std::string LinePrefix(TextEditor* ed) + { + TextEditor::Coordinates at = ed->GetSanitizedCursorCoordinates(); + return ed->GetText(TextEditor::Coordinates(at.mLine, 0), at); + } + + // Completion: replace the `bytes` characters before the cursor with `text`, + // as one undo step. + static void ReplaceBeforeCursor(TextEditor* ed, int bytes, const char* text) + { + if (ed->mReadOnly) + return; + ed->ClearExtraCursors(); + ed->ClearSelections(); + TextEditor::Coordinates end = ed->GetSanitizedCursorCoordinates(); + int endIndex = ed->GetCharacterIndexR(end); + int startIndex = std::max(0, endIndex - std::max(0, bytes)); + TextEditor::Coordinates start(end.mLine, ed->GetCharacterColumn(end.mLine, startIndex)); + + TextEditor::UndoRecord u; + u.mBefore = ed->mState; + if (start < end) + { + ed->SetSelection(start, end); + u.mOperations.push_back({ ed->GetSelectedText(), start, end, TextEditor::UndoOperationType::Delete }); + ed->DeleteSelection(); + } + TextEditor::Coordinates insertAt = ed->GetSanitizedCursorCoordinates(); + ed->InsertTextAtCursor(text); + u.mOperations.push_back({ std::string(text), insertAt, ed->GetSanitizedCursorCoordinates(), TextEditor::UndoOperationType::Add }); + u.mAfter = ed->mState; + ed->AddUndo(u); + } +}; + +static void FillWordSet(std::unordered_set& set, const char* words) +{ + set.clear(); + if (words == nullptr) + return; + std::string current; + for (const char* p = words;; p++) + { + if (*p == '\n' || *p == '\0') + { + if (!current.empty()) + set.insert(current); + current.clear(); + if (*p == '\0') + break; + } + else + current.push_back((char)::toupper((unsigned char)*p)); + } +} + +RYNTH_EXPORT TextEditor* RynthTE_Create(void) +{ + TextEditor* ed = new TextEditor(); + ed->SetShowWhitespacesEnabled(false); + return ed; +} + +RYNTH_EXPORT void RynthTE_Destroy(TextEditor* ed) +{ + delete ed; +} + +/// Newline-separated words, matched case-insensitively. Applies to every Meta editor. +RYNTH_EXPORT void RynthTE_SetMetaVocabulary(const char* structWords, const char* conditionWords, const char* actionWords) +{ + FillWordSet(RynthTextEditAccess::StructWords(), structWords); + FillWordSet(RynthTextEditAccess::ConditionWords(), conditionWords); + FillWordSet(RynthTextEditAccess::ActionWords(), actionWords); +} + +RYNTH_EXPORT void RynthTE_SetLanguage(TextEditor* ed, int language) +{ + RynthTextEditAccess::SetLanguage(ed, language); +} + +/// `count` ImU32 colours in TextEditor::PaletteIndex order. +RYNTH_EXPORT void RynthTE_SetPalette(TextEditor* ed, const ImU32* colors, int count) +{ + RynthTextEditAccess::SetPalette(ed, colors, count); +} + +RYNTH_EXPORT void RynthTE_SetOptions(TextEditor* ed, int readOnly, int showWhitespaces, int showLineNumbers, int tabSize) +{ + ed->SetReadOnlyEnabled(readOnly != 0); + ed->SetShowWhitespacesEnabled(showWhitespaces != 0); + ed->SetShowLineNumbersEnabled(showLineNumbers != 0); + ed->SetTabSize(tabSize); +} + +RYNTH_EXPORT void RynthTE_SetText(TextEditor* ed, const char* utf8) +{ + ed->SetText(utf8 != nullptr ? std::string(utf8) : std::string()); +} + +RYNTH_EXPORT const char* RynthTE_GetText(TextEditor* ed, int* length) +{ + static std::string text; + text = ed->GetText(); + if (length != nullptr) + *length = (int)text.size(); + return text.c_str(); +} + +RYNTH_EXPORT unsigned RynthTE_GetChangeCount(TextEditor* ed) +{ + return ed->GetChangeCount(); +} + +/// Draws the editor as a child window; returns whether it has keyboard focus. +RYNTH_EXPORT int RynthTE_Render(TextEditor* ed, const char* id, float width, float height, int border) +{ + return ed->Render(id, false, ImVec2(width, height), border != 0) ? 1 : 0; +} + +RYNTH_EXPORT void RynthTE_GetCursor(TextEditor* ed, int* line, int* column) +{ + ed->GetCursorPosition(*line, *column); +} + +RYNTH_EXPORT void RynthTE_SetCursor(TextEditor* ed, int line, int charIndex) +{ + ed->SetCursorPosition(line, charIndex); +} + +/// Screen position of the bottom-left corner of the cursor's cell (valid after Render). +RYNTH_EXPORT void RynthTE_GetCursorScreenPos(TextEditor* ed, float* x, float* y) +{ + RynthTextEditAccess::CursorScreenPos(ed, x, y); +} + +/// The cursor's line up to the cursor. +RYNTH_EXPORT const char* RynthTE_GetLinePrefix(TextEditor* ed, int* length) +{ + static std::string prefix; + prefix = RynthTextEditAccess::LinePrefix(ed); + if (length != nullptr) + *length = (int)prefix.size(); + return prefix.c_str(); +} + +RYNTH_EXPORT void RynthTE_ReplaceBeforeCursor(TextEditor* ed, int bytes, const char* utf8) +{ + RynthTextEditAccess::ReplaceBeforeCursor(ed, bytes, utf8 != nullptr ? utf8 : ""); +} + +/// While set, the editor ignores Up/Down/PageUp/PageDown/Enter/Tab/Escape (the host's completion list uses them). +RYNTH_EXPORT void RynthTE_SetCompletionKeysHeld(TextEditor* ed, int held) +{ + ed->SetCompletionKeysHeld(held != 0); +} + +RYNTH_EXPORT void RynthTE_RequestFocus(TextEditor* ed) +{ + ed->RequestFocus(); +} diff --git a/native/cimgui/textedit-rynth.patch b/native/cimgui/textedit-rynth.patch new file mode 100644 index 0000000..4c71d83 --- /dev/null +++ b/native/cimgui/textedit-rynth.patch @@ -0,0 +1,129 @@ +diff --git a/TextEditor.cpp b/TextEditor.cpp +index 013111f..9cd55a1 100644 +--- a/TextEditor.cpp ++++ b/TextEditor.cpp +@@ -325,13 +325,19 @@ void TextEditor::Paste() + void TextEditor::Undo(int aSteps) + { + while (CanUndo() && aSteps-- > 0) ++ { + mUndoBuffer[--mUndoIndex].Undo(this); ++ ++mChangeCount; ++ } + } + + void TextEditor::Redo(int aSteps) + { + while (CanRedo() && aSteps-- > 0) ++ { + mUndoBuffer[mUndoIndex++].Redo(this); ++ ++mChangeCount; ++ } + } + + void TextEditor::SetText(const std::string& aText) +@@ -355,6 +361,7 @@ void TextEditor::SetText(const std::string& aText) + + mUndoBuffer.clear(); + mUndoIndex = 0; ++ ++mChangeCount; + + Colorize(); + } +@@ -392,6 +399,7 @@ void TextEditor::SetTextLines(const std::vector& aLines) + + mUndoBuffer.clear(); + mUndoIndex = 0; ++ ++mChangeCount; + + Colorize(); + } +@@ -428,6 +436,11 @@ bool TextEditor::Render(const char* aTitle, bool aParentIsFocused, const ImVec2& + + ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavInputs); + ++ if (mFocusRequested) ++ { ++ ImGui::SetWindowFocus(); ++ mFocusRequested = false; ++ } + bool isFocused = ImGui::IsWindowFocused(); + HandleKeyboardInputs(aParentIsFocused); + HandleMouseInputs(); +@@ -1993,7 +2006,12 @@ void TextEditor::HandleKeyboardInputs(bool aParentIsFocused) + io.WantCaptureKeyboard = true; + io.WantTextInput = true; + +- if (!mReadOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) ++ if (mCompletionKeysHeld && (ImGui::IsKeyPressed(ImGuiKey_UpArrow) || ImGui::IsKeyPressed(ImGuiKey_DownArrow) || ++ ImGui::IsKeyPressed(ImGuiKey_PageUp) || ImGui::IsKeyPressed(ImGuiKey_PageDown) || ++ ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter) || ++ ImGui::IsKeyPressed(ImGuiKey_Tab) || ImGui::IsKeyPressed(ImGuiKey_Escape))) ++ ; // the host's completion list owns these keys ++ else if (!mReadOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) + Undo(); + else if (!mReadOnly && isAltOnly && ImGui::IsKeyPressed(ImGuiKey_Backspace)) + Undo(); +@@ -2238,6 +2256,7 @@ void TextEditor::Render(bool aParentIsFocused) + } + + ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos(); ++ mTextOrigin = cursorScreenPos; + mScrollX = ImGui::GetScrollX(); + mScrollY = ImGui::GetScrollY(); + UpdateViewVariables(mScrollX, mScrollY); +@@ -2549,6 +2568,7 @@ void TextEditor::AddUndo(UndoRecord& aValue) + mUndoBuffer.resize((size_t)(mUndoIndex + 1)); + mUndoBuffer.back() = aValue; + ++mUndoIndex; ++ ++mChangeCount; + } + + // TODO +@@ -2687,6 +2707,8 @@ void TextEditor::ColorizeInternal() + if (mLines.empty() || mLanguageDefinition == nullptr) + return; + ++ if (mCheckComments && mLanguageDefinition->mTokenizerOwnsComments) ++ mCheckComments = false; + if (mCheckComments) + { + auto endLine = mLines.size(); +diff --git a/TextEditor.h b/TextEditor.h +index 19ad61b..6883412 100644 +--- a/TextEditor.h ++++ b/TextEditor.h +@@ -97,6 +97,14 @@ public: + void ImGuiDebugPanel(const std::string& panelName = "Debug"); + void UnitTests(); + ++ // RynthCore (native/cimgui/textedit-rynth.patch): a text change counter, a ++ // hold-off on the keys the host's completion list uses, a focus request, ++ // and access for the C exports in rynth_textedit_ext.cpp. ++ inline unsigned GetChangeCount() const { return mChangeCount; } ++ inline void SetCompletionKeysHeld(bool aValue) { mCompletionKeysHeld = aValue; } ++ inline void RequestFocus() { mFocusRequested = true; } ++ friend struct RynthTextEditAccess; ++ + private: + // ------------- Generic utils ------------- // + +@@ -280,6 +288,7 @@ private: + TokenizeCallback mTokenize = nullptr; + std::vector mTokenRegexStrings; + bool mCaseSensitive = true; ++ bool mTokenizerOwnsComments = false; // RynthCore: skip the whole-text comment scan + + static const LanguageDefinition& Cpp(); + static const LanguageDefinition& Hlsl(); +@@ -452,6 +461,10 @@ private: + Palette mPalette; + LanguageDefinitionId mLanguageDefinitionId; + const LanguageDefinition* mLanguageDefinition = nullptr; ++ unsigned mChangeCount = 0; ++ bool mCompletionKeysHeld = false; ++ bool mFocusRequested = false; ++ ImVec2 mTextOrigin; + + inline bool IsHorizontalScrollbarVisible() const { return mCurrentSpaceWidth > mContentWidth; } + inline bool IsVerticalScrollbarVisible() const { return mCurrentSpaceHeight > mContentHeight; } diff --git a/native/cimgui/textedit_shim/boost/regex.hpp b/native/cimgui/textedit_shim/boost/regex.hpp new file mode 100644 index 0000000..1cde777 --- /dev/null +++ b/native/cimgui/textedit_shim/boost/regex.hpp @@ -0,0 +1,13 @@ +// RynthCore: ImGuiColorTextEdit (santaclose fork) includes . +// Its regex path only runs for languages without a hand-written tokenizer, and +// the two we use (Meta, Lua) both have one, so std::regex stands in for Boost. +#pragma once +#include + +namespace boost +{ + using std::regex; + using std::cmatch; + using std::regex_search; + namespace regex_constants = std::regex_constants; +} diff --git a/scripts/Build-Cimgui.ps1 b/scripts/Build-Cimgui.ps1 new file mode 100644 index 0000000..3154a99 --- /dev/null +++ b/scripts/Build-Cimgui.ps1 @@ -0,0 +1,93 @@ +<# +.SYNOPSIS + Builds the engine's 32-bit cimgui.dll from pinned upstream sources. + +.DESCRIPTION + Fetches cimgui at tag 1.91.6dock (and its Dear ImGui submodule) into + native\cimgui\_src, verifies both commits, fetches ImGuiColorTextEdit + (santaclose fork, the Meta/Lua source editor) into native\cimgui\_textedit + at a pinned commit and applies native\cimgui\textedit-rynth.patch, builds + with MSVC via CMake (Win32, Release, static CRT) using + native\cimgui\CMakeLists.txt, and copies + the result to src\RynthCore.Engine\Native\cimgui.dll. + + Why a custom build: ImGui.NET 1.91.6.1 treats ImTextureID as a pointer, + but Dear ImGui 1.91.6 defaults it to a 64-bit integer, so on x86 the stock + NuGet cimgui.dll does not match the wrapper (see native\cimgui\rynth_imconfig.h). + + Needs git and Visual Studio 2022 (Build Tools is enough) with the C++ + workload; CMake is taken from PATH or from the VS install. + +.PARAMETER Clean + Delete the CMake build directory first. +#> +[CmdletBinding()] +param( + [switch]$Clean +) + +$ErrorActionPreference = 'Stop' + +$Tag = '1.91.6dock' +$CimguiCommit = '970c614802935f51f451aa21ae06e838bdcf9349' +$ImguiCommit = '947aa9c9722bd6ff740dd757da609ff41f4d3ba3' +$TextEditCommit = '264bee49ddc3c789b05d928d09c628649458da47' + +$repoRoot = Split-Path -Parent $PSScriptRoot +$nativeDir = Join-Path $repoRoot 'native\cimgui' +$srcDir = Join-Path $nativeDir '_src' +$textEditDir = Join-Path $nativeDir '_textedit' +$textEditPatch = Join-Path $nativeDir 'textedit-rynth.patch' +$buildDir = Join-Path $nativeDir '_build' +$outDll = Join-Path $repoRoot 'src\RynthCore.Engine\Native\cimgui.dll' + +function Invoke-Checked([string]$What, [scriptblock]$Command) { + & $Command + if ($LASTEXITCODE -ne 0) { throw "$What failed (exit $LASTEXITCODE)" } +} + +# ---- Sources ---- +if (-not (Test-Path -LiteralPath $srcDir)) { + Write-Host "Fetching cimgui $Tag ..." + Invoke-Checked 'git clone' { git clone -q --depth 1 --branch $Tag --recurse-submodules --shallow-submodules https://github.com/cimgui/cimgui $srcDir } +} +$head = (git -C $srcDir rev-parse HEAD).Trim() +$imguiHead = (git -C (Join-Path $srcDir 'imgui') rev-parse HEAD).Trim() +if ($head -ne $CimguiCommit) { throw "native\cimgui\_src is at $head, expected $CimguiCommit ($Tag). Delete _src and rerun." } +if ($imguiHead -ne $ImguiCommit) { throw "native\cimgui\_src\imgui is at $imguiHead, expected $ImguiCommit. Delete _src and rerun." } + +# ImGuiColorTextEdit: no submodules (its Boost.Regex is replaced by +# textedit_shim\boost\regex.hpp). LF checkout so the committed patch applies. +if (-not (Test-Path -LiteralPath $textEditDir)) { + Write-Host "Fetching ImGuiColorTextEdit $TextEditCommit ..." + Invoke-Checked 'git clone (textedit)' { git -c core.autocrlf=false clone -q --no-checkout https://github.com/santaclose/ImGuiColorTextEdit $textEditDir } + Invoke-Checked 'git checkout (textedit)' { git -C $textEditDir -c core.autocrlf=false checkout -q $TextEditCommit } +} +$teHead = (git -C $textEditDir rev-parse HEAD).Trim() +if ($teHead -ne $TextEditCommit) { throw "native\cimgui\_textedit is at $teHead, expected $TextEditCommit. Delete _textedit and rerun." } +git -C $textEditDir apply --reverse --check $textEditPatch 2>$null +if ($LASTEXITCODE -ne 0) { + Invoke-Checked 'git apply (textedit patch)' { git -C $textEditDir apply $textEditPatch } +} + +# ---- CMake ---- +$cmake = (Get-Command cmake -ErrorAction SilentlyContinue).Source +if (-not $cmake) { + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' + $vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath + if (-not $vs) { throw 'Visual Studio with the C++ x86/x64 tools was not found.' } + $cmake = Join-Path $vs 'Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe' + if (-not (Test-Path -LiteralPath $cmake)) { throw "CMake not found on PATH or at $cmake" } +} + +if ($Clean -and (Test-Path -LiteralPath $buildDir)) { Remove-Item -LiteralPath $buildDir -Recurse -Force } + +Invoke-Checked 'cmake configure' { & $cmake -S $nativeDir -B $buildDir -G 'Visual Studio 17 2022' -A Win32 } +Invoke-Checked 'cmake build' { & $cmake --build $buildDir --config Release } + +$built = Join-Path $buildDir 'Release\cimgui.dll' +if (-not (Test-Path -LiteralPath $built)) { throw "Build produced no $built" } + +Copy-Item -LiteralPath $built -Destination $outDll -Force +$size = (Get-Item -LiteralPath $outDll).Length +Write-Host "cimgui.dll ($size bytes) -> $outDll" diff --git a/scripts/Deploy-RynthCore.ps1 b/scripts/Deploy-RynthCore.ps1 index 74caba6..fa4f8f5 100644 --- a/scripts/Deploy-RynthCore.ps1 +++ b/scripts/Deploy-RynthCore.ps1 @@ -15,7 +15,13 @@ param( # -AcClient overrides the binary it checks (default: auto-detect the private # copy under $Destination\AcClient, else C:\Turbine\Asheron's Call). [switch]$SkipPatternCheck, - [string]$AcClient = "" + [string]$AcClient = "", + # The old deploy: NativeAOT loader, engine and plugins (a hot reload leaks every + # generation). The default since 2026-09-29 is the unloadable engine + # (docs/UNLOADABLE_ENGINE_PLAN.md): native loader + CoreCLR engine + app-local runtime + # in Runtime\ (scripts\Publish-EngineCoreClr.ps1), and managed plugins, all of which + # a hot reload frees. Releases (installer\) still ship NativeAOT: players run that engine. + [switch]$NativeAot ) $ErrorActionPreference = "Stop" @@ -38,7 +44,6 @@ $loaderProject = Join-Path $repoRoot "src\RynthCore.Loader\RynthCore.Loader.cspr $rynthAiSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi" $rynthChatSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthChat" $rynthVisionSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthVision" -$rynthJuiceSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthJuice" $pluginProjects = @( @{ Project = Join-Path $rynthAiSourceRoot "RynthCore.Plugin.RynthAi.csproj" @@ -67,15 +72,6 @@ $pluginProjects = @( DllName = "RynthCore.Plugin.RynthTracker.dll" DestSubdir = "RynthTracker" }, - # RynthJuice sets to its deploy home (like RynthVision), so - # publish lands directly in $PluginsDestination\RynthJuice and the copy step - # below detects source == dest and skips the redundant self-copy. - @{ - Project = Join-Path $rynthJuiceSourceRoot "RynthCore.Plugin.RynthJuice.csproj" - Publish = Join-Path $PluginsDestination "RynthJuice" - DllName = "RynthCore.Plugin.RynthJuice.dll" - DestSubdir = "RynthJuice" - }, # RynthNav also publishes straight to its deploy home via . # It was missing from this list entirely, so full deploys never refreshed it. @{ @@ -83,6 +79,13 @@ $pluginProjects = @( Publish = Join-Path $PluginsDestination "RynthNav" DllName = "RynthCore.Plugin.RynthNav.dll" DestSubdir = "RynthNav" + }, + # RynthLua: Lua scripting, split out of RynthAi on 2026-09-29. + @{ + Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthLua\RynthCore.Plugin.RynthLua.csproj" + Publish = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthLua\bin\Release\net10.0-windows\win-x86\publish" + DllName = "RynthCore.Plugin.RynthLua.dll" + DestSubdir = "RynthLua" } ) @@ -158,6 +161,13 @@ function Invoke-Publish { } } +# Managed plugins publish to (and deploy from) out\plugins-clr\, -SkipPublish too. +if (-not $NativeAot) { + foreach ($plugin in $pluginProjects) { + $plugin.Publish = Join-Path $repoRoot ("out\plugins-clr\" + $plugin.DestSubdir) + } +} + if (-not $SkipPublish) { $env:DOTNET_CLI_HOME = Join-Path $repoRoot ".dotnet-home-deploy-clean" $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1" @@ -166,10 +176,24 @@ if (-not $SkipPublish) { # --self-contained false is required: omitting it with the launcher's IncludeNativeLibrariesForSelfExtract=true produces a broken half-payload (apphost + coreclr.dll, no framework) that reports ".NET is not installed". Invoke-Publish -What "launcher" -Arguments @('publish', $launcherProject, '-c', 'Release', '-r', 'win-x86', '--self-contained', 'false') } - Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release') - Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release') + if ($NativeAot) { + Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release') + Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release') + } + # (CoreCLR: the engine, loader and shim are built by Publish-EngineCoreClr.ps1 below, + # after Runtime\ is wiped.) foreach ($plugin in $pluginProjects) { - Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release') + if ($NativeAot) { + Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release') + } else { + # Same source, managed: loads into its own collectible context in the CoreCLR + # engine (Plugins/ManagedPlugins.cs). Staged under out\plugins-clr, then copied. + $stage = $plugin.Publish + if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } + Invoke-Publish -What "$($plugin.DllName) (managed)" -Arguments @('publish', $plugin.Project, '-c', 'Release', + '-p:PublishAot=false', '-p:NativeLib=', '-p:SelfContained=false', '-p:RuntimeIdentifier=win-x86', + '-p:GenerateRuntimeConfigurationFiles=false', '-o', $stage) + } } } @@ -256,13 +280,20 @@ if (-not $SkipLauncher) { Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb") } -# Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins -# are deployed separately to $PluginsDestination so they have a single home. -Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb") +if ($NativeAot) { + # Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins + # are deployed separately to $PluginsDestination so they have a single home. + Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb") -# Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the -# Loader then maps RynthCore.Engine.dll and provides hot-reload support. -Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force + # Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the + # Loader then maps RynthCore.Engine.dll and provides hot-reload support. + Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force +} else { + # Native loader (native\Loader) + RynthCore.Shim + CoreCLR engine (ReadyToRun) + its + # dependencies + Runtime\dotnet (app-local CoreCLR x86). Same contract with the + # injector (RynthCoreInit); the loader also hosts a NativeAOT engine if one is dropped in. + & (Join-Path $PSScriptRoot "Publish-EngineCoreClr.ps1") -Target $runtimeDir +} # SEH trampoline - small native x86 MSVC DLL providing __try/__except wrappers # around dangerous AC API calls so object-teardown AVs are caught instead of @@ -302,6 +333,16 @@ foreach ($plugin in $pluginProjects) { New-Item -ItemType Directory -Path $pluginTargetDir -Force | Out-Null } + if (-not $NativeAot) { + # A managed plugin is its DLL plus its dependencies (RynthCore.PluginSdk, + # PluginCore, MoonSharp, ImGui.NET...) and pdbs; copy those, leave user data. + foreach ($f in Get-ChildItem -LiteralPath $plugin.Publish -File | Where-Object { $_.Extension -in '.dll', '.pdb' }) { + Copy-Item -LiteralPath $f.FullName -Destination (Join-Path $pluginTargetDir $f.Name) -Force + } + Write-Host "Plugin $($plugin.DllName) (managed) deployed to $pluginTargetDir" + continue + } + # Only the DLL - leave any user data (LootProfiles\, imgui.ini, etc.) # in place by not touching anything else under $pluginTargetDir. $pluginDest = Join-Path $pluginTargetDir $plugin.DllName @@ -318,7 +359,10 @@ foreach ($plugin in $pluginProjects) { # Scoped pdb sweep: root + Runtime\ only. A $Destination-wide recurse walked # the ~1.4 GB private AcClient copy on every deploy for nothing. Get-ChildItem -Path $Destination -Filter *.pdb -File | Remove-Item -Force -Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File | Remove-Item -Force +# (The CoreCLR engine's own pdbs stay: they give its stack traces line numbers.) +Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File | + Where-Object { $NativeAot -or $_.Name -notin 'RynthCore.Engine.pdb', 'RynthCore.Shim.pdb', 'RynthCore.Loader.pdb' } | + Remove-Item -Force if (-not $SkipLauncher) { Write-Host "Launcher deployed to $Destination" diff --git a/scripts/Publish-EngineCoreClr.ps1 b/scripts/Publish-EngineCoreClr.ps1 new file mode 100644 index 0000000..cad170e --- /dev/null +++ b/scripts/Publish-EngineCoreClr.ps1 @@ -0,0 +1,122 @@ +# Publish-EngineCoreClr.ps1 +# Builds the CoreCLR-hosted engine (docs/UNLOADABLE_ENGINE_PLAN.md) and lays it out in a +# Runtime folder: +# RynthCore.Loader.dll native loader (native\Loader), hosts CoreCLR +# RynthCore.Shim.dll default-ALC shim (src\RynthCore.Shim) +# RynthCore.Engine.dll (+pdb) the engine as a managed assembly (-p:EngineHost=coreclr) +# Avalonia*, ImGui.NET, ... the engine's managed dependencies (load into its collectible ALC) +# cimgui, minhook, Skia, ... native libraries (process-wide, loaded once) +# dotnet\ app-local CoreCLR x86 (from the NuGet runtime pack) +# +# Default target is the live install; a running client hot-reloads onto a new engine by itself: +# .\scripts\Publish-EngineCoreClr.ps1 -> C:\Games\RynthCore\Runtime +# .\scripts\Publish-EngineCoreClr.ps1 -Target -EngineOnly (engine + deps only: a hot reload) + +param( + [string]$Target = "C:\Games\RynthCore\Runtime", + [string]$Configuration = "Release", + [switch]$EngineOnly, + # The engine is precompiled (ReadyToRun) unless -NoReadyToRun: each generation then + # loads in ~130 ms instead of ~750 (less JIT); the DLL is ~5 MB instead of ~2. + [switch]$NoReadyToRun, + # Extra MSBuild arguments for the engine and shim builds (the installer passes -p:Version=...). + [string[]]$MsBuildArgs = @(), + # Deploy to the live Runtime even though status-export has commits this checkout lacks. + [switch]$AllowBehind +) + +$ErrorActionPreference = "Stop" +$repo = Split-Path $PSScriptRoot -Parent + +# Deploying to the live install from a checkout that lacks status-export's commits rolls +# back other sessions' engine fixes on every running client (2026-09-29, API v70). Refuse. +$liveRuntime = "C:\Games\RynthCore\Runtime" +if ([IO.Path]::GetFullPath($Target).TrimEnd('\') -ieq $liveRuntime -and -not $AllowBehind) { + git -C $repo merge-base --is-ancestor status-export HEAD 2>$null + if ($LASTEXITCODE -ne 0) { + $missing = git -C $repo log --oneline HEAD..status-export + throw "This checkout is missing status-export commits; deploying it to the live Runtime would roll them back:`n$($missing -join "`n")`nMerge status-export first (or pass -AllowBehind if you really mean it)." + } +} +$env:PATH += ";C:\Program Files (x86)\Microsoft Visual Studio\Installer" +New-Item -ItemType Directory -Force -Path $Target | Out-Null + +$stage = Join-Path $repo "out\engine-clr" +if (Test-Path $stage) { Remove-Item $stage -Recurse -Force } +Write-Host "Building the engine (EngineHost=coreclr)..." +$r2r = if (-not $NoReadyToRun) { "-p:PublishReadyToRun=true" } else { "-p:PublishReadyToRun=false" } +dotnet publish "$repo\src\RynthCore.Engine\RynthCore.Engine.csproj" -c $Configuration -p:EngineHost=coreclr $r2r -o $stage -nologo -v q @MsBuildArgs +if ($LASTEXITCODE -ne 0) { throw "engine build failed" } + +if (-not $EngineOnly) { + Write-Host "Building the native loader..." + & "$repo\native\Loader\Build-Loader.ps1" + Write-Host "Building the shim..." + dotnet build "$repo\src\RynthCore.Shim\RynthCore.Shim.csproj" -c $Configuration -nologo -v q @MsBuildArgs + if ($LASTEXITCODE -ne 0) { throw "shim build failed" } + + # The loader and the shim load once per client: a running client keeps its copy (and + # locks the file) until it restarts. Skip them with a warning rather than fail. + $hostFiles = @( + "$repo\native\Loader\bin\RynthCore.Loader.dll", "$repo\native\Loader\bin\RynthCore.Loader.pdb", + "$repo\src\RynthCore.Shim\bin\$Configuration\net10.0-windows\RynthCore.Shim.dll", + "$repo\src\RynthCore.Shim\bin\$Configuration\net10.0-windows\RynthCore.Shim.pdb") + # A running client holds these files; Windows lets a loaded DLL be renamed, so the old + # copy is moved aside (the client keeps using it) and the new one goes in for the next + # launch. Earlier moved-aside copies are deleted once no client holds them. + Get-ChildItem $Target -Filter "RynthCore.*.old-*" -ErrorAction SilentlyContinue | + ForEach-Object { Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue } + foreach ($f in $hostFiles) { + $dest = Join-Path $Target (Split-Path $f -Leaf) + try { Copy-Item $f $dest -Force -ErrorAction Stop } + catch { + try { + Rename-Item $dest ("{0}.old-{1:yyyyMMddHHmmss}" -f (Split-Path $dest -Leaf), (Get-Date)) -ErrorAction Stop + Copy-Item $f $dest -Force -ErrorAction Stop + Write-Host "$(Split-Path $f -Leaf) was in use: moved the old one aside; new launches get the new one." + } + catch { Write-Warning "$(Split-Path $f -Leaf) is in use by a running client; it keeps the old one until it restarts." } + } + } + + $seh = "$repo\native\SehTrampoline\bin\RynthCore.SehTrampoline.dll" + if (-not (Test-Path $seh)) { $seh = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll" } + $sehDest = Join-Path (Resolve-Path $Target).Path "RynthCore.SehTrampoline.dll" + $sameSeh = (Test-Path $sehDest) -and ((Resolve-Path $seh).Path -eq $sehDest -or + (Get-FileHash $seh).Hash -eq (Get-FileHash $sehDest).Hash) + if (-not $sameSeh) { + try { Copy-Item $seh $sehDest -Force -ErrorAction Stop } + catch { Write-Warning "RynthCore.SehTrampoline.dll changed but is in use by a running client; it gets the new one when it restarts." } + } + + # App-local runtime: the win-x86 runtime pack the SDK restores (same version the engine was built against). + $dotnet = Join-Path $Target "dotnet" + if (-not (Test-Path "$dotnet\coreclr.dll")) { + $pack = Join-Path $env:USERPROFILE ".nuget\packages\microsoft.netcore.app.runtime.win-x86" + $ver = (Get-ChildItem $pack | Where-Object Name -like "10.*" | Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1).Name + if (-not $ver) { throw "microsoft.netcore.app.runtime.win-x86 10.x not in the NuGet cache (restore any win-x86 self-contained project once)" } + $rt = "$pack\$ver\runtimes\win-x86" + New-Item -ItemType Directory -Force -Path $dotnet | Out-Null + Copy-Item "$rt\native\*" $dotnet -Force + Copy-Item "$rt\lib\net10.0\*.dll" $dotnet -Force + # Diagnostics-only natives the host never loads. + Remove-Item "$dotnet\createdump.exe", "$dotnet\mscordaccore_*.dll", "$dotnet\msquic.dll" -Force -ErrorAction SilentlyContinue + Write-Host "App-local runtime $ver -> $dotnet" + } +} + +# Engine + dependencies. The canonical RynthCore.Engine.dll goes last: the loader's file +# watcher reloads on its timestamp, so everything it needs must already be in place. +# Only what changed. Native libraries (cimgui, Skia...) are loaded once per client and +# locked while it runs; they rarely change, so a locked unchanged one is simply skipped. +foreach ($f in Get-ChildItem $stage -File | Where-Object { $_.Name -notlike "RynthCore.Engine.*" -and $_.Name -ne "minhook.x86.dll" }) { + $dest = Join-Path $Target $f.Name + if ((Test-Path $dest) -and (Get-Item $dest).Length -eq $f.Length -and + (Get-FileHash $dest).Hash -eq (Get-FileHash $f.FullName).Hash) { continue } + try { Copy-Item $f.FullName $dest -Force -ErrorAction Stop } + catch { Write-Warning "$($f.Name) changed but is in use by a running client; it gets the new one when it restarts." } +} +if (-not (Test-Path "$Target\minhook.x86.dll")) { Copy-Item "$stage\minhook.x86.dll" $Target -Force } +Copy-Item "$stage\RynthCore.Engine.pdb" $Target -Force +Copy-Item "$stage\RynthCore.Engine.dll" $Target -Force +Write-Host "Published the CoreCLR engine to $Target" diff --git a/scripts/Publish-PluginsCoreClr.ps1 b/scripts/Publish-PluginsCoreClr.ps1 new file mode 100644 index 0000000..bc4454f --- /dev/null +++ b/scripts/Publish-PluginsCoreClr.ps1 @@ -0,0 +1,28 @@ +# Publish-PluginsCoreClr.ps1 +# Builds RynthSuite plugins as MANAGED assemblies for the CoreCLR engine (plan Phase 4): the +# same source as the NativeAOT build, with PublishAot off (command-line properties override +# the csproj). Each plugin lands in its own folder with its dependencies (RynthCore.PluginSdk, +# PluginCore, MoonSharp, ...), which the engine loads into the plugin's collectible context. +# +# For a test build into a separate folder; scripts\Deploy-RynthCore.ps1 is what deploys the +# managed plugins to C:\Games\RynthSuite. The plugins reference ..\..\..\RynthCore\src\... (the +# SDK), so they build against whatever RynthCore checkout sits next to -RynthSuite. +# .\scripts\Publish-PluginsCoreClr.ps1 [-Plugins RynthAi,RynthChat] [-Out ] +param( + [string]$RynthSuite = "C:\Projects\RynthSuite", + [string]$Out = "C:\Games\RynthCore\Test\plugins-clr", + [string[]]$Plugins = @("RynthAi", "RynthChat", "RynthNav", "RynthTracker", "RynthLua", "RynthVision") +) + +$ErrorActionPreference = "Stop" +foreach ($name in $Plugins) { + $proj = Join-Path $RynthSuite "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" + if (-not (Test-Path $proj)) { Write-Warning "${name}: no project at $proj"; continue } + $dest = Join-Path $Out $name + if (Test-Path $dest) { Remove-Item $dest -Recurse -Force } + Write-Host "Building $name (managed)..." + dotnet publish $proj -c Release -p:PublishAot=false -p:NativeLib= -p:SelfContained=false ` + -p:RuntimeIdentifier=win-x86 -p:GenerateRuntimeConfigurationFiles=false -o $dest -nologo -v q + if ($LASTEXITCODE -ne 0) { throw "$name build failed" } + Write-Host " -> $dest\RynthCore.Plugin.$name.dll" +} diff --git a/scripts/Test-ClrReload.ps1 b/scripts/Test-ClrReload.ps1 new file mode 100644 index 0000000..757fd8f --- /dev/null +++ b/scripts/Test-ClrReload.ps1 @@ -0,0 +1,62 @@ +# Test-ClrReload.ps1 - hot-reload test for the CoreCLR-hosted engine in a throwaway client. +# +# Starts acclient from the private copy against -Server (default: a closed local port, so +# nothing logs in), with its own engine.json (-Settings), reloads it -Reloads times, +# and after each reload prints the loader/shim lines. If a generation did not unload, +# runs tools\AlcRoots against the client to show what still holds it. Kills the client at +# the end unless -Keep. +param( + [string]$Runtime = "C:\Games\RynthCore\Runtime", + [string]$Settings = "C:\Games\RynthCore\Test\engine-noplugins.json", + [int]$Reloads = 1, + [int]$WarmupSeconds = 20, + [int]$SettleSeconds = 15, + [string[]]$ClientArgs = @("-h", "127.0.0.1", "-p", "9", "-a", "spike", "-v", "spike"), + [switch]$Keep, + [switch]$AlwaysRoots +) + +$ErrorActionPreference = "Stop" +$repo = Split-Path $PSScriptRoot -Parent +$testClient = "$repo\tools\TestClient\bin\TestClient.exe" +$alcRoots = "$repo\tools\AlcRoots\bin\Release\net10.0\win-x86\AlcRoots.exe" + +$env:RYNTHCORE_ENGINE_SETTINGS = $Settings +$env:RYNTHCORE_TEST_CLIENT = "Test-ClrReload" # the loader logs "TestClient: ..." (monitors skip test clients) +# Panel layout (panel_state.txt) lives in %LOCALAPPDATA%\RynthCore and is shared with real +# clients: a test client gets its own so it never moves the player's bar or panels. +$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata" +New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null +$out = & $testClient "C:\Games\RynthCore\AcClient\acclient.exe" "$Runtime\RynthCore.Loader.dll" RynthCoreInit 0 @ClientArgs +$clientPid = [int](($out | Select-String "TEST_PID=(\d+)").Matches[0].Groups[1].Value) +$log = "C:\Games\RynthCore\Logs\RynthCore.$clientPid.log" +Write-Host "client pid $clientPid, log $log" +Start-Sleep $WarmupSeconds + +$seen = 0 +function Show-NewLoaderLines { + $lines = @(Get-Content $log | Select-String "\[loader\]|\[ERR\]|\[WRN\]") + $lines[$script:seen..($lines.Count - 1)] | ForEach-Object { $_.Line } + $script:seen = $lines.Count +} +Show-NewLoaderLines + +for ($i = 1; $i -le $Reloads; $i++) { + if (-not (Get-Process -Id $clientPid -ErrorAction SilentlyContinue)) { Write-Host "client died"; break } + Write-Host "---- reload $i" + $ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$clientPid") + [void]$ev.Set() + $ev.Dispose() + Start-Sleep $SettleSeconds + Show-NewLoaderLines + $notFreed = Select-String -Path $log -Pattern "NOT unloaded" -Quiet + if ($AlwaysRoots -or ($notFreed -and $i -eq 1)) { + Write-Host "---- AlcRoots" + & $alcRoots $clientPid 30 + } +} + +if (-not $Keep) { + Stop-Process -Id $clientPid -Force -ErrorAction SilentlyContinue + Write-Host "client $clientPid stopped" +} diff --git a/scripts/Test-ClrWorld.ps1 b/scripts/Test-ClrWorld.ps1 new file mode 100644 index 0000000..d03e8db --- /dev/null +++ b/scripts/Test-ClrWorld.ps1 @@ -0,0 +1,97 @@ +# Test-ClrWorld.ps1 - logs a test character into a LOCAL server with the CoreCLR engine and +# hot-reloads it N times, reporting per generation: unloaded or not, pattern misses, hangs, +# and the frame rate afterwards. Runs tools\AlcRoots when a generation doesn't unload. +# +# Uses the injector's headless --launch with a saved account profile (the password stays in +# the launcher's settings). Only point it at a server you run yourself. +# .\scripts\Test-ClrWorld.ps1 -Account Buffi -Server ACEmulator -Character "+Buffi" -Reloads 5 +param( + [string]$Account = "Buffi", + [string]$Server = "ACEmulator", + [string]$Character = "+Buffi", + [string]$Runtime = "C:\Games\RynthCore\Runtime", + [string]$Settings = "C:\Games\RynthCore\Test\engine-plugins.json", + [int]$Reloads = 3, + [int]$WarmupSeconds = 45, + [int]$SettleSeconds = 25, + # Chat commands to run after login and again after every reload (through the test + # client's own dispatch file), e.g. "/rc ui popout Radar". + [string[]]$Commands = @(), + [switch]$Keep +) + +$ErrorActionPreference = "Stop" +$repo = Split-Path $PSScriptRoot -Parent +$injector = "$repo\out\injector\RynthCore.Injector.exe" +if (-not (Test-Path $injector)) { + dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector" -nologo -v q | Out-Null + if (-not (Test-Path $injector)) { throw "could not build the injector" } +} +$alcRoots = "$repo\tools\AlcRoots\bin\Release\net10.0\win-x86\AlcRoots.exe" +$pidFile = "C:\Games\RynthCore\Test\current-pid.txt" + +# A client killed without logging off keeps its session on the server for about a minute. +if (Test-Path $pidFile) { + $old = [int](Get-Content $pidFile) + if (Get-Process -Id $old -ErrorAction SilentlyContinue) { + Stop-Process -Id $old -Force + Write-Host "stopped previous test client $old; waiting 65 s for the server to drop its session" + Start-Sleep 65 + } +} + +$env:RYNTHCORE_ENGINE_SETTINGS = $Settings +$env:RYNTHCORE_TEST_CLIENT = "Test-ClrWorld" # the loader logs "TestClient: ..." (monitors skip test clients) +# Panel layout (panel_state.txt) lives in %LOCALAPPDATA%\RynthCore and is shared with real +# clients: a test client gets its own so it never moves the player's bar or panels. +$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata" +New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null +$dispatch = "C:\Games\RynthCore\Test\dispatch.txt" +$env:RYNTHCORE_DISPATCH_FILE = $dispatch +Set-Content $dispatch "# test dispatch file" +function Send-Commands { + foreach ($c in $Commands) { + Set-Content $dispatch "force:$c" + Start-Sleep 2 + } +} +$out = & $injector --launch --account $Account --server $Server --engine "$Runtime\RynthCore.Loader.dll" --character $Character 2>&1 +$clientPid = [int](($out | Select-String "LAUNCHED_PID=(\d+)").Matches[0].Groups[1].Value) +Set-Content $pidFile $clientPid +$log = "C:\Games\RynthCore\Logs\RynthCore.$clientPid.log" +Write-Host "client $clientPid, log $log" +Start-Sleep $WarmupSeconds + +function Summarize([int]$from) { + $lines = @(Get-Content $log | Select-Object -Skip $from) + $lines | Select-String "unloaded in|NOT unloaded|unloaded since|Reload: |PATTERN MISS|HANG DETECTED|prologue not found|\[ERR\]|still running|ChatFileDispatcher: dispatching|PopOut|pop-out" | + ForEach-Object { Write-Host (" " + ($_.Line -replace '^\[(\S+)\] \[pid:\d+\] ', '$1 ')) } + $fps = $lines | Select-String "hb #\d+ .*fps=(\d+).*login=(\d)" | Select-Object -Last 8 | + ForEach-Object { $_.Matches[0].Groups[1].Value } + Write-Host " fps (last 8 heartbeats): $($fps -join ' ')" + return (Get-Content $log).Count +} + +Send-Commands +Start-Sleep 5 +$mark = 0 +Write-Host "---- gen 1" +$mark = Summarize $mark +for ($i = 1; $i -le $Reloads; $i++) { + if (-not (Get-Process -Id $clientPid -ErrorAction SilentlyContinue)) { Write-Host "CLIENT DIED"; break } + Write-Host "---- reload $i" + $ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$clientPid") + [void]$ev.Set(); $ev.Dispose() + Start-Sleep $SettleSeconds + Send-Commands + Start-Sleep 5 + $before = $mark + $mark = Summarize $mark + if (Get-Content $log | Select-Object -Skip $before | Select-String "NOT unloaded" -Quiet) { + Write-Host "---- AlcRoots" + & $alcRoots $clientPid 15 + } +} +$p = Get-Process -Id $clientPid -ErrorAction SilentlyContinue +Write-Host ("client " + $(if ($p) { "alive, responding=$($p.Responding)" } else { "DEAD" })) +if (-not $Keep -and $p) { Stop-Process -Id $clientPid -Force; Write-Host "client stopped" } diff --git a/scripts/Watch-AcFreeze.ps1 b/scripts/Watch-AcFreeze.ps1 index 6289ce9..7829719 100644 --- a/scripts/Watch-AcFreeze.ps1 +++ b/scripts/Watch-AcFreeze.ps1 @@ -7,7 +7,8 @@ # (MaybeRestartWedgedClients), so it can run with the launcher closed: # # * fps=0 with login=1 sustained >= WedgeHoldSeconds (render dead, alive) -# * main-thread queue qd > QueueWedgeDepth with login=1 (queue not draining) +# * (inert since 2026-10-01: the engine reports qdrop, a running total of dropped +# actions, not a queue depth; healthy clients were being killed on it) # * combat-mode "stuck Ns" >= StanceStuckSeconds (item-action hard-lock) # * heartbeat file silent > HbStaleSeconds while alive (engine died in-proc) # diff --git a/spikes/CoreClrHost/Build.ps1 b/spikes/CoreClrHost/Build.ps1 new file mode 100644 index 0000000..ca8d6ff --- /dev/null +++ b/spikes/CoreClrHost/Build.ps1 @@ -0,0 +1,52 @@ +# Build.ps1 - builds the Phase 0 CoreCLR hosting spike into .\bin +# bin\SpikeHostExe.exe, SpikeHost.dll native x86 (cl.exe) +# bin\Shim.dll, Contracts.dll default ALC (in the TPA list) +# bin\payload\Payload.dll loaded into a collectible ALC per generation +# bin\runtime\ app-local CoreCLR x86 from the NuGet runtime pack +# Run: .\bin\SpikeHostExe.exe (mode bits: see Payload.cs) + +$ErrorActionPreference = "Stop" +$root = $PSScriptRoot +$bin = Join-Path $root "bin" +New-Item -ItemType Directory -Force -Path $bin, "$bin\payload", "$bin\runtime", "$bin\obj" | Out-Null + +# --- native --- +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" ` + -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$cl = "$vcBase\bin\Hostx86\x86\cl.exe" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" + +Push-Location "$bin\obj" +try { + & $cl /nologo /O2 /MT /W3 /LD "$root\native\SpikeHost.c" /link /MACHINE:X86 /OUT:"$bin\SpikeHost.dll" + if ($LASTEXITCODE -ne 0) { throw "SpikeHost.dll failed" } + & $cl /nologo /O2 /MT /W3 "$root\native\SpikeHostExe.c" /link /MACHINE:X86 /LARGEADDRESSAWARE /OUT:"$bin\SpikeHostExe.exe" + if ($LASTEXITCODE -ne 0) { throw "SpikeHostExe.exe failed" } + & $cl /nologo /O2 /MT /W3 "$root\native\SpikeInject.c" /link /MACHINE:X86 /OUT:"$bin\SpikeInject.exe" + if ($LASTEXITCODE -ne 0) { throw "SpikeInject.exe failed" } +} finally { Pop-Location } + +# --- managed --- +foreach ($p in "Contracts", "Shim", "Payload") { + dotnet build "$root\$p\$p.csproj" -c Release -nologo -v q + if ($LASTEXITCODE -ne 0) { throw "$p build failed" } +} +Copy-Item "$root\Shim\bin\Release\net10.0\Shim.dll" $bin -Force +Copy-Item "$root\Contracts\bin\Release\net10.0\Contracts.dll" $bin -Force +Copy-Item "$root\Payload\bin\Release\net10.0\Payload.dll" "$bin\payload" -Force + +# --- app-local runtime --- +$pack = Join-Path $env:USERPROFILE ".nuget\packages\microsoft.netcore.app.runtime.win-x86" +$ver = (Get-ChildItem $pack | Where-Object Name -like "10.*" | Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1).Name +$rt = "$pack\$ver\runtimes\win-x86" +if (-not (Test-Path "$bin\runtime\coreclr.dll")) { + Copy-Item "$rt\native\*" "$bin\runtime" -Force + Copy-Item "$rt\lib\net10.0\*.dll" "$bin\runtime" -Force +} +Write-Host "Built spike with runtime $ver into $bin" diff --git a/spikes/CoreClrHost/Contracts/Contracts.csproj b/spikes/CoreClrHost/Contracts/Contracts.csproj new file mode 100644 index 0000000..2cb3dc9 --- /dev/null +++ b/spikes/CoreClrHost/Contracts/Contracts.csproj @@ -0,0 +1,8 @@ + + + net10.0 + x86 + enable + Contracts + + diff --git a/spikes/CoreClrHost/Contracts/IPayload.cs b/spikes/CoreClrHost/Contracts/IPayload.cs new file mode 100644 index 0000000..569d7b0 --- /dev/null +++ b/spikes/CoreClrHost/Contracts/IPayload.cs @@ -0,0 +1,17 @@ +namespace Contracts; + +/// What the Shim (default ALC) sees of a payload living in a collectible ALC. +public interface IPayload +{ + /// Address of an [UnmanagedCallersOnly] stdcall (int,int)->int method, or 0 with an error. + nint GetUcoPointer(out string? error); + + /// Marshal.GetFunctionPointerForDelegate of a stdcall (int,int)->int delegate the payload keeps alive. + nint GetDelegatePointer(); + + /// Does the work selected by the mode bits; returns a short description. + string Work(int mode); + + /// Stops everything Work started. + void Shutdown(); +} diff --git a/spikes/CoreClrHost/Payload/Payload.cs b/spikes/CoreClrHost/Payload/Payload.cs new file mode 100644 index 0000000..341ca00 --- /dev/null +++ b/spikes/CoreClrHost/Payload/Payload.cs @@ -0,0 +1,153 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.Json; +using Contracts; + +namespace Payload; + +// Mode bits (the Shim passes the host's mode through): +// 0x01 System.Text.Json reflection serialize/deserialize of payload types +// 0x02 start a Thread and join it in Shutdown +// 0x04 Task.Run work + a System.Threading.Timer, both finished/disposed in Shutdown +// 0x08 hold a 32 MB static array (the GC heap should give it back) +// 0x10 LEAK ON PURPOSE: subscribe to AppDomain.ProcessExit and never unsubscribe +// 0x20 JIT a lot of code (many generic instantiations over payload types) +// 0x40 allocate 8 MB with NativeMemory and free it in Shutdown +// 0x80 System.Text.Json reflection with a JsonSerializerOptions the payload owns +// 0x100 (Shim side) load a private copy of System.Text.Json into the collectible ALC +public sealed class Entry : IPayload +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int BinaryFn(int a, int b); + + private static byte[]? s_big; + private static BinaryFn? s_mul; + private Thread? _thread; + private volatile bool _stop; + private Timer? _timer; + private Task? _task; + private unsafe void* _native; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int Add(int a, int b) => a + b; + + public unsafe nint GetUcoPointer(out string? error) + { + try + { + error = null; + return (nint)(delegate* unmanaged[Stdcall])&Add; + } + catch (Exception ex) + { + error = ex.GetType().Name + ": " + ex.Message; + return 0; + } + } + + public nint GetDelegatePointer() + { + s_mul = (a, b) => a * b; + return Marshal.GetFunctionPointerForDelegate(s_mul); + } + + public unsafe string Work(int mode) + { + var did = new List(); + if ((mode & 0x01) != 0) + { + var rec = new Record { Name = "gen", Values = Enumerable.Range(0, 100).ToList(), Child = new Record { Name = "c" } }; + string json = JsonSerializer.Serialize(rec); + var back = JsonSerializer.Deserialize(json)!; + did.Add($"json {json.Length}b {back.Values.Count} stj alc {System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(typeof(JsonSerializer).Assembly)?.Name}"); + } + if ((mode & 0x80) != 0) + { + var opts = new JsonSerializerOptions { WriteIndented = false }; + var rec = new Record { Name = "own", Values = Enumerable.Range(0, 10).ToList() }; + string json = JsonSerializer.Serialize(rec, opts); + var back = JsonSerializer.Deserialize(json, opts)!; + did.Add($"json(own opts) {json.Length}b {back.Values.Count} stj@{typeof(JsonSerializer).Assembly.GetName().Name}:{System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(typeof(JsonSerializer).Assembly)?.Name}"); + } + if ((mode & 0x02) != 0) + { + _thread = new Thread(() => { while (!_stop) Thread.Sleep(5); }) { IsBackground = true, Name = "payload" }; + _thread.Start(); + did.Add("thread"); + } + if ((mode & 0x04) != 0) + { + _task = Task.Run(() => Thread.Sleep(20)); + _timer = new Timer(_ => { }, null, 0, 10); + did.Add("task+timer"); + } + if ((mode & 0x08) != 0) + { + s_big = new byte[32 * 1024 * 1024]; + s_big[^1] = 1; + did.Add("32MB static"); + } + if ((mode & 0x10) != 0) + { + AppDomain.CurrentDomain.ProcessExit += OnExit; + did.Add("LEAK ProcessExit"); + } + if ((mode & 0x20) != 0) + { + int n = JitMany(); + did.Add($"jit {n}"); + } + if ((mode & 0x40) != 0) + { + _native = NativeMemory.Alloc(8 * 1024 * 1024); + did.Add("native 8MB"); + } + return did.Count == 0 ? "basic" : string.Join(", ", did); + } + + private void OnExit(object? s, EventArgs e) { } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int JitMany() + { + int sum = 0; + sum += Gen.Run(); sum += Gen.Run(); sum += Gen.Run(); sum += Gen.Run(); + sum += Gen.Run(); sum += Gen.Run(); sum += Gen.Run(); sum += Gen.Run(); + var d = new Dictionary>(); d[new A1()] = new List { new() }; + sum += d.Count + d.Values.SelectMany(x => x).Count(); + return sum; + } + + public unsafe void Shutdown() + { + _stop = true; + _thread?.Join(); + _timer?.Dispose(); + _task?.Wait(); + if (_native != null) { NativeMemory.Free(_native); _native = null; } + s_big = null; + // s_mul stays: a static in the collectible ALC, it dies with the ALC. + } + + public sealed class Record + { + public string Name { get; set; } = ""; + public List Values { get; set; } = new(); + public Record? Child { get; set; } + } + + private sealed class A1 { } private sealed class A2 { } private sealed class A3 { } private sealed class A4 { } + private sealed class A5 { } private sealed class A6 { } private sealed class A7 { } private sealed class A8 { } + + private static class Gen where T : new() + { + public static int Run() + { + var list = new List(); + for (int i = 0; i < 16; i++) list.Add(new T()); + var set = new HashSet(list); + var dict = list.Select((x, i) => (x, i)).ToDictionary(p => p.x, p => p.i); + return list.Where(x => x != null).OrderBy(x => x!.GetHashCode()).Count() + set.Count + dict.Count; + } + } +} diff --git a/spikes/CoreClrHost/Payload/Payload.csproj b/spikes/CoreClrHost/Payload/Payload.csproj new file mode 100644 index 0000000..24df78a --- /dev/null +++ b/spikes/CoreClrHost/Payload/Payload.csproj @@ -0,0 +1,14 @@ + + + net10.0 + x86 + true + enable + enable + Payload + + + + + + diff --git a/spikes/CoreClrHost/Shim/Entry.cs b/spikes/CoreClrHost/Shim/Entry.cs new file mode 100644 index 0000000..b3be594 --- /dev/null +++ b/spikes/CoreClrHost/Shim/Entry.cs @@ -0,0 +1,134 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Loader; +using System.Text; +using Contracts; + +namespace Shim; + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct HostApi +{ + public int Size; + public delegate* unmanaged[Stdcall] FreeMb; + public delegate* unmanaged[Stdcall] Log; + public delegate* unmanaged[Stdcall] CallBinary; + public delegate* unmanaged[Stdcall] CommittedMb; +} + +public static unsafe class Entry +{ + private static HostApi* s_api; + + private static void Log(string msg) + { + byte[] bytes = Encoding.UTF8.GetBytes(msg + "\0"); + fixed (byte* p = bytes) s_api->Log(p); + } + + private static (double free, double largest) Free() + { + double largest; + double free = s_api->FreeMb(&largest); + return (free, largest); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + public static int Run(HostApi* api, int cycles, int mode) + { + s_api = api; + try + { + string dir = Path.GetDirectoryName(typeof(Entry).Assembly.Location)!; + string payloadPath = Path.Combine(dir, "payload", "Payload.dll"); + Log($"Shim up: CLR {Environment.Version}, {RuntimeInformation.ProcessArchitecture}, mode 0x{mode:x}, {cycles} cycles, payload {payloadPath}"); + + var (free0, _) = Free(); + uint commit0 = s_api->CommittedMb(); + double firstGenFree = 0; + int failures = 0; + for (int i = 1; i <= cycles; i++) + { + var sw = Stopwatch.StartNew(); + WeakReference alcRef = RunGeneration(i, payloadPath, mode, out string report); + long loadMs = sw.ElapsedMilliseconds; + sw.Restart(); + int collections = 0; + while (alcRef.IsAlive && sw.ElapsedMilliseconds < 5000) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + collections++; + if (alcRef.IsAlive) Thread.Sleep(5); + } + GC.Collect(); + bool freed = !alcRef.IsAlive; + if (!freed) failures++; + var (free, largest) = Free(); + if (i == 1) firstGenFree = free; + Log($"gen {i,2}: {report} | load+run {loadMs} ms | alc {(freed ? "freed" : "NOT freed")} after {collections} GCs, {sw.ElapsedMilliseconds} ms | free {free:F0} MB (largest {largest:F0}), vs gen1 {free - firstGenFree:+0;-0} MB | commit {s_api->CommittedMb()} MB | gc heap {GC.GetTotalMemory(false) / 1048576.0:F1} MB"); + } + var (freeEnd, _) = Free(); + Log($"done: {cycles} cycles, {failures} not freed; free {free0:F0} -> {freeEnd:F0} MB ({freeEnd - free0:+0;-0}), after gen1 {freeEnd - firstGenFree:+0;-0} MB; commit {commit0} -> {s_api->CommittedMb()} MB"); + return failures; + } + catch (Exception ex) + { + Log("Shim.Run failed: " + ex); + return -100; + } + } + + // NoInlining so no local in Run keeps the ALC, the assembly or the payload alive. + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference RunGeneration(int gen, string payloadPath, int mode, out string report) + { + var alc = new PayloadAlc($"gen{gen}", Path.GetDirectoryName(payloadPath)!, (mode & 0x100) != 0); + Assembly asm; + using (var fs = File.OpenRead(payloadPath)) asm = alc.LoadFromStream(fs); + var payload = (IPayload)Activator.CreateInstance(asm.GetType("Payload.Entry", throwOnError: true)!)!; + + var parts = new List(); + nint uco = payload.GetUcoPointer(out string? ucoError); + parts.Add(uco != 0 ? $"uco 2+3={s_api->CallBinary(uco, 2, 3)}" : $"uco FAILED {ucoError}"); + nint del = payload.GetDelegatePointer(); + parts.Add($"delegate 6*7={s_api->CallBinary(del, 6, 7)}"); + parts.Add(payload.Work(mode)); + payload.Shutdown(); + + report = string.Join("; ", parts); + alc.Unload(); + return new WeakReference(alc, trackResurrection: true); + } + + private sealed class PayloadAlc : AssemblyLoadContext + { + private static readonly string s_runtimeDir = Path.GetDirectoryName(typeof(object).Assembly.Location)!; + private static readonly HashSet s_private = new(StringComparer.OrdinalIgnoreCase) + { + "System.Text.Json", "System.Text.Encodings.Web", "System.IO.Pipelines", + }; + private readonly string _dir; + private readonly bool _privateFramework; + + public PayloadAlc(string name, string dir, bool privateFramework) : base(name, isCollectible: true) + { + _dir = dir; + _privateFramework = privateFramework; + } + + protected override Assembly? Load(AssemblyName name) + { + // Contracts and the framework come from the default ALC; anything else next to the payload loads here. + if (name.Name == "Contracts") return null; + if (_privateFramework && s_private.Contains(name.Name!)) + return LoadFromAssemblyPath(Path.Combine(s_runtimeDir, name.Name + ".dll")); + string candidate = Path.Combine(_dir, name.Name + ".dll"); + if (!File.Exists(candidate)) return null; + using var fs = File.OpenRead(candidate); + return LoadFromStream(fs); + } + } +} diff --git a/spikes/CoreClrHost/Shim/Shim.csproj b/spikes/CoreClrHost/Shim/Shim.csproj new file mode 100644 index 0000000..83ef59e --- /dev/null +++ b/spikes/CoreClrHost/Shim/Shim.csproj @@ -0,0 +1,14 @@ + + + net10.0 + x86 + true + enable + enable + Shim + false + + + + + diff --git a/spikes/CoreClrHost/native/SpikeHost.c b/spikes/CoreClrHost/native/SpikeHost.c new file mode 100644 index 0000000..776ae3d --- /dev/null +++ b/spikes/CoreClrHost/native/SpikeHost.c @@ -0,0 +1,216 @@ +// SpikeHost: Phase 0 spike for docs/UNLOADABLE_ENGINE_PLAN.md. +// +// Starts an app-local CoreCLR (x86) through the raw coreclr_* hosting API, loads +// Shim.dll into the default ALC and calls Shim.Entry.Run, which loads Payload.dll +// into a collectible ALC N times, calls into it from native code, unloads it and +// measures free address space through the HostApi below. +// +// Built as a DLL (SpikeHost.dll, export SpikeRun) so the same code can be injected +// into acclient; SpikeHostExe.exe is a console driver that LoadLibrary's it. + +#include +#include +#include + +typedef int (__stdcall *coreclr_initialize_fn)(const char* exePath, const char* appDomainFriendlyName, + int propertyCount, const char** propertyKeys, const char** propertyValues, + void** hostHandle, unsigned int* domainId); +typedef int (__stdcall *coreclr_create_delegate_fn)(void* hostHandle, unsigned int domainId, + const char* assemblyName, const char* typeName, const char* methodName, void** fn); + +typedef struct HostApi { + int size; + double (__stdcall *freeMb)(double* largestFreeMb); + void (__stdcall *log)(const char* utf8); + int (__stdcall *callBinary)(void* fn, int a, int b); // native frame -> managed fn pointer + unsigned int (__stdcall *committedMb)(void); +} HostApi; + +typedef int (__stdcall *shim_run_fn)(HostApi* api, int cycles, int mode); + +static char g_dir[MAX_PATH]; +static FILE* g_log; + +static void LogLine(const char* fmt, ...) +{ + char buf[2048]; + va_list ap; + va_start(ap, fmt); + _vsnprintf_s(buf, sizeof buf, _TRUNCATE, fmt, ap); + va_end(ap); + SYSTEMTIME t; + GetLocalTime(&t); + char line[2200]; + _snprintf_s(line, sizeof line, _TRUNCATE, "[%02d:%02d:%02d.%03d] [pid:%lu] %s\n", + t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, GetCurrentProcessId(), buf); + fputs(line, stdout); + fflush(stdout); + if (g_log) { fputs(line, g_log); fflush(g_log); } + OutputDebugStringA(line); +} + +static double __stdcall FreeMb(double* largestFreeMb) +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress; + unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress; + unsigned long long total = 0, largest = 0; + MEMORY_BASIC_INFORMATION mbi; + while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) { + if (mbi.State == MEM_FREE) { + total += mbi.RegionSize; + if (mbi.RegionSize > largest) largest = mbi.RegionSize; + } + p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize; + } + if (largestFreeMb) *largestFreeMb = largest / (1024.0 * 1024.0); + return total / (1024.0 * 1024.0); +} + +static unsigned int __stdcall CommittedMb(void) +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress; + unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress; + unsigned long long total = 0; + MEMORY_BASIC_INFORMATION mbi; + while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) { + if (mbi.State == MEM_COMMIT && mbi.Type == MEM_PRIVATE) total += mbi.RegionSize; + p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize; + } + return (unsigned int)(total / (1024 * 1024)); +} + +static void __stdcall ManagedLog(const char* utf8) { LogLine("[shim] %s", utf8); } + +static int __stdcall CallBinary(void* fn, int a, int b) +{ + typedef int (__stdcall *bin_fn)(int, int); + return ((bin_fn)fn)(a, b); +} + +// Appends every *.dll in dir to the ';'-separated TPA list. +static void AppendDlls(char* tpa, size_t cap, const char* dir) +{ + char pattern[MAX_PATH]; + _snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\*.dll", dir); + WIN32_FIND_DATAA fd; + HANDLE h = FindFirstFileA(pattern, &fd); + if (h == INVALID_HANDLE_VALUE) return; + do { + // Native runtime DLLs sit in the same folder; skip what isn't managed. + const char* n = fd.cFileName; + if (!_stricmp(n, "coreclr.dll") || !_stricmp(n, "clrjit.dll") || !_stricmp(n, "clrgc.dll") || + !_stricmp(n, "hostfxr.dll") || !_stricmp(n, "hostpolicy.dll") || !_stricmp(n, "mscordaccore.dll") || + !_stricmp(n, "mscordbi.dll") || !_stricmp(n, "mscorrc.dll") || !_stricmp(n, "clretwrc.dll") || + !_strnicmp(n, "mscordaccore_", 13) || !_stricmp(n, "msquic.dll") || + !_stricmp(n, "System.IO.Compression.Native.dll") || !_stricmp(n, "Microsoft.DiaSymReader.Native.x86.dll") || + !_stricmp(n, "SpikeHost.dll")) + continue; + strcat_s(tpa, cap, dir); + strcat_s(tpa, cap, "\\"); + strcat_s(tpa, cap, n); + strcat_s(tpa, cap, ";"); + } while (FindNextFileA(h, &fd)); + FindClose(h); +} + +__declspec(dllexport) int __stdcall SpikeRun(int cycles, int mode) +{ + HMODULE self; + GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCSTR)&SpikeRun, &self); + GetModuleFileNameA(self, g_dir, MAX_PATH); + *strrchr(g_dir, '\\') = 0; + + char logPath[MAX_PATH]; + _snprintf_s(logPath, sizeof logPath, _TRUNCATE, "%s\\spike.%lu.log", g_dir, GetCurrentProcessId()); + fopen_s(&g_log, logPath, "a"); + + double largest; + double free0 = FreeMb(&largest); + LogLine("host: start, free %.0f MB (largest %.0f), private commit %u MB", free0, largest, CommittedMb()); + + char runtimeDir[MAX_PATH], coreclrPath[MAX_PATH]; + _snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\runtime", g_dir); + _snprintf_s(coreclrPath, sizeof coreclrPath, _TRUNCATE, "%s\\coreclr.dll", runtimeDir); + + DWORD t0 = GetTickCount(); + HMODULE clr = LoadLibraryExA(coreclrPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + if (!clr) { LogLine("host: LoadLibrary coreclr failed %lu", GetLastError()); return -1; } + coreclr_initialize_fn init = (coreclr_initialize_fn)GetProcAddress(clr, "coreclr_initialize"); + coreclr_create_delegate_fn create = (coreclr_create_delegate_fn)GetProcAddress(clr, "coreclr_create_delegate"); + if (!init || !create) { LogLine("host: coreclr exports missing"); return -2; } + + static char tpa[64 * 1024]; + tpa[0] = 0; + AppendDlls(tpa, sizeof tpa, runtimeDir); + AppendDlls(tpa, sizeof tpa, g_dir); // Shim.dll + Contracts.dll (default ALC) + + // Mode bit 0x200: concurrent (background) GC on. + const char* keys[] = { + "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", + "System.GC.Server", "System.GC.Concurrent", "System.Globalization.Invariant", + "System.GC.RetainVM", + }; + char nativeDirs[2 * MAX_PATH + 4]; + _snprintf_s(nativeDirs, sizeof nativeDirs, _TRUNCATE, "%s;%s;", runtimeDir, g_dir); + const char* values[] = { + tpa, "", nativeDirs, + "false", (mode & 0x200) ? "true" : "false", "true", + "false", + }; + int count = sizeof keys / sizeof keys[0]; + + char exePath[MAX_PATH]; + GetModuleFileNameA(NULL, exePath, MAX_PATH); + void* hostHandle = NULL; + unsigned int domainId = 0; + int hr = init(exePath, "RynthCoreSpike", count, keys, values, &hostHandle, &domainId); + if (hr < 0) { LogLine("host: coreclr_initialize failed 0x%08x", hr); return -3; } + LogLine("host: CoreCLR up in %lu ms, free %.0f MB (cost %.0f MB), private commit %u MB", + GetTickCount() - t0, FreeMb(&largest), free0 - FreeMb(NULL), CommittedMb()); + + shim_run_fn run = NULL; + hr = create(hostHandle, domainId, "Shim", "Shim.Entry", "Run", (void**)&run); + if (hr < 0 || !run) { LogLine("host: create_delegate Shim.Entry.Run failed 0x%08x", hr); return -4; } + + static HostApi api; + api.size = sizeof api; + api.freeMb = FreeMb; + api.log = ManagedLog; + api.callBinary = CallBinary; + api.committedMb = CommittedMb; + int rc = run(&api, cycles, mode); + LogLine("host: Shim.Run returned %d, free %.0f MB (largest %.0f)", rc, FreeMb(&largest), largest); + if (g_log) { fclose(g_log); g_log = NULL; } + return rc; +} + +// Injected use: RYNTH_SPIKE_AUTORUN="cycles,mode,delayMs" in the target's environment +// makes DllMain start a worker (no CLR work under the loader lock). +static int g_autoCycles = 20, g_autoMode = 0, g_autoDelay = 3000; + +static DWORD WINAPI AutoRun(LPVOID p) +{ + (void)p; + Sleep(g_autoDelay); + SpikeRun(g_autoCycles, g_autoMode); + return 0; +} + +BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved) +{ + (void)h; (void)reserved; + if (reason == DLL_PROCESS_ATTACH) { + char v[64]; + if (GetEnvironmentVariableA("RYNTH_SPIKE_AUTORUN", v, sizeof v) > 0) { + sscanf_s(v, "%d,%i,%d", &g_autoCycles, &g_autoMode, &g_autoDelay); + HANDLE t = CreateThread(NULL, 0, AutoRun, NULL, 0, NULL); + if (t) CloseHandle(t); + } + } + return TRUE; +} diff --git a/spikes/CoreClrHost/native/SpikeHostExe.c b/spikes/CoreClrHost/native/SpikeHostExe.c new file mode 100644 index 0000000..e9e087a --- /dev/null +++ b/spikes/CoreClrHost/native/SpikeHostExe.c @@ -0,0 +1,19 @@ +// Console driver: SpikeHostExe.exe [cycles] [mode]. LoadLibrary's SpikeHost.dll the +// way an injected loader would and calls SpikeRun. +#include +#include +#include + +typedef int (__stdcall *spike_run_fn)(int cycles, int mode); + +int main(int argc, char** argv) +{ + int cycles = argc > 1 ? atoi(argv[1]) : 20; + int mode = argc > 2 ? (int)strtol(argv[2], NULL, 0) : 0; + HMODULE h = LoadLibraryA("SpikeHost.dll"); + if (!h) { printf("LoadLibrary SpikeHost.dll failed %lu\n", GetLastError()); return 1; } + spike_run_fn run = (spike_run_fn)GetProcAddress(h, "_SpikeRun@8"); + if (!run) run = (spike_run_fn)GetProcAddress(h, "SpikeRun"); + if (!run) { printf("SpikeRun export missing\n"); return 2; } + return run(cycles, mode); +} diff --git a/spikes/CoreClrHost/native/SpikeInject.c b/spikes/CoreClrHost/native/SpikeInject.c new file mode 100644 index 0000000..25f2eb4 --- /dev/null +++ b/spikes/CoreClrHost/native/SpikeInject.c @@ -0,0 +1,53 @@ +// SpikeInject: starts acclient.exe suspended, LoadLibrary's SpikeHost.dll into it with +// RYNTH_SPIKE_AUTORUN set, resumes it, waits, then terminates it. +// SpikeInject.exe [acclient args...] +#include +#include +#include + +int main(int argc, char** argv) +{ + if (argc < 5) { printf("usage: SpikeInject [args]\n"); return 1; } + const char* exe = argv[1]; + const char* dll = argv[2]; + int waitSeconds = atoi(argv[4]); + SetEnvironmentVariableA("RYNTH_SPIKE_AUTORUN", argv[3]); + + char cmd[4096]; + _snprintf_s(cmd, sizeof cmd, _TRUNCATE, "\"%s\"", exe); + for (int i = 5; i < argc; i++) { strcat_s(cmd, sizeof cmd, " "); strcat_s(cmd, sizeof cmd, argv[i]); } + char dir[MAX_PATH]; + strcpy_s(dir, sizeof dir, exe); + *strrchr(dir, '\\') = 0; + + STARTUPINFOA si = { sizeof si }; + PROCESS_INFORMATION pi; + if (!CreateProcessA(exe, cmd, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, dir, &si, &pi)) { + printf("CreateProcess failed %lu\n", GetLastError()); return 2; + } + printf("SPIKE_PID=%lu\n", pi.dwProcessId); + + size_t len = strlen(dll) + 1; + void* remote = VirtualAllocEx(pi.hProcess, NULL, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + WriteProcessMemory(pi.hProcess, remote, dll, len, NULL); + FARPROC loadLib = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA"); + HANDLE t = CreateRemoteThread(pi.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadLib, remote, 0, NULL); + if (!t) { printf("CreateRemoteThread failed %lu\n", GetLastError()); TerminateProcess(pi.hProcess, 1); return 3; } + WaitForSingleObject(t, 30000); + DWORD mod = 0; + GetExitCodeThread(t, &mod); + printf("LoadLibrary in target -> 0x%08lx\n", mod); + CloseHandle(t); + ResumeThread(pi.hThread); + + DWORD r = WaitForSingleObject(pi.hProcess, waitSeconds * 1000); + if (r == WAIT_OBJECT_0) { + DWORD code = 0; + GetExitCodeProcess(pi.hProcess, &code); + printf("acclient exited by itself, code 0x%08lx\n", code); + } else { + TerminateProcess(pi.hProcess, 0); + printf("acclient terminated after %d s\n", waitSeconds); + } + return 0; +} diff --git a/spikes/DecalBridge/AcWindow.py b/spikes/DecalBridge/AcWindow.py new file mode 100644 index 0000000..546b845 --- /dev/null +++ b/spikes/DecalBridge/AcWindow.py @@ -0,0 +1,169 @@ +"""AcWindow.py - look at and click ONE test client's game window, by its process id. + +Spike helper (Decal bridge): used once, to drive the retail character-creation screen of a +test client. Everything goes to the HWND of the given pid (PostMessage), so no other window +- and no other client - is touched, and nothing moves the real mouse or keyboard. + + python AcWindow.py shot + python AcWindow.py click client coordinates of the game window + python AcWindow.py type + python AcWindow.py key e.g. 0x0D (Enter), 0x08 (Backspace) +""" +import ctypes +import ctypes.wintypes as wt +import sys +import time + +user32 = ctypes.WinDLL("user32", use_last_error=True) +gdi32 = ctypes.WinDLL("gdi32", use_last_error=True) +user32.PostMessageW.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p] +user32.GetClientRect.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.RECT)] +user32.GetWindowThreadProcessId.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.DWORD)] +user32.GetClassNameW.argtypes = [ctypes.c_void_p, wt.LPWSTR, ctypes.c_int] +user32.IsWindowVisible.argtypes = [ctypes.c_void_p] +user32.PrintWindow.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint] +user32.GetDC.argtypes = [ctypes.c_void_p] +user32.GetDC.restype = ctypes.c_void_p +user32.ReleaseDC.argtypes = [ctypes.c_void_p, ctypes.c_void_p] +gdi32.CreateCompatibleDC.argtypes = [ctypes.c_void_p] +gdi32.CreateCompatibleDC.restype = ctypes.c_void_p +gdi32.CreateCompatibleBitmap.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] +gdi32.CreateCompatibleBitmap.restype = ctypes.c_void_p +gdi32.SelectObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p] +gdi32.GetDIBits.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint] +gdi32.DeleteObject.argtypes = [ctypes.c_void_p] +gdi32.DeleteDC.argtypes = [ctypes.c_void_p] + +WM_MOUSEMOVE, WM_LBUTTONDOWN, WM_LBUTTONUP = 0x0200, 0x0201, 0x0202 +WM_KEYDOWN, WM_KEYUP, WM_CHAR = 0x0100, 0x0101, 0x0102 + + +def game_window(pid): + found = [] + proto = ctypes.WINFUNCTYPE(wt.BOOL, ctypes.c_void_p, ctypes.c_void_p) + + def cb(hwnd, _): + owner = wt.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + if owner.value == pid and user32.IsWindowVisible(hwnd): + cls = ctypes.create_unicode_buffer(128) + user32.GetClassNameW(hwnd, cls, 128) + if cls.value == "Turbine Device Class": + found.append(hwnd) + return True + + user32.EnumWindows(proto(cb), None) + if not found: + raise SystemExit(f"no game window for pid {pid}") + return found[0] + + +def dialogs(pid): + """Message boxes (#32770) the process has open, with their static text.""" + proto = ctypes.WINFUNCTYPE(wt.BOOL, ctypes.c_void_p, ctypes.c_void_p) + user32.GetWindowTextW.argtypes = [ctypes.c_void_p, wt.LPWSTR, ctypes.c_int] + out = [] + + def top(hwnd, _): + owner = wt.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + cls = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, cls, 64) + if owner.value == pid and cls.value == "#32770" and user32.IsWindowVisible(hwnd): + texts = [] + + def child(ch, _): + c = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(ch, c, 64) + t = ctypes.create_unicode_buffer(1024) + user32.GetWindowTextW(ch, t, 1024) + if t.value: + texts.append(f"{c.value}: {t.value}") + return True + + user32.EnumChildWindows(ctypes.c_void_p(hwnd), proto(child), None) + out.append((hwnd, texts)) + return True + + user32.EnumWindows(proto(top), None) + for hwnd, texts in out: + print(f"dialog 0x{hwnd:X}: " + " | ".join(texts)) + if not out: + print("no dialogs") + + +def shot(pid, out): + from PIL import Image + hwnd = game_window(pid) + r = wt.RECT() + user32.GetClientRect(hwnd, ctypes.byref(r)) + w, h = r.right, r.bottom + hdc = user32.GetDC(hwnd) + mdc = gdi32.CreateCompatibleDC(hdc) + bmp = gdi32.CreateCompatibleBitmap(hdc, w, h) + gdi32.SelectObject(mdc, bmp) + user32.PrintWindow(hwnd, mdc, 3) # PW_CLIENTONLY | PW_RENDERFULLCONTENT + bmi = (ctypes.c_byte * 40)() + ctypes.memmove(bmi, (ctypes.c_int * 3)(40, w, -h), 12) + ctypes.memmove(ctypes.byref(bmi, 12), (ctypes.c_short * 2)(1, 32), 4) + buf = (ctypes.c_byte * (w * h * 4))() + gdi32.GetDIBits(mdc, bmp, 0, h, buf, bmi, 0) + Image.frombuffer("RGB", (w, h), bytes(buf), "raw", "BGRX", 0, 1).save(out) + gdi32.DeleteObject(bmp) + gdi32.DeleteDC(mdc) + user32.ReleaseDC(hwnd, hdc) + print(f"{w}x{h} -> {out}") + + +def click(pid, x, y): + hwnd = game_window(pid) + lp = (y << 16) | (x & 0xFFFF) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lp) + time.sleep(0.08) + user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp) + + +def drag(pid, x0, y0, x1, y1): + hwnd = game_window(pid) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, (y0 << 16) | x0) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, (y0 << 16) | x0) + for i in range(1, 11): + x = x0 + (x1 - x0) * i // 10 + y = y0 + (y1 - y0) * i // 10 + time.sleep(0.03) + user32.PostMessageW(hwnd, WM_MOUSEMOVE, 1, (y << 16) | x) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, (y1 << 16) | x1) + + +def type_text(pid, text): + hwnd = game_window(pid) + for ch in text: + user32.PostMessageW(hwnd, WM_CHAR, ord(ch), 1) + time.sleep(0.04) + + +def key(pid, vk): + hwnd = game_window(pid) + user32.PostMessageW(hwnd, WM_KEYDOWN, vk, 1) + time.sleep(0.05) + user32.PostMessageW(hwnd, WM_KEYUP, vk, 0xC0000001) + + +if __name__ == "__main__": + cmd, pid = sys.argv[1], int(sys.argv[2]) + if cmd == "shot": + shot(pid, sys.argv[3]) + elif cmd == "click": + click(pid, int(sys.argv[3]), int(sys.argv[4])) + elif cmd == "dialogs": + dialogs(pid) + elif cmd == "drag": + drag(pid, *(int(v) for v in sys.argv[3:7])) + elif cmd == "type": + type_text(pid, sys.argv[3]) + elif cmd == "key": + key(pid, int(sys.argv[3], 0)) diff --git a/spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs b/spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs new file mode 100644 index 0000000..8657bd9 --- /dev/null +++ b/spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs @@ -0,0 +1,157 @@ +// BridgeProbe - a trivial RynthCore plugin for the Decal-bridge spike. It logs the first +// few of every event it receives, and a count per event every 15 s, through the host log, +// so the engine log shows what reached a plugin in bridge mode. +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.PluginCore; + +namespace RynthCore.Plugin.BridgeProbe; + +public sealed class BridgeProbePlugin : RynthPluginBase +{ + internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("BridgeProbe"); + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0"); + + private int _raLines; + private int _chat, _chatBar, _create, _delete, _update, _health, _damage, _enchAdd, _enchRem, _kill, _ticks; + private long _lastSummary; + private const int FirstN = 5; + // Every chat line, for reading command output on a test client: BRIDGEPROBE_ALLCHAT=1, or a + // file "bridgeprobe-allchat.flag" next to the client's dispatch file (read at plugin load). + private static readonly bool AllChat = Environment.GetEnvironmentVariable("BRIDGEPROBE_ALLCHAT") == "1" || FlagFileExists(); + + private static bool FlagFileExists() + { + try + { + string? dispatch = Environment.GetEnvironmentVariable("RYNTHCORE_DISPATCH_FILE"); + string? dir = string.IsNullOrEmpty(dispatch) ? null : System.IO.Path.GetDirectoryName(dispatch); + return dir != null && System.IO.File.Exists(System.IO.Path.Combine(dir, "bridgeprobe-allchat.flag")); + } + catch { return false; } + } + + public override int Initialize() + { + Log("BridgeProbe: initialized."); + return 0; + } + + public override void OnLoginComplete() => Log("BridgeProbe: OnLoginComplete"); + + public override void OnChatWindowText(string? text, int chatType, ref int eat) + { + // BRIDGEPROBE_ALLCHAT=1: log every chat line (reading command output on a test client). + if (_chat++ < FirstN || AllChat) Log($"BridgeProbe: OnChatWindowText type={chatType} '{text?.TrimEnd('\n')}'"); + // RynthAi's answers to the harness's "/ra cache": its object cache, as seen in chat. + else if (text != null && text.Contains("[RynthAi]") && _raLines++ < 30) + Log($"BridgeProbe: RynthAi said: '{text.TrimEnd('\n')}'"); + } + + public override void OnChatBarEnter(string? text, ref int eat) + { + if (_chatBar++ < FirstN) Log($"BridgeProbe: OnChatBarEnter '{text}'"); + } + + public override void OnCreateObject(uint objectId) + { + if (_create++ < FirstN) Log($"BridgeProbe: OnCreateObject 0x{objectId:X8}"); + } + + public override void OnDeleteObject(uint objectId) + { + if (_delete++ < FirstN) Log($"BridgeProbe: OnDeleteObject 0x{objectId:X8}"); + } + + public override void OnUpdateObject(uint objectId) => _update++; + + public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + { + if (_health++ < FirstN) Log($"BridgeProbe: OnUpdateHealth 0x{targetId:X8} ratio={healthRatio:0.00} {currentHealth}/{maxHealth}"); + } + + public override void OnCombatDamage(uint damage, uint damageType, bool crit, bool isAttacker) + { + if (_damage++ < FirstN) Log($"BridgeProbe: OnCombatDamage {damage} type={damageType} crit={crit} attacker={isAttacker}"); + } + + public override void OnKillNotification(string? deathMessage) + { + if (_kill++ < FirstN) Log($"BridgeProbe: OnKillNotification '{deathMessage}'"); + } + + public override void OnEnchantmentAdded(uint spellId, double durationSeconds) + { + if (_enchAdd++ < FirstN) Log($"BridgeProbe: OnEnchantmentAdded spell={spellId} dur={durationSeconds:0}"); + } + + public override void OnEnchantmentRemoved(uint enchantmentId) + { + if (_enchRem++ < FirstN) Log($"BridgeProbe: OnEnchantmentRemoved {enchantmentId}"); + } + + public override void OnTick() + { + _ticks++; + long now = Environment.TickCount64; + if (now - _lastSummary < 15000) return; + _lastSummary = now; + Log($"BridgeProbe: counts ticks={_ticks} chat={_chat} chatBar={_chatBar} create={_create} delete={_delete} update={_update} " + + $"health={_health} damage={_damage} kill={_kill} enchAdd={_enchAdd} enchRem={_enchRem}"); + } +} + +public static unsafe class PluginExports +{ + private static readonly RynthPluginRuntime Runtime = new(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Init(RynthCore.PluginSdk.RynthCoreApiNative* api) => Runtime.Init(api); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Shutdown() => Runtime.Shutdown(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetName() => BridgeProbePlugin.NamePointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetVersion() => BridgeProbePlugin.VersionPointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Tick() => Runtime.OnTick(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLoginComplete() => Runtime.OnLoginComplete(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObject", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateObject(uint objectId) => Runtime.OnUpdateObject(objectId); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + => Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatDamage", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnCombatDamage(uint damage, uint damageType, uint crit, uint isAttacker) => Runtime.OnCombatDamage(damage, damageType, crit, isAttacker); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentAdded", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnEnchantmentAdded(uint spellId, double durationSeconds) => Runtime.OnEnchantmentAdded(spellId, durationSeconds); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId); +} diff --git a/spikes/DecalBridge/BridgeProbePlugin/RynthCore.Plugin.BridgeProbe.csproj b/spikes/DecalBridge/BridgeProbePlugin/RynthCore.Plugin.BridgeProbe.csproj new file mode 100644 index 0000000..eb2dd54 --- /dev/null +++ b/spikes/DecalBridge/BridgeProbePlugin/RynthCore.Plugin.BridgeProbe.csproj @@ -0,0 +1,23 @@ + + + + + net10.0-windows + x86 + win-x86 + false + false + Library + true + enable + RynthCore.Plugin.BridgeProbe + RynthCore.Plugin.BridgeProbe + + + + + + + + diff --git a/spikes/DecalBridge/Inject-BridgeRecords.py b/spikes/DecalBridge/Inject-BridgeRecords.py new file mode 100644 index 0000000..d73a225 --- /dev/null +++ b/spikes/DecalBridge/Inject-BridgeRecords.py @@ -0,0 +1,65 @@ +"""Inject-BridgeRecords.py - append SYNTHETIC records to a test client's Decal-bridge ring. + +For testing the engine half of the bridge while no server is available: it writes the same +records the bridge would (BridgeProtocol.cs layout) into Local\\RynthCore.DecalBridge.p. +Only use it on a test client whose bridge is idle (pre-login), or the two writers race. +""" +import mmap +import struct +import sys + +# BridgeProtocol.cs version 2: header, 64 KB command ring, then the event ring. +HEADER, CMD, RING = 4096, 64 * 1024, 16 * 1024 * 1024 +RING_BASE = HEADER + CMD +OFF_WRITE, OFF_READ, OFF_RECORDS = 16, 24, 40 +K_CHAT, K_CHATBAR, K_CREATE, K_RELEASE, K_CHANGE, K_SERVER = 2, 3, 4, 5, 6, 7 + + +def main(): + pid = int(sys.argv[1]) + m = mmap.mmap(-1, RING_BASE + RING, tagname=f"Local\\RynthCore.DecalBridge.p{pid}") + magic, version = struct.unpack_from("= rec and RING - (w - r) > rec + base = RING_BASE + pos + struct.pack_into(" $null + $tp = [int]((Get-Content C:\Games\RynthCore\Test\decal-spike-pids.txt -Tail 1).Split(' ')[2]) + Write-Host "==== launch $i pid $tp" + $lines = python $watch $tp 25 @addrs 2>&1 + $lines | ForEach-Object { Write-Host " $_" } + $final = @{} + foreach ($l in $lines) { if ($l -match '^\S+ (0x[0-9A-F]{8}) \S+ -> (.*)$') { $final[$Matches[1]] = $Matches[2] } } + $lost = $addrs[0..1] | Where-Object { $final[$_] -like "Decal*" } + Write-Host " final: $(($addrs | ForEach-Object { "$_=$($final[$_])" }) -join '; ')" + if ($lost) { + Write-Host " Decal is on top at $($lost -join ', ') -> hot reload, watching" + $job = Start-Job { python $using:watch $using:tp 14 @using:addrs 2>&1 } + Start-Sleep 1 + $ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$tp") + [void]$ev.Set(); $ev.Dispose() + Wait-Job $job -Timeout 30 | Out-Null + Receive-Job $job | ForEach-Object { Write-Host " $_" } + } + Stop-Process -Id $tp -Force -ErrorAction SilentlyContinue + Start-Sleep 2 +} diff --git a/spikes/DecalBridge/Register-DecalBridge.ps1 b/spikes/DecalBridge/Register-DecalBridge.ps1 new file mode 100644 index 0000000..dfcf3b8 --- /dev/null +++ b/spikes/DecalBridge/Register-DecalBridge.ps1 @@ -0,0 +1,37 @@ +# Register-DecalBridge.ps1 - registers (or removes) the RynthCore Decal bridge for this +# Windows user, for TEST clients. A thin wrapper over the real code +# (src\RynthCore.App\DecalBridgeRegistration.cs, the same class the launcher uses for +# "Decal + RynthCore" accounts), reached through RynthCore.Injector --decal-bridge. +# +# What it does (docs\DECAL_BRIDGE_PLAN.md, "Registration"): no admin rights, nothing under +# HKLM. The bridge's entry goes into the per-user registry VirtualStore copy of Decal's +# NetworkFilters key, which the virtualized 32-bit acclient.exe reads instead of HKLM's. If +# that per-user key has to be created, every HKLM filter entry is mirrored into it first +# (otherwise Decal would see only the bridge: no WorldFilter, VTank refuses to start). +# Everything added is recorded in %APPDATA%\RynthCore\decal-bridge-registration.json and +# -Remove takes away exactly that. +# +# The bridge idles in every Decal client of this user until RynthCore is in the same client. +# +# .\Register-DecalBridge.ps1 build the bridge, copy it to Test\decal-bridge, register +# .\Register-DecalBridge.ps1 -Status show what a Decal client would load +# .\Register-DecalBridge.ps1 -Remove remove what the registration added +param([switch]$Remove, [switch]$Status) +$ErrorActionPreference = "Stop" +$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$dir = "C:\Games\RynthCore\Test\decal-bridge" +$injector = "$repo\out\injector-spike\RynthCore.Injector.exe" +dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector-spike" -nologo -v q | Out-Null +if ($LASTEXITCODE -ne 0) { throw "injector build failed" } + +if ($Status) { & $injector --decal-bridge status; return } +if ($Remove) { & $injector --decal-bridge unregister; return } + +dotnet build "$repo\src\RynthCore.DecalBridge\RynthCore.DecalBridge.csproj" -c Release -nologo -v q | Out-Null +if ($LASTEXITCODE -ne 0) { throw "bridge build failed" } +$built = "$repo\src\RynthCore.DecalBridge\bin\Release\RynthCore.DecalBridge.dll" +if (-not (Test-Path $built)) { throw "bridge not built (is Decal installed?)" } +New-Item -ItemType Directory -Force $dir | Out-Null +# Decal clients that loaded the old copy keep it locked until they exit. +Copy-Item $built $dir -Force +& $injector --decal-bridge register --dir $dir diff --git a/spikes/DecalBridge/Start-DecalTestClient.ps1 b/spikes/DecalBridge/Start-DecalTestClient.ps1 new file mode 100644 index 0000000..31c8182 --- /dev/null +++ b/spikes/DecalBridge/Start-DecalTestClient.ps1 @@ -0,0 +1,59 @@ +# Start-DecalTestClient.ps1 - Decal-bridge spike: start ONE test client with Decal and/or +# the CoreCLR RynthCore engine from a TEST runtime folder, against Tom's local server. +# +# -Mode DecalOnly Decal alone (Inject.dll + DecalStartup) - baseline +# -Mode EngineOnly RynthCore alone - baseline +# -Mode Both Decal first, then RynthCore (the coexistence case) +# +# Same isolation as scripts\Test-ClrWorld.ps1: its own engine settings, LOCALAPPDATA and +# dispatch file; RYNTHCORE_TEST_CLIENT marks it. -Bridge sets the engine's bridge mode for this +# client only (RYNTHCORE_DECAL_BRIDGE: Auto = unset, the engine.json default; On = 1; Off = 0, +# which also keeps the bridge filter itself idle); -InGameUi does the same for DecalInGameImGui. +# The bridge arms by itself when the RynthCore loader is in the client, so it must be registered +# (RynthCore.Injector --decal-bridge register). +# Never point -Runtime at C:\Games\RynthCore\Runtime (the live runtime every client shares). +param( + [ValidateSet("DecalOnly", "EngineOnly", "Both")] [string]$Mode = "Both", + [string]$Account = "Buffi", + [string]$Server = "ACEmulator", + [string]$Character = "+Buffi", + [string]$Runtime = "C:\Games\RynthCore\Test\rt-decal", + [string]$Settings = "C:\Games\RynthCore\Test\engine-decal.json", + # Override the server profile's host/port for this launch (the profile is not changed). + [string]$HostName = "", + [int]$Port = 0, + [ValidateSet("Auto", "On", "Off")] [string]$Bridge = "Auto", + [switch]$NoBridge, # = -Bridge Off + # In-game ImGui under Decal (engine.json DecalInGameImGui, default on): Default leaves + # RYNTHCORE_DECAL_IMGUI unset; On = 1; Off = 0 (the old coexistence path, no D3D9). + [ValidateSet("Default", "On", "Off")] [string]$InGameUi = "Default" +) +$ErrorActionPreference = "Stop" +if ([IO.Path]::GetFullPath($Runtime).TrimEnd('\') -ieq "C:\Games\RynthCore\Runtime") { throw "refusing the live runtime" } +$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$injector = "$repo\out\injector-spike\RynthCore.Injector.exe" +if (-not (Test-Path $injector)) { + dotnet publish "$repo\src\RynthCore.Injector\RynthCore.Injector.csproj" -c Release -o "$repo\out\injector-spike" -nologo -v q | Out-Null +} +$env:RYNTHCORE_ENGINE_SETTINGS = $Settings +$env:RYNTHCORE_TEST_CLIENT = "DecalBridgeSpike" +$env:LOCALAPPDATA = "C:\Games\RynthCore\Test\localappdata" +New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null +$env:RYNTHCORE_DISPATCH_FILE = "C:\Games\RynthCore\Test\dispatch-decal.txt" +Set-Content $env:RYNTHCORE_DISPATCH_FILE "# decal spike dispatch file" +# Set or clear both every time: a script run in the same session must not inherit the last run's. +if ($NoBridge) { $Bridge = "Off" } +$env:RYNTHCORE_DECAL_BRIDGE = switch ($Bridge) { "On" { "1" } "Off" { "0" } default { $null } } +$env:RYNTHCORE_DECAL_IMGUI = switch ($InGameUi) { "On" { "1" } "Off" { "0" } default { $null } } + +$launchArgs = @("--launch", "--account", $Account, "--server", $Server, "--engine", "$Runtime\RynthCore.Loader.dll", "--character", $Character) +if ($Mode -eq "DecalOnly") { $launchArgs += "--decal-only" } elseif ($Mode -eq "Both") { $launchArgs += "--decal" } +if ($HostName) { $launchArgs += @("--host", $HostName) } +if ($Port -gt 0) { $launchArgs += @("--port", "$Port") } +$out = & $injector $launchArgs 2>&1 +$out | ForEach-Object { Write-Host " $_" } +$m = $out | Select-String "LAUNCHED_PID=(\d+)" +if (-not $m) { throw "launch failed" } +$clientPid = [int]$m.Matches[0].Groups[1].Value +Add-Content "C:\Games\RynthCore\Test\decal-spike-pids.txt" "$(Get-Date -Format s) $Mode $clientPid" +Write-Host "TEST_PID=$clientPid" diff --git a/spikes/DecalBridge/Test-DecalBridgeInWorld.ps1 b/spikes/DecalBridge/Test-DecalBridgeInWorld.ps1 new file mode 100644 index 0000000..5848ede --- /dev/null +++ b/spikes/DecalBridge/Test-DecalBridgeInWorld.ps1 @@ -0,0 +1,168 @@ +# Test-DecalBridgeInWorld.ps1 - the in-world half of the Decal-bridge spike, in one command. +# Needs Tom's LOCAL server running and the bridge registered (Register-DecalBridge.ps1, or +# RynthCore.Injector --decal-bridge register --dir ). +# TEST CLIENTS ONLY: it starts its own clients from C:\Games\RynthCore\AcClient and kills only +# the PIDs it started. Three runs, one test client at a time: +# A Decal only (opt-in: -Runs A,B,C; nothing auto-selects the character without the +# engine, so pick it by hand) -> which code Decal + its plugins patch in world +# B Decal + RynthCore, bridge (DecalBridge=Auto) -> bridge traffic, a plugin receiving it, +# a TYPED chat-bar command, a line sent to AC through +# Decal (/loc), 2 hot reloads, VTank loaded, the own-device +# ImGui pop-out (snapshot BMP) +# C Decal + RynthCore, DecalBridge=Off (the old coexistence mode) -> who owns the contested hooks +# D RynthCore only, no Decal (normal hook mode must be unchanged) +# Everything lands in C:\Games\RynthCore\Test\decal-bridge\inworld-