diff --git a/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md b/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md
new file mode 100644
index 0000000..7b73590
--- /dev/null
+++ b/Changelog/2026-10-10-release-2026.10.5.23-large-address-alignment-fix.md
@@ -0,0 +1,64 @@
+# RynthCore 2026.10.5.23: fix AC crashes when its memory goes above 2 GB
+
+Released 2026-10-10. Previous release: 2026.10.5.22 (Buffs picker).
+No plugin changes; any RynthAi version works with it.
+
+## What's fixed
+
+- **Random client crashes on long open-world sessions** (hunting nav routes across many
+ landblocks while fighting and looting). Windows reported them as faults in `acclient.exe`
+ (`+0x1271C3`, `+0x12718B`, `+0x126A70`, `+0x139153`) or, when they passed through an engine
+ hook, in `coreclr.dll`.
+
+## Cause
+
+Asheron's Call pads its read and write position to a multiple of 4 bytes when it unpacks dat
+files and network messages. It works the padding out as a *signed* `address % 4`. The client
+runs large-address-aware, so once a session has used enough memory, AC gets buffers above
+2 GB. Their addresses count as negative, the remainder comes out negative, and AC pads 4
+bytes too many. It then reads every later field from the wrong place, writes zeros over real
+data, and reads garbage counts until it runs off the end of the memory region.
+
+A crash dump of kelpie (10 October, 10:32) showed motion table 0x09000009 being unpacked into a
+buffer at 0x80438034. The data on disk was fine, but 21 bytes of the in-memory copy were zeroed.
+Replaying AC's padding code at that address zeroes the same 21 bytes, and reads the modifier
+count as 0xFFFF0000, the value on the crashed stack. At an address below 2 GB the same data
+unpacks cleanly.
+
+## The fix
+
+At startup the engine finds every place in `acclient.exe` that pads this way (190 in the
+retail client) and changes `and reg, 0x80000003` to `and reg, 3` in memory. The remainder is
+then 0 to 3 at any address, so AC pads correctly above 2 GB too. Below 2 GB nothing changes.
+`acclient.exe` on disk is not modified. A site is only changed when it is followed by AC's
+"already aligned" check, so a signed `% 4` of a value that can really be negative is left
+alone (one in the retail client: a 16-bit ring index).
+
+The change stays for the life of the client: a hot reload finds every site already patched
+and logs `0 site(s) patched, 190 already patched`.
+
+To turn it off for diagnostics, add `"EnableLargeAddressAlignmentFix": false` to
+`%APPDATA%\RynthCore\engine.json`. The launcher keeps that setting when it saves.
+
+## Files
+
+- `Compatibility/LargeAddressAlignmentScan.cs` (new): the byte-pattern scan for the padding
+ code.
+- `Compatibility/LargeAddressAlignmentPatch.cs` (new): finds `.text` in the loaded client,
+ rewrites each site's immediate (one byte, page protection restored per site), flushes the
+ instruction cache, and logs the counts.
+- `EntryPoint.cs`: runs the patch in early init, right after the multi-client hooks.
+- `Plugins/EngineSettings.cs`: the `EnableLargeAddressAlignmentFix` kill-switch.
+- `tools/LargeAddressAlignmentTests` (new): offline checks.
+
+## Checks
+
+- `tools/LargeAddressAlignmentTests` (31 checks) pass:
+ - The real `acclient.exe` has 190 sites, including the ones in the crash dumps.
+ - The 16-bit ring index is left alone.
+ - A patched image rescans as fully patched.
+ - Bytes that only look like the pattern are refused.
+ - The padding above and below 2 GB comes out as expected.
+- Release publish of the CoreCLR engine succeeds.
+- Not yet run in game. The engine log should show
+ `Compat: large-address alignment fix - 190 site(s) patched`.
diff --git a/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentPatch.cs b/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentPatch.cs
new file mode 100644
index 0000000..cc2d52c
--- /dev/null
+++ b/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentPatch.cs
@@ -0,0 +1,143 @@
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+namespace RynthCore.Engine.Compatibility;
+
+///
+/// Rewrites acclient's signed "pointer % 4" padding ()
+/// to and r, 3 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.
+///
+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;
+
+ /// Sites rewritten by this engine generation.
+ public static int PatchedCount { get; private set; }
+
+ /// Sites a previous engine generation had already rewritten.
+ 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 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;
+ }
+}
diff --git a/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentScan.cs b/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentScan.cs
new file mode 100644
index 0000000..b1ffa98
--- /dev/null
+++ b/src/RynthCore.Engine/Compatibility/LargeAddressAlignmentScan.cs
@@ -0,0 +1,107 @@
+using System;
+using System.Collections.Generic;
+
+namespace RynthCore.Engine.Compatibility;
+
+/// One signed "pointer % 4" padding site in acclient's code.
+/// VA of the and r32, imm32 instruction.
+/// VA of the immediate's top byte (0x80 stock, 0x00 once patched).
+/// x86 register number (0 = eax ... 7 = edi).
+/// True when the immediate is already 0x00000003.
+internal readonly record struct AlignmentSite(int AndVa, int ImmHighByteVa, int Register, bool AlreadyPatched);
+
+///
+/// Finds AC's 4-byte pack/unpack padding code, which MSVC compiled from a signed
+/// (int)ptr % 4:
+///
+/// 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
+///
+/// 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 (and r, 3) makes the remainder 0..3 at any address.
+/// Requiring the trailing je limits the patch to padding code: a signed modulo of a value
+/// that can really be negative is left alone.
+///
+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;
+
+ /// Scans (the bytes of .text, which starts at
+ /// ) for stock and already-patched padding sites.
+ public static List Find(ReadOnlySpan text, int textVa)
+ {
+ var sites = new List();
+ // 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;
+ }
+
+ /// The immediate's top byte value a site must hold before it is patched.
+ public static byte StockHighByte => StockImmHighByte;
+
+ /// The immediate's top byte value after the patch (and r, 3).
+ public static byte PatchedHighByte => PatchedImmHighByte;
+
+ // jns +5 ; dec r ; or r, 0xFC ; inc r ; [pop r32] ; je rel8|rel32
+ private static bool HasSignedFixupThenJe(ReadOnlySpan 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;
+ }
+}
diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs
index 6c56e0e..3f30b08 100644
--- a/src/RynthCore.Engine/EntryPoint.cs
+++ b/src/RynthCore.Engine/EntryPoint.cs
@@ -216,6 +216,9 @@ public static class EntryPoint
TryPreloadMinHookForEarlyInit();
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
diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs
index 1698fcd..8e91496 100644
--- a/src/RynthCore.Engine/Plugins/EngineSettings.cs
+++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs
@@ -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
}
}
+ /// 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.
+ public static bool EnableLargeAddressAlignmentFix
+ {
+ get
+ {
+ EnsureLoaded();
+ return _enableLargeAddressAlignmentFix;
+ }
+ }
+
/// 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
@@ -382,6 +397,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))
{
diff --git a/tools/LargeAddressAlignmentTests/LargeAddressAlignmentTests.csproj b/tools/LargeAddressAlignmentTests/LargeAddressAlignmentTests.csproj
new file mode 100644
index 0000000..ba581e5
--- /dev/null
+++ b/tools/LargeAddressAlignmentTests/LargeAddressAlignmentTests.csproj
@@ -0,0 +1,25 @@
+
+
+
+
+ Exe
+ net10.0-windows
+ enable
+ enable
+ true
+ LargeAddressAlignmentTests
+
+
+
+
+
+
+
diff --git a/tools/LargeAddressAlignmentTests/Program.cs b/tools/LargeAddressAlignmentTests/Program.cs
new file mode 100644
index 0000000..eec1fa7
--- /dev/null
+++ b/tools/LargeAddressAlignmentTests/Program.cs
@@ -0,0 +1,154 @@
+using System.Buffers.Binary;
+using RynthCore.Engine.Compatibility;
+
+namespace LargeAddressAlignmentTests;
+
+///
+/// The large-address alignment fix, offline: which acclient code the scan picks, that a patched
+/// image rescans as fully patched, that look-alike bytes are refused, and that the patched
+/// remainder pads a cursor above 2 GB the same as below it.
+///
+internal static class Program
+{
+ private static int _checks, _failed;
+
+ private static int Main(string[] args)
+ {
+ string exe = FindExe(args.Length > 0 ? args[0] : @"C:\Turbine\Asheron's Call-ryn");
+ RealClient(exe);
+ SyntheticPatterns();
+ PaddingArithmetic();
+ Console.WriteLine();
+ Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)");
+ return _failed == 0 && _checks > 0 ? 0 : 1;
+ }
+
+ private static string FindExe(string arg) =>
+ File.Exists(arg) ? arg : Path.Combine(arg, "acclient.exe");
+
+ private static void RealClient(string path)
+ {
+ Section("acclient .text from " + path);
+ if (!File.Exists(path))
+ {
+ Check(false, "acclient.exe exists");
+ return;
+ }
+
+ byte[] image = File.ReadAllBytes(path);
+ Check(TryReadText(image, out int textVa, out byte[] text), ".text section read");
+ if (text.Length == 0) return;
+
+ List sites = LargeAddressAlignmentScan.Find(text, textVa);
+ Console.WriteLine($" {sites.Count} site(s), first 0x{sites.FirstOrDefault().AndVa:X8}, last 0x{sites.LastOrDefault().AndVa:X8}");
+ Check(sites.Count == 190, "retail client has 190 padding sites");
+ Check(sites.All(s => !s.AlreadyPatched), "none patched on disk");
+
+ // MotionData::UnPack (kelpie's 0x09000009 corruption) and the setup unpack under the
+ // 0x539153 crashes, plus the one site with a pop before its je.
+ foreach (int va in new[] { 0x005271A6, 0x00534B48, 0x00534C96, 0x00532E78, 0x004FD1B6, 0x006B394E })
+ Check(sites.Any(s => s.AndVa == va), $"0x{va:X8} found");
+ // A 16-bit ring index (movzx, never negative), not cursor padding: no trailing je.
+ Check(sites.All(s => s.AndVa != 0x00547029), "0x00547029 (ring index) left alone");
+
+ foreach (AlignmentSite s in sites)
+ text[s.ImmHighByteVa - textVa] = LargeAddressAlignmentScan.PatchedHighByte;
+ List again = LargeAddressAlignmentScan.Find(text, textVa);
+ Check(again.Count == sites.Count && again.All(s => s.AlreadyPatched), "patched image rescans as all already patched");
+ Check(again.Select(s => s.AndVa).SequenceEqual(sites.Select(s => s.AndVa)), "same sites after patching");
+ }
+
+ private static void SyntheticPatterns()
+ {
+ Section("synthetic byte patterns");
+ // and eax, 0x80000003 ; jns +5 ; dec eax ; or eax, -4 ; inc eax ; je +0x18
+ byte[] eax = { 0x25, 0x03, 0x00, 0x00, 0x80, 0x79, 0x05, 0x48, 0x83, 0xC8, 0xFC, 0x40, 0x74, 0x18 };
+ Check(Scan(eax).Count == 1, "eax short form matches");
+ Check(Scan(eax)[0].ImmHighByteVa == 0x1000 + 4, "immediate high byte located");
+
+ // and ecx, 0x80000003 ; mov [esp+0xC], eax ; jns ; dec ecx ; or ecx, -4 ; inc ecx ; pop ebx ; je
+ byte[] ecxGap = { 0x81, 0xE1, 0x03, 0x00, 0x00, 0x80, 0x89, 0x44, 0x24, 0x0C, 0x79, 0x05, 0x49, 0x83, 0xC9, 0xFC, 0x41, 0x5B, 0x74, 0x10 };
+ Check(Scan(ecxGap).Count == 1 && Scan(ecxGap)[0].Register == 1, "ecx long form with gap and pop matches");
+
+ byte[] noJe = (byte[])eax.Clone();
+ noJe[12] = 0x66;
+ Check(Scan(noJe).Count == 0, "no trailing je: refused");
+
+ byte[] wrongReg = (byte[])eax.Clone();
+ wrongReg[7] = 0x49; // dec ecx after and eax
+ Check(Scan(wrongReg).Count == 0, "fix-up on another register: refused");
+
+ byte[] otherMask = (byte[])eax.Clone();
+ otherMask[1] = 0x07; // % 8
+ Check(Scan(otherMask).Count == 0, "and 0x80000007: refused");
+
+ byte[] patched = (byte[])eax.Clone();
+ patched[4] = 0x00;
+ Check(Scan(patched) is [{ AlreadyPatched: true }], "and eax, 3 reported as already patched");
+ }
+
+ private static void PaddingArithmetic()
+ {
+ Section("padding above and below 2 GB");
+ foreach (uint cursor in new uint[] { 0x2FDC98E1, 0x2FDC98E3, 0x80438035, 0x80438036, 0x8043A4C3, 0xFFFFFFFD })
+ {
+ int stock = StockPad(cursor), fixedPad = FixedPad(cursor);
+ Check((cursor + (uint)fixedPad) % 4 == 0 && fixedPad < 4, $"0x{cursor:X8}: patched pad {fixedPad} aligns");
+ if (cursor < 0x80000000)
+ Check(stock == fixedPad, $"0x{cursor:X8}: below 2 GB the patch changes nothing");
+ else
+ Check(stock == fixedPad + 4, $"0x{cursor:X8}: stock pad {stock} overshoots by 4");
+ }
+ }
+
+ // AC's code: r = and(ptr, 0x80000003) with the sign fix-up, pad = r == 0 ? 0 : 4 - r.
+ private static int StockPad(uint cursor)
+ {
+ int r = (int)cursor % 4;
+ return r == 0 ? 0 : 4 - r;
+ }
+
+ private static int FixedPad(uint cursor)
+ {
+ int r = (int)(cursor & 3);
+ return r == 0 ? 0 : 4 - r;
+ }
+
+ private static List Scan(byte[] code)
+ {
+ byte[] padded = new byte[code.Length + 64];
+ code.CopyTo(padded, 0);
+ return LargeAddressAlignmentScan.Find(padded, 0x1000);
+ }
+
+ private static bool TryReadText(byte[] image, out int textVa, out byte[] text)
+ {
+ textVa = 0;
+ text = Array.Empty();
+ int pe = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C));
+ int sections = BinaryPrimitives.ReadUInt16LittleEndian(image.AsSpan(pe + 6));
+ int optSize = BinaryPrimitives.ReadUInt16LittleEndian(image.AsSpan(pe + 20));
+ int imageBase = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(pe + 24 + 28));
+ for (int i = 0; i < sections; i++)
+ {
+ int s = pe + 24 + optSize + i * 40;
+ if (System.Text.Encoding.ASCII.GetString(image, s, 8).TrimEnd('\0') != ".text") continue;
+ int virtualSize = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 8));
+ int rva = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 12));
+ int rawOffset = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 20));
+ textVa = imageBase + rva;
+ text = image.AsSpan(rawOffset, virtualSize).ToArray();
+ return true;
+ }
+ return false;
+ }
+
+ private static void Section(string name) => Console.WriteLine($"\n== {name}");
+
+ private static void Check(bool ok, string what)
+ {
+ _checks++;
+ if (!ok) _failed++;
+ Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}");
+ }
+}