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:
parent
d0dfa37ace
commit
9814b65ac5
7 changed files with 517 additions and 0 deletions
|
|
@ -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`.
|
||||
143
src/RynthCore.Engine/Compatibility/LargeAddressAlignmentPatch.cs
Normal file
143
src/RynthCore.Engine/Compatibility/LargeAddressAlignmentPatch.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
107
src/RynthCore.Engine/Compatibility/LargeAddressAlignmentScan.cs
Normal file
107
src/RynthCore.Engine/Compatibility/LargeAddressAlignmentScan.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the large-address alignment fix
|
||||
(src\RynthCore.Engine\Compatibility\LargeAddressAlignmentScan.cs, compiled in): the site scan
|
||||
against the .text of a real acclient.exe read from disk, idempotence once patched, refusal of
|
||||
near-miss byte patterns, and the padding arithmetic above and below 2 GB. Nothing native: no
|
||||
AC process, no engine state.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail); after the usual separator, an AC folder or an acclient.exe.
|
||||
Default: C:\Turbine\Asheron's Call-ryn\acclient.exe.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>LargeAddressAlignmentTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\LargeAddressAlignmentScan.cs" Link="Engine\LargeAddressAlignmentScan.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
154
tools/LargeAddressAlignmentTests/Program.cs
Normal file
154
tools/LargeAddressAlignmentTests/Program.cs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
using System.Buffers.Binary;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace LargeAddressAlignmentTests;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<AlignmentSite> 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<AlignmentSite> 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<AlignmentSite> 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<byte>();
|
||||
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}");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue