fix(engine): DAT share hook covers the 2025 client's private CreateFileW slot

The 2025 ACClient.exe (0.0.11.6096) resolves kernel32!CreateFileW on first use
into a private slot (0x00837374) and opens every DAT through it. Since
2026.10.5.61 the hook only patched import tables, so no DAT open was shared:
the first client held the DATs deny-write and every later client failed with
"Can't open the data files".

- LazyImportSlotScanner finds the Layer-for-Unicode stubs by their full byte
  pattern and returns the slots they fill.
- DatFileShareHooks hooks those slots with the same detours and restores them
  on uninstall; an unresolved slot calls the kernel32 export directly.
- tools/DatShareSlotTests: 20 checks, including the real 2025 client.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-15 12:39:09 -04:00
commit bd97e41345
5 changed files with 592 additions and 12 deletions

View file

@ -0,0 +1,65 @@
# 2026.10.5.64 - engine: second client can open the DAT files again (2025 client)
Previous release: 2026.10.5.62.
## Problem
With "Allow multiple clients" on, only the first client started. Every client launched after it
(Silentstorm, SK, ...) showed "Can't open the data files. Check that they exist and that you
have permission to write to them. The program will now exit." about half a second after the
engine loaded.
The 2025 client (`C:\Turbine\Asheron's Call-ryn\ACClient.exe`, 0.0.11.6096) does not import
`kernel32!CreateFileW`. A Layer-for-Unicode style stub at `0x006B8D00` looks it up on first use
and stores it in a private slot at `0x00837374`, and AC opens every DAT file through that slot.
- Up to 2026.10.5.60 the DAT share hook detoured the kernel32 export, so it caught those opens.
The log showed them as `Compat: DAT share - W [filtered]: client_portal.dat ... share=0x1->0x7`.
- 2026.10.5.61 moved the hook to the import tables of `acclient.exe` and `MSVCR70.dll`, to keep
Direct3D and drivers out of it. The private slot is in no import table, so from .61 on no DAT
open was rewritten. The `W [filtered]` lines stopped appearing.
- The first client then opened the DATs read/write and denied writes to everyone else
(`share=0x1`). A second client's own read/write open failed with a sharing violation.
Confirmed on the running client: the three import slots pointed at the engine's detours, but the
private slot `0x00837374` still held `kernel32!CreateFileW`.
## Change
- The DAT share hook also finds acclient.exe's private CreateFileW/CreateFileA slots, then points
them at the same detours. Uninstall restores them like the import slots.
- The slots are found by the stub's full byte pattern, not a fixed address:
- push slot, push the function name, push "kernel32.dll", call the resolver, then
`jmp [slot]` through the same slot;
- the name must stand alone ("MyCreateFileW" does not count);
- the DLL operand must name kernel32.dll.
- If the slot hasn't been resolved yet (it still points at its stub), the detour calls
`kernel32!CreateFileW` directly, because calling the stub would overwrite the slot.
- Direct3D, drivers, the runtime and plugins still call CreateFile without the engine in the way.
- The startup log lists the slot, for example
`Compat: DAT share - hooked acclient.exe!CreateFileW private slot (stub 0x006B8D00) (slot 0x00837374, was 0x76ACEA10).`
With multi-client on, the `W [filtered]: client_portal.dat` lines come back.
## Code
- `src/RynthCore.Engine/Compatibility/LazyImportSlotScanner.cs` (new): reads the section table
of a mapped image and finds the stubs (`ReadSections`, `FindSlots`).
- `src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs`:
- `HookLazySlots` hooks the private slots;
- `HookSlot` builds the A/W detour for import slots and private slots alike;
- the log line names the kind of slot.
- `tools/DatShareSlotTests` (new), 20 checks:
- synthetic stubs;
- near misses that must not match (another jmp slot, another DLL, a longer name, no call, a
slot outside the image, a lone push of the name);
- the real 2025 client: slot `0x00837374`, stub `0x006B8D00`, no CreateFileA slot.
## Tests
- `dotnet run -c Release --project tools\DatShareSlotTests`: 20 checks, 0 failed.
- `dotnet build src\RynthCore.Engine -c Release`: 0 errors, no new warnings.
## Before updating
Close the other clients first. A client already running on .61/.62 holds the DATs deny-write,
so a new client can't start alongside it until it is closed, even on .64.

View file

@ -29,8 +29,13 @@ namespace RynthCore.Engine.Compatibility;
///
/// Why IAT-hook instead of MinHook on the kernel32 export:
/// Only the modules that open AC's data files are hooked: acclient.exe
/// (imports CreateFileA) and its CRT MSVCR70.dll (CreateFileA/W, behind
/// fopen/_wfopen). A kernel32 export hook also caught every other module,
/// (imports CreateFileA), its CRT MSVCR70.dll (CreateFileA/W, behind
/// fopen/_wfopen), and acclient.exe's private CreateFileW slot, which the
/// 2025 client fills on first use and opens every DAT through (it is in no
/// import table; <see cref="LazyImportSlotScanner"/>). Missing that slot let
/// the first client open the DATs read/write, deny-write, and every later
/// client failed with "Can't open the data files" (2026-10-15).
/// A kernel32 export hook also caught every other module,
/// including d3d9.dll and the GPU driver while AC created its device: their
/// CreateFile calls went through managed code, could wait on the runtime
/// while plugins loaded, and on some PCs AC then failed with "Could not
@ -138,11 +143,20 @@ internal static class DatFileShareHooks
return;
}
// acclient.exe opens DATs with its own CreateFileA import; its CRT
// acclient.exe opens DATs with its own CreateFileA import, or (the 2025 client)
// through a private CreateFileW slot its Layer-for-Unicode stub fills; its CRT
// (MSVCR70.dll, statically imported, so loaded by now) does fopen/_wfopen
// opens through its CreateFileA/W imports. Nothing else is hooked.
HookModuleImports("acclient.exe", moduleBase);
HookModuleImports("MSVCR70.dll", GetModuleHandleW("MSVCR70.dll"));
try
{
HookLazySlots(moduleBase);
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: DAT share - private slot scan failed: {ex.Message}");
}
if (_iatHooks.Count == 0)
{
@ -177,20 +191,69 @@ internal static class DatFileShareHooks
return;
}
if (TryPatchIatSlot(moduleBase, "CreateFileW", out IntPtr wSlot, out IntPtr wCurrent))
foreach (string function in new[] { "CreateFileW", "CreateFileA" })
{
CreateFileWDelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(wCurrent);
if (TryPatchIatSlot(moduleBase, function, out IntPtr slot, out IntPtr current))
HookSlot(moduleName, function, "import", slot, current, current);
}
}
/// <summary>
/// Points acclient.exe's private CreateFileA/W slots (filled on first use by a Layer-for-Unicode
/// style stub, see <see cref="LazyImportSlotScanner"/>) at the detours. The 2025 client opens
/// its DAT files through the CreateFileW one; it is not in any import table.
/// </summary>
private static unsafe void HookLazySlots(IntPtr moduleBase)
{
byte* basePtr = (byte*)moduleBase;
int peOffset = *(int*)(basePtr + 0x3C);
uint sizeOfImage = *(uint*)(basePtr + peOffset + 24 + 56);
var image = new ReadOnlySpan<byte>(basePtr, (int)sizeOfImage);
uint imageBase = (uint)moduleBase.ToInt32();
var sections = LazyImportSlotScanner.ReadSections(image);
foreach (string function in new[] { "CreateFileW", "CreateFileA" })
{
foreach (LazyImportSlot lazy in LazyImportSlotScanner.FindSlots(image, imageBase, sections, "kernel32.dll", function))
{
var slot = (IntPtr)(int)lazy.SlotVa;
IntPtr current = Marshal.ReadIntPtr(slot);
// Not resolved yet: the slot still points at its stub inside acclient.exe. Calling
// the stub would overwrite the slot with the real function (dropping the detour),
// so the detour calls the kernel32 export the stub would have resolved.
IntPtr target = current;
if ((uint)current.ToInt32() - imageBase < sizeOfImage)
target = GetProcAddress(GetModuleHandleW("kernel32.dll"), function);
if (target == IntPtr.Zero)
{
RynthLog.Compat($"Compat: DAT share - kernel32!{function} not found; private slot 0x{lazy.SlotVa:X8} left alone.");
continue;
}
HookSlot("acclient.exe", function, $"private slot (stub 0x{lazy.StubVa:X8})", slot, current, target);
}
}
}
/// <summary>
/// Builds the detour for <paramref name="function"/> calling <paramref name="callTarget"/>,
/// and points <paramref name="slot"/> at it. <paramref name="restoreValue"/> is what
/// <see cref="Uninstall"/> writes back.
/// </summary>
private static void HookSlot(string moduleName, string function, string kind, IntPtr slot, IntPtr restoreValue, IntPtr callTarget)
{
if (function == "CreateFileW")
{
CreateFileWDelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(callTarget);
CreateFileWDelegate detour = (name, access, share, security, disposition, flags, template) =>
CreateFileWDetour(original, name, access, share, security, disposition, flags, template);
InstallSlot(moduleName, "CreateFileW", wSlot, wCurrent, detour, Marshal.GetFunctionPointerForDelegate(detour));
InstallSlot(moduleName, function, kind, slot, restoreValue, detour, Marshal.GetFunctionPointerForDelegate(detour));
}
if (TryPatchIatSlot(moduleBase, "CreateFileA", out IntPtr aSlot, out IntPtr aCurrent))
else
{
CreateFileADelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(aCurrent);
CreateFileADelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(callTarget);
CreateFileADelegate detour = (name, access, share, security, disposition, flags, template) =>
CreateFileADetour(original, name, access, share, security, disposition, flags, template);
InstallSlot(moduleName, "CreateFileA", aSlot, aCurrent, detour, Marshal.GetFunctionPointerForDelegate(detour));
InstallSlot(moduleName, function, kind, slot, restoreValue, detour, Marshal.GetFunctionPointerForDelegate(detour));
}
}
@ -198,7 +261,7 @@ internal static class DatFileShareHooks
/// Records the hook (so the delegate stays reachable) before the slot is written: the
/// detour can run on any thread the moment the pointer lands.
/// </summary>
private static void InstallSlot(string moduleName, string function, IntPtr slot, IntPtr original, Delegate detour, IntPtr detourPtr)
private static void InstallSlot(string moduleName, string function, string kind, IntPtr slot, IntPtr original, Delegate detour, IntPtr detourPtr)
{
var hook = new IatHook(moduleName, function, slot, original, detour);
_iatHooks.Add(hook);
@ -206,7 +269,7 @@ internal static class DatFileShareHooks
if (WriteIatPointer(slot, detourPtr))
{
RynthLog.Info($"Compat: DAT share - hooked {moduleName}!{function} import (slot 0x{slot.ToInt32():X8}, was 0x{original.ToInt32():X8}).");
RynthLog.Info($"Compat: DAT share - hooked {moduleName}!{function} {kind} (slot 0x{slot.ToInt32():X8}, was 0x{original.ToInt32():X8}).");
return;
}

View file

@ -0,0 +1,187 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Engine.Compatibility;
/// <summary>One section of a PE image as it is mapped in memory (RVA layout, not file layout).</summary>
internal readonly record struct ImageSection(string Name, uint Rva, uint Size, bool Executable);
/// <summary>A private function-pointer slot filled by a lazy-resolve stub, and the stub that fills it.</summary>
internal readonly record struct LazyImportSlot(uint SlotVa, uint StubVa);
/// <summary>
/// Finds the private pointer slots that Layer-for-Unicode style stubs fill on first use.
///
/// The 2025 ACClient.exe (0.0.11.6096) does not import kernel32!CreateFileW. It resolves it the
/// first time it is called, with a stub of this exact shape, and every call goes through the slot:
/// <code>
/// 68 xx xx xx xx push fallback
/// FF 35 xx xx xx xx push [module handle cache]
/// 68 SS SS SS SS push slot (the pointer the stub fills)
/// 68 NN NN NN NN push "CreateFileW"
/// 68 DD DD DD DD push "kernel32.dll"
/// E8 xx xx xx xx call resolver
/// FF 25 SS SS SS SS jmp [slot]
/// </code>
/// AC opens its DAT files through that slot, so a hook on the import table alone never sees them.
/// The pattern is matched in full (both slot operands must agree, and the DLL operand must name
/// <c>dll</c>), so a stray push of the name string is never taken for a stub.
/// </summary>
internal static class LazyImportSlotScanner
{
private const byte PushImm32 = 0x68;
private const byte CallRel32 = 0xE8;
private const int IMAGE_SCN_CNT_CODE = 0x00000020;
private const int IMAGE_SCN_MEM_EXECUTE = 0x20000000;
// Offsets inside the stub, from the "push name" instruction.
private const int SlotPushBack = 5; // push slot sits right before push name
private const int DllPushAhead = 5; // push dll sits right after it
private const int CallAhead = 10;
private const int JmpAhead = 15; // FF 25 <slot>, after the 5-byte call
private const int StubHeadBytes = 11; // push fallback (5) + push [handle cache] (6), before push slot
/// <summary>
/// Reads the section table of a PE32 image mapped at RVA layout (a module's memory, or a test
/// buffer laid out the same way). Returns an empty list when the headers don't parse.
/// </summary>
public static List<ImageSection> ReadSections(ReadOnlySpan<byte> image)
{
var sections = new List<ImageSection>();
if (image.Length < 0x40)
return sections;
int pe = BitConverter.ToInt32(image.Slice(0x3C, 4));
if (pe <= 0 || pe + 24 > image.Length || BitConverter.ToUInt32(image.Slice(pe, 4)) != 0x00004550) // "PE\0\0"
return sections;
int count = BitConverter.ToUInt16(image.Slice(pe + 6, 2));
int optionalSize = BitConverter.ToUInt16(image.Slice(pe + 20, 2));
int table = pe + 24 + optionalSize;
for (int i = 0; i < count; i++)
{
int h = table + 40 * i;
if (h + 40 > image.Length)
break;
string name = Encoding.ASCII.GetString(image.Slice(h, 8)).TrimEnd('\0');
uint virtualSize = BitConverter.ToUInt32(image.Slice(h + 8, 4));
uint rva = BitConverter.ToUInt32(image.Slice(h + 12, 4));
uint rawSize = BitConverter.ToUInt32(image.Slice(h + 16, 4));
int flags = BitConverter.ToInt32(image.Slice(h + 36, 4));
uint size = virtualSize != 0 ? virtualSize : rawSize;
// Clamp to the buffer: a section can't be scanned past the mapped image.
if (rva >= image.Length)
continue;
size = (uint)Math.Min(size, image.Length - rva);
bool executable = (flags & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE)) != 0;
sections.Add(new ImageSection(name, rva, size, executable));
}
return sections;
}
/// <summary>
/// Every slot a stub fills with <paramref name="dll"/>!<paramref name="function"/>, as absolute
/// addresses (the stubs push absolute addresses, already relocated to <paramref name="imageBase"/>).
/// </summary>
public static List<LazyImportSlot> FindSlots(ReadOnlySpan<byte> image, uint imageBase,
IReadOnlyList<ImageSection> sections, string dll, string function)
{
var found = new List<LazyImportSlot>();
Span<byte> needle = stackalloc byte[5];
foreach (uint nameVa in FindNameStrings(image, imageBase, sections, function))
{
needle[0] = PushImm32;
BitConverter.TryWriteBytes(needle.Slice(1), nameVa);
foreach (ImageSection code in sections)
{
if (!code.Executable)
continue;
ReadOnlySpan<byte> text = image.Slice((int)code.Rva, (int)code.Size);
int from = 0;
while (true)
{
int hit = text.Slice(from).IndexOf(needle);
if (hit < 0)
break;
int at = from + hit;
from = at + 1;
if (TryReadStub(text, at, image, imageBase, dll, out uint slotVa))
found.Add(new LazyImportSlot(slotVa, imageBase + code.Rva + (uint)Math.Max(0, at - SlotPushBack - StubHeadBytes)));
}
}
}
return found;
}
// The NUL-terminated name, not as the tail of a longer identifier (e.g. "MyCreateFileW").
private static IEnumerable<uint> FindNameStrings(ReadOnlySpan<byte> image, uint imageBase,
IReadOnlyList<ImageSection> sections, string function)
{
byte[] name = Encoding.ASCII.GetBytes(function + "\0");
var hits = new List<uint>();
foreach (ImageSection s in sections)
{
if (s.Executable)
continue;
ReadOnlySpan<byte> data = image.Slice((int)s.Rva, (int)s.Size);
int from = 0;
while (true)
{
int hit = data.Slice(from).IndexOf(name);
if (hit < 0)
break;
int at = from + hit;
from = at + 1;
if (at > 0 && IsIdentifierByte(data[at - 1]))
continue;
hits.Add(imageBase + s.Rva + (uint)at);
}
}
return hits;
}
private static bool TryReadStub(ReadOnlySpan<byte> text, int namePush, ReadOnlySpan<byte> image,
uint imageBase, string dll, out uint slotVa)
{
slotVa = 0;
int slotPush = namePush - SlotPushBack;
if (slotPush < 0 || namePush + JmpAhead + 6 > text.Length)
return false;
if (text[slotPush] != PushImm32
|| text[namePush + DllPushAhead] != PushImm32
|| text[namePush + CallAhead] != CallRel32
|| text[namePush + JmpAhead] != 0xFF || text[namePush + JmpAhead + 1] != 0x25)
return false;
uint slot = BitConverter.ToUInt32(text.Slice(slotPush + 1, 4));
uint jmpSlot = BitConverter.ToUInt32(text.Slice(namePush + JmpAhead + 2, 4));
if (slot != jmpSlot || !InImage(slot, 4, imageBase, image.Length))
return false;
uint dllVa = BitConverter.ToUInt32(text.Slice(namePush + DllPushAhead + 1, 4));
if (!string.Equals(ReadAsciiz(image, imageBase, dllVa), dll, StringComparison.OrdinalIgnoreCase))
return false;
slotVa = slot;
return true;
}
private static bool InImage(uint va, int size, uint imageBase, int imageLength) =>
va >= imageBase && (long)va - imageBase + size <= imageLength;
private static string? ReadAsciiz(ReadOnlySpan<byte> image, uint imageBase, uint va)
{
if (!InImage(va, 1, imageBase, image.Length))
return null;
ReadOnlySpan<byte> rest = image.Slice((int)(va - imageBase));
int end = rest.IndexOf((byte)0);
if (end < 0 || end > 260)
return null;
return Encoding.ASCII.GetString(rest.Slice(0, end));
}
private static bool IsIdentifierByte(byte b) =>
b is >= (byte)'A' and <= (byte)'Z' or >= (byte)'a' and <= (byte)'z' or >= (byte)'0' and <= (byte)'9' or (byte)'_';
}

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for src\RynthCore.Engine\Compatibility\LazyImportSlotScanner.cs (2026-10-15):
the 2025 ACClient.exe resolves kernel32!CreateFileW into a private slot on first use and opens
its DAT files through it, so the DAT share hook has to find that slot as well as the import
slots. Synthetic images cover the stub shape and the near misses that must not match; when the
2025 client is on this PC (or RYNTH_ACCLIENT points at one) its real slot is checked too.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>DatShareSlotTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\LazyImportSlotScanner.cs" Link="Engine\LazyImportSlotScanner.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,241 @@
using System.Text;
using RynthCore.Engine.Compatibility;
namespace DatShareSlotTests;
/// <summary>
/// LazyImportSlotScanner: finds the private CreateFileW slot the 2025 ACClient.exe fills on first
/// use. Without it the DAT share hook missed every DAT open and a second client failed with
/// "Can't open the data files" (2026-10-15).
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
// Synthetic image layout: headers, .text at 0x1000 (code), .rdata at 0x2000 (strings + slots).
private const uint ImageBase = 0x00400000;
private const uint TextRva = 0x1000;
private const uint DataRva = 0x2000;
private const int ImageSize = 0x3000;
private const uint DllRva = DataRva + 0x10;
private const uint NameRva = DataRva + 0x40;
private const uint SlotRva = DataRva + 0x100;
private static int Main()
{
ReadsSections();
FindsTheStub();
UnresolvedOrResolvedSlotIsFoundTheSame();
RejectsJmpThroughAnotherSlot();
RejectsAnotherDll();
RejectsNameAsTailOfLongerName();
RejectsBrokenStubShape();
OtherFunctionHasNoSlot();
Real2025Client();
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($"[FAIL] {_case}: {what}");
}
// ── synthetic image ──────────────────────────────────────────────────────
/// <summary>A minimal PE32 header with .text and .rdata, plus "kernel32.dll" and the name.</summary>
private static byte[] NewImage(string functionName = "CreateFileW", string dllName = "kernel32.dll")
{
var img = new byte[ImageSize];
const int pe = 0x80;
BitConverter.TryWriteBytes(img.AsSpan(0x3C), pe);
Encoding.ASCII.GetBytes("PE\0\0").CopyTo(img, pe);
BitConverter.TryWriteBytes(img.AsSpan(pe + 6), (ushort)2); // NumberOfSections
BitConverter.TryWriteBytes(img.AsSpan(pe + 20), (ushort)0xE0); // SizeOfOptionalHeader
BitConverter.TryWriteBytes(img.AsSpan(pe + 24), (ushort)0x10B); // PE32
int table = pe + 24 + 0xE0;
WriteSection(img, table, ".text", TextRva, 0x1000, 0x60000020);
WriteSection(img, table + 40, ".rdata", DataRva, 0x1000, 0x40000040);
Encoding.ASCII.GetBytes(dllName + "\0").CopyTo(img, DllRva);
Encoding.ASCII.GetBytes(functionName + "\0").CopyTo(img, NameRva);
return img;
}
private static void WriteSection(byte[] img, int at, string name, uint rva, uint size, uint flags)
{
Encoding.ASCII.GetBytes(name.PadRight(8, '\0')).CopyTo(img, at);
BitConverter.TryWriteBytes(img.AsSpan(at + 8), size);
BitConverter.TryWriteBytes(img.AsSpan(at + 12), rva);
BitConverter.TryWriteBytes(img.AsSpan(at + 16), size);
BitConverter.TryWriteBytes(img.AsSpan(at + 20), rva);
BitConverter.TryWriteBytes(img.AsSpan(at + 36), flags);
}
/// <summary>Writes the stub at <paramref name="stubRva"/>, the same bytes the 2025 client has.</summary>
private static void WriteStub(byte[] img, uint stubRva, uint slotVa, uint nameVa, uint dllVa, uint jmpSlotVa)
{
var code = new List<byte>();
code.Add(0x68); code.AddRange(BitConverter.GetBytes(0x00405BB3u)); // push fallback
code.Add(0xFF); code.Add(0x35); code.AddRange(BitConverter.GetBytes(0x00906788u)); // push [handle cache]
code.Add(0x68); code.AddRange(BitConverter.GetBytes(slotVa));
code.Add(0x68); code.AddRange(BitConverter.GetBytes(nameVa));
code.Add(0x68); code.AddRange(BitConverter.GetBytes(dllVa));
code.Add(0xE8); code.AddRange(BitConverter.GetBytes(0xFFD4CD41u)); // call resolver
code.Add(0xFF); code.Add(0x25); code.AddRange(BitConverter.GetBytes(jmpSlotVa)); // jmp [slot]
code.CopyTo(img, (int)stubRva);
}
private static List<LazyImportSlot> Scan(byte[] img, string function = "CreateFileW") =>
LazyImportSlotScanner.FindSlots(img, ImageBase, LazyImportSlotScanner.ReadSections(img), "kernel32.dll", function);
// ── cases ────────────────────────────────────────────────────────────────
private static void ReadsSections()
{
_case = "sections";
var s = LazyImportSlotScanner.ReadSections(NewImage());
Check(s.Count == 2, $"two sections, got {s.Count}");
Check(s.Count == 2 && s[0].Name == ".text" && s[0].Executable && s[0].Rva == TextRva, ".text is code at 0x1000");
Check(s.Count == 2 && s[1].Name == ".rdata" && !s[1].Executable && s[1].Rva == DataRva, ".rdata is data at 0x2000");
Check(LazyImportSlotScanner.ReadSections(new byte[0x100]).Count == 0, "no PE signature: nothing");
}
private static void FindsTheStub()
{
_case = "stub";
var img = NewImage();
WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva);
var found = Scan(img);
Check(found.Count == 1, $"one slot, got {found.Count}");
Check(found.Count == 1 && found[0].SlotVa == ImageBase + SlotRva, $"slot 0x{ImageBase + SlotRva:X8}");
Check(found.Count == 1 && found[0].StubVa == ImageBase + TextRva + 0x20, $"stub at 0x{ImageBase + TextRva + 0x20:X8}, got 0x{(found.Count == 1 ? found[0].StubVa : 0):X8}");
}
private static void UnresolvedOrResolvedSlotIsFoundTheSame()
{
_case = "slot contents";
var img = NewImage();
WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva);
BitConverter.TryWriteBytes(img.AsSpan((int)SlotRva), ImageBase + TextRva + 0x20); // still points at its stub
Check(Scan(img).Count == 1, "unresolved (slot points at the stub)");
BitConverter.TryWriteBytes(img.AsSpan((int)SlotRva), 0x76ACEA10u); // resolved to kernel32
Check(Scan(img).Count == 1, "resolved (slot points into kernel32)");
}
private static void RejectsJmpThroughAnotherSlot()
{
_case = "jmp slot";
var img = NewImage();
WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva + 8);
Check(Scan(img).Count == 0, "the jmp must go through the slot the stub fills");
}
private static void RejectsAnotherDll()
{
_case = "dll";
var img = NewImage(dllName: "user32.dll");
WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva);
Check(Scan(img).Count == 0, "a stub resolving from user32.dll is not kernel32's CreateFileW");
var upper = NewImage(dllName: "KERNEL32.DLL");
WriteStub(upper, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva);
Check(Scan(upper).Count == 1, "the DLL name matches in any case");
}
private static void RejectsNameAsTailOfLongerName()
{
_case = "longer name";
var img = NewImage(functionName: "MyCreateFileW");
// Points at the "CreateFileW" tail of "MyCreateFileW".
WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva + 2, ImageBase + DllRva, ImageBase + SlotRva);
Check(Scan(img).Count == 0, "\"MyCreateFileW\" is not CreateFileW");
}
private static void RejectsBrokenStubShape()
{
_case = "shape";
var img = NewImage();
WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva);
img[TextRva + 0x20 + 26] = 0x90; // the call becomes a nop
Check(Scan(img).Count == 0, "no call to the resolver: not a stub");
var outside = NewImage();
WriteStub(outside, TextRva + 0x20, 0x12345678, ImageBase + NameRva, ImageBase + DllRva, 0x12345678);
Check(Scan(outside).Count == 0, "a slot outside the image is never written");
var atStart = NewImage();
WriteStub(atStart, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva);
// A lone push of the name at the very start of .text has no stub around it.
atStart[TextRva] = 0x68;
BitConverter.TryWriteBytes(atStart.AsSpan((int)TextRva + 1), ImageBase + NameRva);
Check(Scan(atStart).Count == 1, "a lone push of the name is skipped, the real stub still found");
}
private static void OtherFunctionHasNoSlot()
{
_case = "other function";
var img = NewImage();
WriteStub(img, TextRva + 0x20, ImageBase + SlotRva, ImageBase + NameRva, ImageBase + DllRva, ImageBase + SlotRva);
Check(Scan(img, "CreateFileA").Count == 0, "only the named function's slot is returned");
}
// ── the real client ──────────────────────────────────────────────────────
private static void Real2025Client()
{
_case = "ACClient.exe 0.0.11.6096";
string? path = Environment.GetEnvironmentVariable("RYNTH_ACCLIENT");
if (string.IsNullOrEmpty(path))
path = @"C:\Turbine\Asheron's Call-ryn\ACClient.exe";
if (!File.Exists(path))
{
Console.WriteLine($" skip: {path} not found (set RYNTH_ACCLIENT to check a client)");
return;
}
byte[] mapped = MapImage(File.ReadAllBytes(path), out uint imageBase);
var sections = LazyImportSlotScanner.ReadSections(mapped);
var w = LazyImportSlotScanner.FindSlots(mapped, imageBase, sections, "kernel32.dll", "CreateFileW");
var a = LazyImportSlotScanner.FindSlots(mapped, imageBase, sections, "kernel32.dll", "CreateFileA");
Console.WriteLine($" {path}: CreateFileW slots {string.Join(", ", w.Select(s => $"0x{s.SlotVa:X8} (stub 0x{s.StubVa:X8})"))}; CreateFileA slots {a.Count}");
// Read from the running client on 2026-10-15: slot 0x00837374 held kernel32!CreateFileW.
if (imageBase == 0x00400000 && FileVersion(path) == "00.00.11.6096")
{
Check(w.Count == 1 && w[0].SlotVa == 0x00837374, "the CreateFileW slot is 0x00837374");
Check(w.Count == 1 && w[0].StubVa == 0x006B8D00, "filled by the stub at 0x006B8D00");
Check(a.Count == 0, "CreateFileA is a normal import, no private slot");
}
}
private static string FileVersion(string path) =>
System.Diagnostics.FileVersionInfo.GetVersionInfo(path).FileVersion ?? "";
/// <summary>Lays a PE file out the way the loader maps it (headers, then each section at its RVA).</summary>
private static byte[] MapImage(byte[] file, out uint imageBase)
{
int pe = BitConverter.ToInt32(file, 0x3C);
int opt = pe + 24;
imageBase = BitConverter.ToUInt32(file, opt + 28);
uint sizeOfImage = BitConverter.ToUInt32(file, opt + 56);
uint sizeOfHeaders = BitConverter.ToUInt32(file, opt + 60);
var img = new byte[sizeOfImage];
Array.Copy(file, img, Math.Min(sizeOfHeaders, (uint)file.Length));
int count = BitConverter.ToUInt16(file, pe + 6);
int table = opt + BitConverter.ToUInt16(file, pe + 20);
for (int i = 0; i < count; i++)
{
int h = table + 40 * i;
uint rva = BitConverter.ToUInt32(file, h + 12);
uint rawSize = BitConverter.ToUInt32(file, h + 16);
uint raw = BitConverter.ToUInt32(file, h + 20);
uint n = Math.Min(rawSize, Math.Min(sizeOfImage - rva, (uint)file.Length - raw));
Array.Copy(file, raw, img, rva, n);
}
return img;
}
}