RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9b5e2765b7
commit
a24ed6df7c
322 changed files with 83009 additions and 7504 deletions
52
spikes/CoreClrHost/Build.ps1
Normal file
52
spikes/CoreClrHost/Build.ps1
Normal file
|
|
@ -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 <cycles> <mode> (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"
|
||||
8
spikes/CoreClrHost/Contracts/Contracts.csproj
Normal file
8
spikes/CoreClrHost/Contracts/Contracts.csproj
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>Contracts</AssemblyName>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
17
spikes/CoreClrHost/Contracts/IPayload.cs
Normal file
17
spikes/CoreClrHost/Contracts/IPayload.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
namespace Contracts;
|
||||
|
||||
/// <summary>What the Shim (default ALC) sees of a payload living in a collectible ALC.</summary>
|
||||
public interface IPayload
|
||||
{
|
||||
/// <summary>Address of an [UnmanagedCallersOnly] stdcall (int,int)->int method, or 0 with an error.</summary>
|
||||
nint GetUcoPointer(out string? error);
|
||||
|
||||
/// <summary>Marshal.GetFunctionPointerForDelegate of a stdcall (int,int)->int delegate the payload keeps alive.</summary>
|
||||
nint GetDelegatePointer();
|
||||
|
||||
/// <summary>Does the work selected by the mode bits; returns a short description.</summary>
|
||||
string Work(int mode);
|
||||
|
||||
/// <summary>Stops everything Work started.</summary>
|
||||
void Shutdown();
|
||||
}
|
||||
153
spikes/CoreClrHost/Payload/Payload.cs
Normal file
153
spikes/CoreClrHost/Payload/Payload.cs
Normal file
|
|
@ -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]<int, int, int>)&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<string>();
|
||||
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<Record>(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<Record>(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<A1>.Run(); sum += Gen<A2>.Run(); sum += Gen<A3>.Run(); sum += Gen<A4>.Run();
|
||||
sum += Gen<A5>.Run(); sum += Gen<A6>.Run(); sum += Gen<A7>.Run(); sum += Gen<A8>.Run();
|
||||
var d = new Dictionary<A1, List<A2>>(); d[new A1()] = new List<A2> { 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<int> 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<T> where T : new()
|
||||
{
|
||||
public static int Run()
|
||||
{
|
||||
var list = new List<T>();
|
||||
for (int i = 0; i < 16; i++) list.Add(new T());
|
||||
var set = new HashSet<T>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
14
spikes/CoreClrHost/Payload/Payload.csproj
Normal file
14
spikes/CoreClrHost/Payload/Payload.csproj
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AssemblyName>Payload</AssemblyName>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- Contracts must come from the default ALC: don't copy it next to the payload. -->
|
||||
<ProjectReference Include="..\Contracts\Contracts.csproj" Private="false" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
134
spikes/CoreClrHost/Shim/Entry.cs
Normal file
134
spikes/CoreClrHost/Shim/Entry.cs
Normal file
|
|
@ -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]<double*, double> FreeMb;
|
||||
public delegate* unmanaged[Stdcall]<byte*, void> Log;
|
||||
public delegate* unmanaged[Stdcall]<nint, int, int, int> CallBinary;
|
||||
public delegate* unmanaged[Stdcall]<uint> 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<string>();
|
||||
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<string> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
14
spikes/CoreClrHost/Shim/Shim.csproj
Normal file
14
spikes/CoreClrHost/Shim/Shim.csproj
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AssemblyName>Shim</AssemblyName>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Contracts\Contracts.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
216
spikes/CoreClrHost/native/SpikeHost.c
Normal file
216
spikes/CoreClrHost/native/SpikeHost.c
Normal file
|
|
@ -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 <windows.h>
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
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;
|
||||
}
|
||||
19
spikes/CoreClrHost/native/SpikeHostExe.c
Normal file
19
spikes/CoreClrHost/native/SpikeHostExe.c
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
// Console driver: SpikeHostExe.exe [cycles] [mode]. LoadLibrary's SpikeHost.dll the
|
||||
// way an injected loader would and calls SpikeRun.
|
||||
#include <windows.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
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);
|
||||
}
|
||||
53
spikes/CoreClrHost/native/SpikeInject.c
Normal file
53
spikes/CoreClrHost/native/SpikeInject.c
Normal file
|
|
@ -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.exe> <SpikeHost.dll> <cycles,mode,delayMs> <waitSeconds> [acclient args...]
|
||||
#include <windows.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
if (argc < 5) { printf("usage: SpikeInject <acclient.exe> <SpikeHost.dll> <cycles,mode,delayMs> <waitSeconds> [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;
|
||||
}
|
||||
169
spikes/DecalBridge/AcWindow.py
Normal file
169
spikes/DecalBridge/AcWindow.py
Normal file
|
|
@ -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 <pid> <out.png>
|
||||
python AcWindow.py click <pid> <x> <y> client coordinates of the game window
|
||||
python AcWindow.py type <pid> <text>
|
||||
python AcWindow.py key <pid> <vk> 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))
|
||||
157
spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs
Normal file
157
spikes/DecalBridge/BridgeProbePlugin/BridgeProbePlugin.cs
Normal file
|
|
@ -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<BridgeProbePlugin> 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);
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Spike (Decal bridge): a managed plugin for the CoreCLR engine that logs what it receives.
|
||||
dotnet publish -c Release -o C:\Games\RynthCore\Test\plugins-decal\BridgeProbe -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles>
|
||||
<OutputType>Library</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>RynthCore.Plugin.BridgeProbe</AssemblyName>
|
||||
<RootNamespace>RynthCore.Plugin.BridgeProbe</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
65
spikes/DecalBridge/Inject-BridgeRecords.py
Normal file
65
spikes/DecalBridge/Inject-BridgeRecords.py
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
"""Inject-BridgeRecords.py <pid> - 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<pid>.
|
||||
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("<II", m, 0)
|
||||
assert magic == 0x42444352 and version == 2, (hex(magic), version)
|
||||
|
||||
def write(kind, a0=0, a1=0, payload=b""):
|
||||
w, r = struct.unpack_from("<qq", m, OFF_WRITE)
|
||||
rec = 16 + len(payload)
|
||||
rec = (rec + 3) & ~3
|
||||
pad = rec - 16 - len(payload)
|
||||
pos = w % RING
|
||||
assert RING - pos >= rec and RING - (w - r) > rec
|
||||
base = RING_BASE + pos
|
||||
struct.pack_into("<iHHII", m, base, rec, kind, pad, a0, a1)
|
||||
m[base + 16: base + 16 + len(payload)] = payload
|
||||
struct.pack_into("<q", m, OFF_WRITE, w + rec) # publish
|
||||
struct.pack_into("<q", m, OFF_RECORDS, struct.unpack_from("<q", m, OFF_RECORDS)[0] + 1)
|
||||
|
||||
def game_event(ev, body):
|
||||
return struct.pack("<IIII", 0xF7B0, 0x50000001, 7, ev) + body
|
||||
|
||||
write(K_CHAT, 0x03, 0, "[synthetic] You say, \"hello from the bridge test\"\n".encode("utf-16-le"))
|
||||
write(K_CHAT, 0x17, 0, "[synthetic] Welcome to Asheron's Call\n".encode("utf-16-le"))
|
||||
write(K_CHATBAR, 0, 0, "[synthetic] hello world".encode("utf-16-le"))
|
||||
for oid in (0x80000101, 0x80000102, 0x80000103):
|
||||
write(K_CREATE, oid)
|
||||
write(K_CHANGE, 0x80000102, 2)
|
||||
write(K_RELEASE, 0x80000103)
|
||||
# Game events, as Decal's Message.RawData: [F7B0][objectId][sequence][eventType][payload]
|
||||
write(K_SERVER, 0xF7B0, 0, game_event(0x01C7, struct.pack("<I", 0))) # UseDone, no error
|
||||
write(K_SERVER, 0xF7B0, 0, game_event(0x028A, struct.pack("<I", 0x0402))) # WeenieError
|
||||
write(K_SERVER, 0xF7B0, 0, game_event(0x01C0, struct.pack("<If", 0x80000101, 0.5))) # UpdateHealth 50 %
|
||||
# spellId, layer, category, hasSpellSet, powerLevel, startTime, duration (+20), then 32 bytes
|
||||
ench = struct.pack("<HHHHI", 2, 1, 0, 0, 1) + struct.pack("<dd", 0.0, 1800.0) + b"\0" * 32
|
||||
assert len(ench) == 60
|
||||
write(K_SERVER, 0xF7B0, 0, game_event(0x02C2, ench)) # UpdateEnchantment spell 2
|
||||
write(K_SERVER, 0xF7B0, 0, game_event(0x02C3, struct.pack("<HH", 2, 1))) # RemoveEnchantment spell 2
|
||||
name = b"Drudge"
|
||||
s16 = struct.pack("<H", len(name)) + name
|
||||
s16 += b"\0" * (((len(s16) + 3) // 4) * 4 - len(s16))
|
||||
write(K_SERVER, 0xF7B0, 0, game_event(0x01B1, s16 + struct.pack("<IdII", 4, 0.3, 57, 1))) # we hit: 57, crit
|
||||
write(K_SERVER, 0xF745, 0, struct.pack("<II", 0xF745, 0x80000104)) # some other message
|
||||
print("wrote synthetic records; ring now", struct.unpack_from("<qq", m, OFF_WRITE))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
30
spikes/DecalBridge/Measure-HookRace.ps1
Normal file
30
spikes/DecalBridge/Measure-HookRace.ps1
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Measure-HookRace.ps1 - how often Decal's patch ends up on top of ours at the entry points
|
||||
# both of us detour (old coexistence mode, no bridge), and what a hot reload then does.
|
||||
# No server needed (the race is decided in the first seconds). TEST clients only.
|
||||
param([int]$Launches = 6, [string]$Runtime = "C:\Games\RynthCore\Test\rt-decal")
|
||||
$ErrorActionPreference = "Stop"
|
||||
$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
$watch = "$repo\tools\WatchPatch.py"
|
||||
$addrs = @("0x005649F0", "0x004CBF70", "0x005821A0") # AddTextToScroll, gmSalvageUI::OpenSalvagePanel, outgoing chat
|
||||
for ($i = 1; $i -le $Launches; $i++) {
|
||||
& "$PSScriptRoot\Start-DecalTestClient.ps1" -Mode Both -NoBridge -Runtime $Runtime *> $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
|
||||
}
|
||||
37
spikes/DecalBridge/Register-DecalBridge.ps1
Normal file
37
spikes/DecalBridge/Register-DecalBridge.ps1
Normal file
|
|
@ -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
|
||||
59
spikes/DecalBridge/Start-DecalTestClient.ps1
Normal file
59
spikes/DecalBridge/Start-DecalTestClient.ps1
Normal file
|
|
@ -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"
|
||||
168
spikes/DecalBridge/Test-DecalBridgeInWorld.ps1
Normal file
168
spikes/DecalBridge/Test-DecalBridgeInWorld.ps1
Normal file
|
|
@ -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 <folder with RynthCore.DecalBridge.dll>).
|
||||
# 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-<time>\.
|
||||
#
|
||||
# .\spikes\DecalBridge\Test-DecalBridgeInWorld.ps1 -Account Buffi -Server ACEmulator -Character "+Buffi"
|
||||
param(
|
||||
[string]$Account = "Buffi",
|
||||
[string]$Server = "ACEmulator",
|
||||
[string]$Character = "+Buffi",
|
||||
[string]$HostName = "",
|
||||
[int]$Port = 0,
|
||||
[string[]]$Runs = @("B", "C", "D"),
|
||||
[int]$LoginTimeout = 150,
|
||||
[string]$Runtime = "C:\Games\RynthCore\Test\rt-decal",
|
||||
[string]$Settings = "C:\Games\RynthCore\Test\engine-decal.json",
|
||||
[int]$Settle = 30
|
||||
)
|
||||
$ErrorActionPreference = "Stop"
|
||||
$repo = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
$start = "$PSScriptRoot\Start-DecalTestClient.ps1"
|
||||
$diff = "$repo\tools\ProcPatchDiff.py"
|
||||
$out = "C:\Games\RynthCore\Test\decal-bridge\inworld-$(Get-Date -Format yyyyMMdd-HHmmss)"
|
||||
New-Item -ItemType Directory -Force $out | Out-Null
|
||||
$report = "$out\report.txt"
|
||||
function Say([string]$s) { Write-Host $s; Add-Content $report $s }
|
||||
|
||||
$checkPort = if ($Port -gt 0) { $Port } else { 9000 }
|
||||
if (-not (Get-NetUDPEndpoint -ErrorAction SilentlyContinue | Where-Object LocalPort -eq $checkPort)) {
|
||||
throw "Nothing listens on UDP ${checkPort}: start the local ACE server first."
|
||||
}
|
||||
$vs = "HKCU:\Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters"
|
||||
if (-not (Get-ChildItem $vs -ErrorAction SilentlyContinue | Where-Object { (Get-ItemProperty $_.PSPath).Object -eq "RynthCore.DecalBridge.BridgeFilter" })) {
|
||||
throw "The bridge is not registered: run Register-DecalBridge.ps1 first."
|
||||
}
|
||||
|
||||
function Start-One([string]$mode, [string[]]$extra) {
|
||||
$opts = @{ Mode = $mode; Account = $Account; Server = $Server; Character = $Character; HostName = $HostName; Port = $Port; Runtime = $Runtime; Settings = $Settings }
|
||||
foreach ($e in $extra) { $opts[$e] = $true }
|
||||
& $start @opts *> $null
|
||||
return [int]((Get-Content C:\Games\RynthCore\Test\decal-spike-pids.txt -Tail 1).Split(' ')[2])
|
||||
}
|
||||
function Wait-Match([string]$path, [string]$pattern, [int]$seconds) {
|
||||
$t0 = Get-Date
|
||||
while (((Get-Date) - $t0).TotalSeconds -lt $seconds) {
|
||||
if ((Test-Path $path) -and (Select-String -Path $path -Pattern $pattern -Quiet)) { return $true }
|
||||
Start-Sleep 2
|
||||
}
|
||||
return $false
|
||||
}
|
||||
function Stop-One([int]$tp) {
|
||||
Stop-Process -Id $tp -Force -ErrorAction SilentlyContinue
|
||||
Say "stopped $tp; waiting 65 s for the server to drop the session"
|
||||
Start-Sleep 65
|
||||
}
|
||||
function Grab([string]$path, [string]$pattern, [int]$max = 60) {
|
||||
if (Test-Path $path) {
|
||||
Select-String -Path $path -Pattern $pattern | Select-Object -Last $max |
|
||||
ForEach-Object { Say (" " + $_.Line.Substring(0, [Math]::Min(300, $_.Line.Length))) }
|
||||
}
|
||||
}
|
||||
function Send([string]$cmd) {
|
||||
# Through the test client's dispatch file -> AC's main thread -> plugins' OnChatBarEnter.
|
||||
Set-Content "C:\Games\RynthCore\Test\dispatch-decal.txt" "force:$cmd"
|
||||
Start-Sleep 4
|
||||
}
|
||||
function Typed([int]$tp, [string]$cmd) {
|
||||
# Into the test client's own window (PostMessage by pid): Enter, the text, Enter.
|
||||
python "$PSScriptRoot\AcWindow.py" key $tp 0x0D | Out-Null
|
||||
Start-Sleep -Milliseconds 400
|
||||
python "$PSScriptRoot\AcWindow.py" type $tp $cmd | Out-Null
|
||||
python "$PSScriptRoot\AcWindow.py" key $tp 0x0D | Out-Null
|
||||
Start-Sleep 4
|
||||
}
|
||||
function HasModule([int]$tp, [string]$name) {
|
||||
$p = Get-Process -Id $tp -ErrorAction SilentlyContinue
|
||||
return [bool]($p -and ($p.Modules | Where-Object { $_.ModuleName -ieq $name }))
|
||||
}
|
||||
function Reload([int]$tp) {
|
||||
$ev = [System.Threading.EventWaitHandle]::OpenExisting("Local\RynthCore.Engine.RequestReload.p$tp")
|
||||
[void]$ev.Set(); $ev.Dispose()
|
||||
}
|
||||
|
||||
if ($Runs -contains "A") {
|
||||
Say "==== A: Decal only"
|
||||
$tp = Start-One "DecalOnly" @()
|
||||
$blog = "C:\Games\RynthCore\Logs\DecalBridge.$tp.log"
|
||||
Say "pid $tp; in world: $(Wait-Match $blog 'LoginComplete' $LoginTimeout)"
|
||||
Start-Sleep $Settle
|
||||
python $diff $tp --json "$out\A-decal-only.json" *> "$out\A-decal-only.txt"
|
||||
Say "patch diff -> $out\A-decal-only.txt"
|
||||
Grab $blog "." 30
|
||||
Stop-One $tp
|
||||
}
|
||||
|
||||
if ($Runs -contains "B") {
|
||||
Say "==== B: Decal + RynthCore, bridge mode Auto (in-game ImGui: engine.json default)"
|
||||
$tp = Start-One "Both" @()
|
||||
$log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log"
|
||||
Say "pid $tp; in world: $(Wait-Match $log 'starting plugin tick pump|BridgeProbe: OnLoginComplete' $LoginTimeout)"
|
||||
Start-Sleep $Settle
|
||||
python $diff $tp --names $log --json "$out\B-bridge.json" *> "$out\B-bridge.txt"
|
||||
Say " VTank loaded (uTank2.dll): $(HasModule $tp 'uTank2.dll')"
|
||||
Send "/ra cache"
|
||||
Say "-- typed /ra cache (Decal CommandLineText -> bridge -> engine)"
|
||||
Typed $tp "/ra cache"
|
||||
Say "-- /loc through the engine's dispatcher -> bridge -> Decal InvokeChatParser"
|
||||
Send "/loc"
|
||||
for ($i = 1; $i -le 2; $i++) {
|
||||
Say "-- reload $i"
|
||||
Reload $tp
|
||||
Start-Sleep 30
|
||||
Send "/ra cache"
|
||||
}
|
||||
Grab $log "BRIDGE MODE|bridge is up|skipped - bridge|bridge fallback|DecalBridge:|BridgeProbe:|location|unloaded|Reload: complete|EndSceneHook: INSTALLED|tick pump|UseTime \(no EndScene|\[ERR\]" 140
|
||||
$fps = Select-String -Path $log -Pattern "hb #\d+ .*fps=(\d+)" | Select-Object -Last 10 | ForEach-Object { $_.Matches[0].Groups[1].Value }
|
||||
Say " fps (last 10 heartbeats): $($fps -join ' ')"
|
||||
Grab "C:\Games\RynthCore\Logs\DecalBridge.$tp.log" "." 40
|
||||
$p = Get-Process -Id $tp -ErrorAction SilentlyContinue
|
||||
Say " client alive=$([bool]$p) responding=$($p.Responding)"
|
||||
Stop-One $tp
|
||||
}
|
||||
|
||||
if ($Runs -contains "C") {
|
||||
Say "==== C: Decal + RynthCore, DecalBridge=Off (old coexistence mode)"
|
||||
$tp = Start-One "Both" @("NoBridge")
|
||||
$log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log"
|
||||
Say "pid $tp; in world: $(Wait-Match $log 'starting plugin tick pump' $LoginTimeout)"
|
||||
Start-Sleep $Settle
|
||||
python $diff $tp --names $log --json "$out\C-coexistence.json" *> "$out\C-coexistence.txt"
|
||||
Send "/ra cache"
|
||||
Say "-- reload"
|
||||
Reload $tp
|
||||
Start-Sleep 30
|
||||
Send "/ra cache"
|
||||
Grab $log "PATTERN MISS|Decal|unloaded|Reload: complete|tick pump|BridgeProbe:|\[ERR\]" 80
|
||||
$p = Get-Process -Id $tp -ErrorAction SilentlyContinue
|
||||
Say " client alive=$([bool]$p) responding=$($p.Responding)"
|
||||
Stop-One $tp
|
||||
}
|
||||
if ($Runs -contains "D") {
|
||||
Say "==== D: RynthCore only, no Decal (normal hook mode)"
|
||||
$tp = Start-One "EngineOnly" @()
|
||||
$log = "C:\Games\RynthCore\Logs\RynthCore.$tp.log"
|
||||
Say "pid $tp; in world: $(Wait-Match $log 'OnLoginComplete observed' $LoginTimeout)"
|
||||
Start-Sleep $Settle
|
||||
Send "/ra cache"
|
||||
Say "-- reload"
|
||||
Reload $tp
|
||||
Start-Sleep 30
|
||||
Send "/ra cache"
|
||||
# Bridge code must stay silent here: no "DecalBridge:" line, no skipped step.
|
||||
Grab $log "DecalBridge|skipped - bridge|Decal coexistence|Cache:|unloaded|Reload: complete|\[ERR\]" 60
|
||||
$p = Get-Process -Id $tp -ErrorAction SilentlyContinue
|
||||
Say " client alive=$([bool]$p) responding=$($p.Responding)"
|
||||
Stop-One $tp
|
||||
}
|
||||
Say "done: $out"
|
||||
Loading…
Reference in a new issue