fix(compat): pad AC unpack buffers correctly above 2 GB (2026.10.5.23)

AC pads its pack/unpack cursor to 4 bytes with a signed "ptr % 4". In the large-address-aware
client a buffer above 0x80000000 gives a negative remainder, AC pads 4 bytes too many, zeroes
live data and parses garbage counts: kelpie's open-world crashes in motion-table and setup
unpacks (dump 2026-10-10 10:32, motion table 0x09000009 at 0x80438034).

Early init now rewrites the 190 padding sites (and r, 0x80000003 followed by the sign fix-up and
the "already aligned" je) to and r, 3 in memory. Kill-switch: engine.json
EnableLargeAddressAlignmentFix=false. Offline checks in tools/LargeAddressAlignmentTests.

Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit fdc7ea71bc)
This commit is contained in:
BlankenshipG 2026-10-10 10:44:31 -04:00
commit 9814b65ac5
7 changed files with 517 additions and 0 deletions

View file

@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Rewrites acclient's signed "pointer % 4" padding (<see cref="LargeAddressAlignmentScan"/>)
/// to <c>and r, 3</c> in memory, so pack/unpack of buffers above 2 GB pads 0..3 bytes like
/// it does below 2 GB. Without it, a large-address-aware client corrupts dat and network
/// unpacks whenever the heap hands AC a buffer above 0x80000000 (long open-world sessions).
///
/// The patch is never undone: an unloading engine generation leaves it in place and the next
/// generation finds every site already patched. acclient.exe on disk is not touched.
/// </summary>
internal static class LargeAddressAlignmentPatch
{
private const uint PAGE_EXECUTE_READWRITE = 0x40;
private const ushort ImageDosSignature = 0x5A4D;
private const uint ImageNtSignature = 0x00004550;
private const int SectionHeaderSize = 40;
private static string _statusMessage = "Not applied yet.";
public static string StatusMessage => _statusMessage;
/// <summary>Sites rewritten by this engine generation.</summary>
public static int PatchedCount { get; private set; }
/// <summary>Sites a previous engine generation had already rewritten.</summary>
public static int AlreadyPatchedCount { get; private set; }
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FlushInstructionCache(IntPtr hProcess, IntPtr lpBaseAddress, UIntPtr dwSize);
public static void Initialize()
{
if (!Plugins.EngineSettings.EnableLargeAddressAlignmentFix)
{
_statusMessage = "Disabled via engine.json (EnableLargeAddressAlignmentFix=false).";
RynthLog.Info($"Compat: large-address alignment fix - {_statusMessage}");
return;
}
IntPtr moduleBase = GetModuleHandleW("acclient.exe");
if (moduleBase == IntPtr.Zero)
moduleBase = GetModuleHandleW(null);
if (moduleBase == IntPtr.Zero || !TryGetTextSection(moduleBase, out int textRva, out int textSize))
{
_statusMessage = "acclient .text section not found.";
RynthLog.Compat($"Compat: large-address alignment fix skipped - {_statusMessage}");
return;
}
IntPtr textBase = IntPtr.Add(moduleBase, textRva);
byte[] text = new byte[textSize];
Marshal.Copy(textBase, text, 0, textSize);
List<AlignmentSite> sites = LargeAddressAlignmentScan.Find(text, textBase.ToInt32());
int patched = 0, already = 0, failed = 0;
foreach (AlignmentSite site in sites)
{
if (site.AlreadyPatched)
{
already++;
continue;
}
if (TryWriteHighByte(new IntPtr(site.ImmHighByteVa)))
patched++;
else
failed++;
}
if (patched > 0)
FlushInstructionCache(GetCurrentProcess(), textBase, (UIntPtr)(uint)textSize);
PatchedCount = patched;
AlreadyPatchedCount = already;
_statusMessage = $"{patched} site(s) patched, {already} already patched, {failed} failed ({sites.Count} found).";
if (sites.Count == 0 || failed > 0)
RynthLog.Compat($"Compat: large-address alignment fix - {_statusMessage}");
else
RynthLog.Info($"Compat: large-address alignment fix - {_statusMessage}");
}
// One byte, protection restored per site: other hooks may hold different protections on
// neighbouring .text pages, so the whole section is never flipped at once.
private static bool TryWriteHighByte(IntPtr address)
{
if (!VirtualProtect(address, (UIntPtr)1u, PAGE_EXECUTE_READWRITE, out uint oldProtect))
{
RynthLog.Compat($"Compat: large-address alignment fix - VirtualProtect 0x{address.ToInt32():X8} failed (error {Marshal.GetLastWin32Error()}).");
return false;
}
try
{
// Re-check the live byte: the scan worked on a copy.
if (Marshal.ReadByte(address) != LargeAddressAlignmentScan.StockHighByte)
return false;
Marshal.WriteByte(address, LargeAddressAlignmentScan.PatchedHighByte);
return true;
}
finally
{
VirtualProtect(address, (UIntPtr)1u, oldProtect, out _);
}
}
private static bool TryGetTextSection(IntPtr moduleBase, out int rva, out int size)
{
rva = 0;
size = 0;
if ((ushort)Marshal.ReadInt16(moduleBase) != ImageDosSignature)
return false;
int peOffset = Marshal.ReadInt32(moduleBase, 0x3C);
IntPtr nt = IntPtr.Add(moduleBase, peOffset);
if (peOffset <= 0 || (uint)Marshal.ReadInt32(nt) != ImageNtSignature)
return false;
int sectionCount = (ushort)Marshal.ReadInt16(nt, 6);
int optionalHeaderSize = (ushort)Marshal.ReadInt16(nt, 20);
IntPtr section = IntPtr.Add(nt, 24 + optionalHeaderSize);
for (int i = 0; i < sectionCount; i++, section = IntPtr.Add(section, SectionHeaderSize))
{
if (Marshal.PtrToStringAnsi(section, 8).TrimEnd('\0') != ".text")
continue;
size = Marshal.ReadInt32(section, 8);
rva = Marshal.ReadInt32(section, 12);
return size > 0 && rva > 0;
}
return false;
}
}

View file

@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>One signed "pointer % 4" padding site in acclient's code.</summary>
/// <param name="AndVa">VA of the <c>and r32, imm32</c> instruction.</param>
/// <param name="ImmHighByteVa">VA of the immediate's top byte (0x80 stock, 0x00 once patched).</param>
/// <param name="Register">x86 register number (0 = eax ... 7 = edi).</param>
/// <param name="AlreadyPatched">True when the immediate is already 0x00000003.</param>
internal readonly record struct AlignmentSite(int AndVa, int ImmHighByteVa, int Register, bool AlreadyPatched);
/// <summary>
/// Finds AC's 4-byte pack/unpack padding code, which MSVC compiled from a signed
/// <c>(int)ptr % 4</c>:
/// <code>
/// and r, 0x80000003 ; keep the sign bit
/// ... (0-12 bytes, no flag writes)
/// jns +5
/// dec r / or r, -4 / inc r ; negative remainder fix-up
/// [pop r32]
/// je skip ; remainder 0: already aligned
/// ... pad 4 - r bytes
/// </code>
/// With large-address-aware acclient a buffer above 2 GB is a negative int, the remainder
/// comes out -3..-1, and AC pads 4 - r = 5..7 bytes instead of 1..3: the cursor runs 4 bytes
/// past the field, zeroes live data and parses garbage counts (kelpie's motion-table crashes).
/// Clearing the immediate's sign bit (<c>and r, 3</c>) makes the remainder 0..3 at any address.
/// Requiring the trailing <c>je</c> limits the patch to padding code: a signed modulo of a value
/// that can really be negative is left alone.
/// </summary>
internal static class LargeAddressAlignmentScan
{
private const byte StockImmHighByte = 0x80;
private const byte PatchedImmHighByte = 0x00;
// and r32, imm32 to the jns: MSVC interleaves at most a few movs; the largest gap in
// the retail client is 5 bytes.
private const int MaxGapBeforeJns = 12;
/// <summary>Scans <paramref name="text"/> (the bytes of .text, which starts at
/// <paramref name="textVa"/>) for stock and already-patched padding sites.</summary>
public static List<AlignmentSite> Find(ReadOnlySpan<byte> text, int textVa)
{
var sites = new List<AlignmentSite>();
// Leave room for the longest match: 6 (and) + 12 (gap) + 7 (fix-up) + 1 (pop) + 2 (je).
int last = text.Length - 28;
for (int i = 0; i < last; i++)
{
int reg, immOffset;
if (text[i] == 0x25)
{
reg = 0; // and eax, imm32 (short form)
immOffset = 1;
}
else if (text[i] == 0x81 && (text[i + 1] & 0xF8) == 0xE0)
{
reg = text[i + 1] & 0x07; // and r32, imm32 (81 /4, mod=11)
immOffset = 2;
}
else
{
continue;
}
if (text[i + immOffset] != 0x03 || text[i + immOffset + 1] != 0x00 || text[i + immOffset + 2] != 0x00)
continue;
byte high = text[i + immOffset + 3];
if (high != StockImmHighByte && high != PatchedImmHighByte)
continue;
int andEnd = i + immOffset + 4;
if (!HasSignedFixupThenJe(text, andEnd, reg))
continue;
sites.Add(new AlignmentSite(textVa + i, textVa + i + immOffset + 3, reg, high == PatchedImmHighByte));
}
return sites;
}
/// <summary>The immediate's top byte value a site must hold before it is patched.</summary>
public static byte StockHighByte => StockImmHighByte;
/// <summary>The immediate's top byte value after the patch (<c>and r, 3</c>).</summary>
public static byte PatchedHighByte => PatchedImmHighByte;
// jns +5 ; dec r ; or r, 0xFC ; inc r ; [pop r32] ; je rel8|rel32
private static bool HasSignedFixupThenJe(ReadOnlySpan<byte> text, int from, int reg)
{
for (int k = from; k <= from + MaxGapBeforeJns; k++)
{
if (text[k] != 0x79 || text[k + 1] != 0x05 ||
text[k + 2] != 0x48 + reg ||
text[k + 3] != 0x83 || text[k + 4] != 0xC8 + reg || text[k + 5] != 0xFC ||
text[k + 6] != 0x40 + reg)
{
continue;
}
int m = k + 7;
if (text[m] >= 0x58 && text[m] <= 0x5F)
m++;
return text[m] == 0x74 || (text[m] == 0x0F && text[m + 1] == 0x84);
}
return false;
}
}

View file

@ -195,6 +195,9 @@ public static class EntryPoint
RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks.");
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
// Before AC's main thread resumes, so no dat or network unpack runs the stock
// signed padding; a hot reload finds every site already patched.
RunInitStep("large-address alignment fix", LargeAddressAlignmentPatch.Initialize);
// DatFileShareHooks force-shares AC's data files at the CreateFile
// layer so we can coexist with Decal-injected clients that other
// launchers (Thwargle etc.) have already opened against the same

View file

@ -21,6 +21,8 @@ internal static class EngineSettings
private static bool _enableImGuiShell = true;
private static bool _enablePlugins = true;
private static bool _enableDatShareHook = true;
// Read-only: Save() leaves it to CopyUnownedFields, so a hand-set false survives launcher saves.
private static bool _enableLargeAddressAlignmentFix = true;
private static bool _enableAvaloniaOverlay = true;
private static bool _enableD3D9Hook = true;
private static bool _enableEngine = true;
@ -82,6 +84,19 @@ internal static class EngineSettings
}
}
/// <summary>When false, LargeAddressAlignmentPatch leaves acclient's signed "pointer % 4"
/// padding code alone (stock AC behaviour, which corrupts unpacks of buffers above 2 GB).
/// Default true. Diagnostic kill-switch only: set "EnableLargeAddressAlignmentFix": false
/// in engine.json by hand.</summary>
public static bool EnableLargeAddressAlignmentFix
{
get
{
EnsureLoaded();
return _enableLargeAddressAlignmentFix;
}
}
/// <summary>When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread,
/// the offscreen overlay window, and all OverlayHost-registered panels never instantiate.
/// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and
@ -390,6 +405,12 @@ internal static class EngineSettings
_enableDatShareHook = datEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableLargeAddressAlignmentFix", out var laaEl) &&
(laaEl.ValueKind == JsonValueKind.True || laaEl.ValueKind == JsonValueKind.False))
{
_enableLargeAddressAlignmentFix = laaEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) &&
(avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False))
{