feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history
Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.
Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
parent
ac0d743e16
commit
4ddbb52eb2
244 changed files with 59710 additions and 3067 deletions
113
tools/HookResolver.Core/Diff/EngineLogParser.cs
Normal file
113
tools/HookResolver.Core/Diff/EngineLogParser.cs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Diff;
|
||||
|
||||
public enum EngineResolutionKind
|
||||
{
|
||||
PatternResolved,
|
||||
FallbackResolved,
|
||||
Unavailable
|
||||
}
|
||||
|
||||
public sealed record EngineResolution(
|
||||
string SymbolId,
|
||||
int? Va,
|
||||
EngineResolutionKind Kind,
|
||||
string Detail);
|
||||
|
||||
public static class EngineLogParser
|
||||
{
|
||||
public const string LogDirectory = @"C:\Games\RynthCore\Logs";
|
||||
public const string DefaultLogPath = LogDirectory + @"\RynthCore.log";
|
||||
|
||||
/// <summary>
|
||||
/// HookResolver lines are engine-origin, so since the per-client log split
|
||||
/// they land in RynthCore.<pid>.log, not the shared RynthCore.log. Pick the
|
||||
/// newest per-PID session log if any exist; otherwise fall back to the shared
|
||||
/// file (and legacy single-file layouts).
|
||||
/// </summary>
|
||||
public static string ResolveDefaultLogPath()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(LogDirectory))
|
||||
{
|
||||
string? newest = null;
|
||||
System.DateTime newestTime = System.DateTime.MinValue;
|
||||
foreach (string f in Directory.GetFiles(LogDirectory, "RynthCore.*.log"))
|
||||
{
|
||||
var t = File.GetLastWriteTime(f);
|
||||
if (t > newestTime) { newestTime = t; newest = f; }
|
||||
}
|
||||
if (newest != null) return newest;
|
||||
}
|
||||
}
|
||||
catch { /* fall through to the shared path */ }
|
||||
return DefaultLogPath;
|
||||
}
|
||||
|
||||
private static readonly Regex Resolved = new(
|
||||
@"HookResolver\[(?<sym>[^\]]+)\]:\s+RESOLVED\s+via\s+(?<detail>\S+)\s+@\s+0x(?<addr>[0-9A-Fa-f]+)",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
private static readonly Regex Fallback = new(
|
||||
@"HookResolver\[(?<sym>[^\]]+)\]:\s+PATTERN MISS.*?VA\s+0x(?<addr>[0-9A-Fa-f]+)",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
private static readonly Regex Unavailable = new(
|
||||
@"HookResolver\[(?<sym>[^\]]+)\]:\s+UNAVAILABLE\b",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
public static async Task<IReadOnlyDictionary<string, EngineResolution>> ParseAsync(
|
||||
string? path = null, CancellationToken ct = default)
|
||||
{
|
||||
path ??= ResolveDefaultLogPath();
|
||||
var result = new Dictionary<string, EngineResolution>();
|
||||
if (!File.Exists(path)) return result;
|
||||
|
||||
await using var stream = new FileStream(
|
||||
path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
using var reader = new StreamReader(stream);
|
||||
|
||||
while (await reader.ReadLineAsync(ct).ConfigureAwait(false) is { } line)
|
||||
{
|
||||
if (TryMatch(Resolved, line, out var sym, out var addr, out var detail))
|
||||
{
|
||||
result[sym] = new EngineResolution(sym, addr, EngineResolutionKind.PatternResolved, detail);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryMatch(Fallback, line, out sym, out addr, out _))
|
||||
{
|
||||
result[sym] = new EngineResolution(sym, addr, EngineResolutionKind.FallbackResolved, "fallback-va");
|
||||
continue;
|
||||
}
|
||||
|
||||
var unavailableMatch = Unavailable.Match(line);
|
||||
if (unavailableMatch.Success)
|
||||
{
|
||||
string s = unavailableMatch.Groups["sym"].Value;
|
||||
result[s] = new EngineResolution(s, null, EngineResolutionKind.Unavailable, "unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static bool TryMatch(Regex rx, string line, out string symbol, out int va, out string detail)
|
||||
{
|
||||
symbol = string.Empty;
|
||||
detail = string.Empty;
|
||||
va = 0;
|
||||
var m = rx.Match(line);
|
||||
if (!m.Success) return false;
|
||||
symbol = m.Groups["sym"].Value;
|
||||
va = int.Parse(m.Groups["addr"].Value, System.Globalization.NumberStyles.HexNumber);
|
||||
if (m.Groups["detail"].Success) detail = m.Groups["detail"].Value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
99
tools/HookResolver.Core/Disassembly/IcedDisassembler.cs
Normal file
99
tools/HookResolver.Core/Disassembly/IcedDisassembler.cs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Iced.Intel;
|
||||
using RynthCore.HookManifest.Scanning;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Disassembly;
|
||||
|
||||
public static class IcedDisassembler
|
||||
{
|
||||
private const int DefaultMaxBytes = 0x1000;
|
||||
private const int DefaultMaxInstructions = 4096;
|
||||
|
||||
public static FunctionSnapshot Snapshot(
|
||||
AcClientImageView image,
|
||||
int rva,
|
||||
int maxBytes = DefaultMaxBytes,
|
||||
int maxInstructions = DefaultMaxInstructions,
|
||||
int maxCallsToCapture = 8)
|
||||
{
|
||||
int textRva = image.TextRva;
|
||||
int textOffset = rva - textRva;
|
||||
if (textOffset < 0 || textOffset >= image.TextBytes.Length)
|
||||
{
|
||||
return new FunctionSnapshot
|
||||
{
|
||||
Rva = rva,
|
||||
Va = image.ImageBase + rva,
|
||||
LengthBytes = 0,
|
||||
InstructionCount = 0,
|
||||
EndsAtReturn = false,
|
||||
PrologueHex = "",
|
||||
Note = "RVA outside .text"
|
||||
};
|
||||
}
|
||||
|
||||
int available = image.TextBytes.Length - textOffset;
|
||||
int scanLen = Math.Min(maxBytes, available);
|
||||
|
||||
byte[] slice = new byte[scanLen];
|
||||
Array.Copy(image.TextBytes, textOffset, slice, 0, scanLen);
|
||||
|
||||
var reader = new ByteArrayCodeReader(slice);
|
||||
var decoder = Decoder.Create(32, reader);
|
||||
decoder.IP = (ulong)(uint)(image.ImageBase + rva);
|
||||
|
||||
int firstVa = image.ImageBase + rva;
|
||||
ulong endIp = (ulong)(uint)(firstVa + scanLen);
|
||||
|
||||
int instructionCount = 0;
|
||||
bool endsAtReturn = false;
|
||||
var calls = new List<CallTarget>();
|
||||
|
||||
while (decoder.IP < endIp && instructionCount < maxInstructions)
|
||||
{
|
||||
decoder.Decode(out var instr);
|
||||
if (instr.IsInvalid)
|
||||
break;
|
||||
|
||||
instructionCount++;
|
||||
|
||||
if (instr.Mnemonic == Mnemonic.Call &&
|
||||
instr.OpCount > 0 &&
|
||||
instr.Op0Kind == OpKind.NearBranch32 &&
|
||||
calls.Count < maxCallsToCapture)
|
||||
{
|
||||
int targetVa = (int)(uint)instr.NearBranch32;
|
||||
int offset = (int)(instr.IP - (ulong)(uint)firstVa);
|
||||
calls.Add(new CallTarget(targetVa, offset));
|
||||
}
|
||||
|
||||
if (instr.FlowControl == FlowControl.Return)
|
||||
{
|
||||
endsAtReturn = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (instr.FlowControl == FlowControl.UnconditionalBranch && instructionCount > 2)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int finalLength = (int)((long)decoder.IP - firstVa);
|
||||
int prologueLen = Math.Min(8, scanLen);
|
||||
string prologueHex = Convert.ToHexString(image.TextBytes.AsSpan(textOffset, prologueLen));
|
||||
|
||||
return new FunctionSnapshot
|
||||
{
|
||||
Rva = rva,
|
||||
Va = firstVa,
|
||||
LengthBytes = finalLength,
|
||||
InstructionCount = instructionCount,
|
||||
EndsAtReturn = endsAtReturn,
|
||||
PrologueHex = prologueHex,
|
||||
CallTargets = calls
|
||||
};
|
||||
}
|
||||
}
|
||||
123
tools/HookResolver.Core/Discovery/StringDiscoveryService.cs
Normal file
123
tools/HookResolver.Core/Discovery/StringDiscoveryService.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.HookManifest.Scanning;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using RynthCore.HookResolver.Core.Disassembly;
|
||||
using RynthCore.HookResolver.Core.Offline;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Discovery;
|
||||
|
||||
public enum StringReferenceMode
|
||||
{
|
||||
PushImm32, // 0x68 + va (printf-style string arg; precise)
|
||||
AnyImm32InText, // any mov/lea/cmp immediate in .text (broad)
|
||||
DataPointer // va appears as a pointer in .rdata table (no function)
|
||||
}
|
||||
|
||||
public sealed record StringDiscoveryRequest(
|
||||
string Literal,
|
||||
byte[] Prologue,
|
||||
int MaxBackward = 0x2000,
|
||||
bool LooseMatch = false,
|
||||
StringReferenceMode ReferenceMode = StringReferenceMode.PushImm32);
|
||||
|
||||
public sealed record StringDiscoveryCandidate(
|
||||
int Va,
|
||||
int Rva,
|
||||
int PushSiteVa,
|
||||
FunctionSnapshot Snapshot);
|
||||
|
||||
public sealed record StringDiscoveryResult(
|
||||
string Literal,
|
||||
int? StringVa,
|
||||
int PushSiteCount,
|
||||
IReadOnlyList<StringDiscoveryCandidate> Candidates,
|
||||
string Summary);
|
||||
|
||||
public static class StringDiscoveryService
|
||||
{
|
||||
public static StringDiscoveryResult Discover(AcClientImage image, StringDiscoveryRequest req)
|
||||
{
|
||||
bool requireNul = !req.LooseMatch;
|
||||
int stringVa = StringRefScanner.FindStringVa(image.View, req.Literal, requireNul);
|
||||
if (stringVa == 0)
|
||||
{
|
||||
string hint = requireNul
|
||||
? " (try Loose match — it may be embedded in a longer string)"
|
||||
: "";
|
||||
return new StringDiscoveryResult(req.Literal, null, 0, [],
|
||||
$"'{req.Literal}' not present in image{hint}.");
|
||||
}
|
||||
|
||||
// DataPointer mode: the string is a table entry, not a code reference.
|
||||
// We can report where the table is but there's no function to walk to.
|
||||
if (req.ReferenceMode == StringReferenceMode.DataPointer)
|
||||
{
|
||||
var ptrs = StringRefScanner.FindDataPointerSites(image.View, stringVa);
|
||||
string msg = ptrs.Count == 0
|
||||
? $"'{req.Literal}' @ 0x{stringVa:X8} — not referenced as a .rdata data pointer either."
|
||||
: $"'{req.Literal}' @ 0x{stringVa:X8} — referenced by {ptrs.Count} data-table " +
|
||||
$"pointer(s): {string.Join(", ", ptrs.ConvertAll(p => $"0x{p:X8}"))}. " +
|
||||
"Table-driven — no function to walk back to (inspect the table layout manually).";
|
||||
return new StringDiscoveryResult(req.Literal, stringVa, ptrs.Count, [], msg);
|
||||
}
|
||||
|
||||
var sites = req.ReferenceMode == StringReferenceMode.AnyImm32InText
|
||||
? StringRefScanner.FindImm32SitesInText(image.View, stringVa)
|
||||
: StringRefScanner.FindPushImm32Sites(image.View, stringVa);
|
||||
|
||||
string refKind = req.ReferenceMode == StringReferenceMode.AnyImm32InText
|
||||
? "imm32" : "push imm32";
|
||||
|
||||
if (sites.Count == 0)
|
||||
{
|
||||
return new StringDiscoveryResult(req.Literal, stringVa, 0, [],
|
||||
$"'{req.Literal}' @ 0x{stringVa:X8} — no `{refKind}` site references it " +
|
||||
"(try AnyImm32 or DataPointer reference mode).");
|
||||
}
|
||||
|
||||
var byFunc = new Dictionary<int, int>();
|
||||
foreach (int site in sites)
|
||||
{
|
||||
int funcOff = StringRefScanner.FindFunctionEntryBefore(
|
||||
image.View, site, req.Prologue, req.MaxBackward);
|
||||
if (funcOff < 0) continue;
|
||||
int funcVa = image.View.TextBaseVa + funcOff;
|
||||
int siteVa = image.View.TextBaseVa + site;
|
||||
if (!byFunc.ContainsKey(funcVa))
|
||||
byFunc[funcVa] = siteVa;
|
||||
}
|
||||
|
||||
var candidates = byFunc
|
||||
.OrderBy(kv => kv.Key)
|
||||
.Select(kv =>
|
||||
{
|
||||
int funcVa = kv.Key;
|
||||
int rva = funcVa - image.View.ImageBase;
|
||||
var snap = IcedDisassembler.Snapshot(image.View, rva);
|
||||
return new StringDiscoveryCandidate(funcVa, rva, kv.Value, snap);
|
||||
})
|
||||
.ToList();
|
||||
|
||||
string summary = candidates.Count switch
|
||||
{
|
||||
0 => $"'{req.Literal}' @ 0x{stringVa:X8} — {sites.Count} {refKind} site(s), " +
|
||||
"but no enclosing prologue match (try a different prologue or larger walk-back).",
|
||||
1 => $"'{req.Literal}' @ 0x{stringVa:X8} — single function candidate via {refKind} (strong anchor).",
|
||||
_ => $"'{req.Literal}' @ 0x{stringVa:X8} — {candidates.Count} candidates via {refKind} " +
|
||||
$"({sites.Count} site(s); disambiguate with the snapshot)."
|
||||
};
|
||||
|
||||
return new StringDiscoveryResult(req.Literal, stringVa, sites.Count, candidates, summary);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<ProloguePreset> Presets { get; } =
|
||||
[
|
||||
new("thiscall (push esi; mov esi, ecx)", [0x56, 0x8B, 0xF1]),
|
||||
new("cdecl (push ebp; mov ebp, esp)", [0x55, 0x8B, 0xEC]),
|
||||
new("combat-action (sub esp,0xC; push regs; call)", [0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8]),
|
||||
new("static (sub esp,N)", [0x83, 0xEC]),
|
||||
];
|
||||
}
|
||||
|
||||
public sealed record ProloguePreset(string Name, byte[] Bytes);
|
||||
69
tools/HookResolver.Core/Discovery/VtableDiscoveryService.cs
Normal file
69
tools/HookResolver.Core/Discovery/VtableDiscoveryService.cs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.HookManifest.Scanning;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using RynthCore.HookResolver.Core.Disassembly;
|
||||
using RynthCore.HookResolver.Core.Offline;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Discovery;
|
||||
|
||||
public sealed record VtableMethodCandidate(
|
||||
int SlotIndex,
|
||||
int Va,
|
||||
int VtableVa,
|
||||
FunctionSnapshot Snapshot);
|
||||
|
||||
public sealed record VtableDiscoveryResult(
|
||||
string ClassName,
|
||||
int? TypeDescriptorVa,
|
||||
int ColCount,
|
||||
int VtableCount,
|
||||
IReadOnlyList<VtableMethodCandidate> Methods,
|
||||
string Summary);
|
||||
|
||||
public static class VtableDiscoveryService
|
||||
{
|
||||
public static VtableDiscoveryResult Discover(AcClientImage image, string className)
|
||||
{
|
||||
var view = image.View;
|
||||
var enumeration = RttiVtableScanner.EnumerateClass(view, className);
|
||||
|
||||
if (enumeration.TypeDescriptorVa is null)
|
||||
{
|
||||
return new VtableDiscoveryResult(className, null, 0, 0, [],
|
||||
$"Type descriptor '.?AV{className}@@' not present in .rdata.");
|
||||
}
|
||||
|
||||
if (enumeration.Vtables.Count == 0)
|
||||
{
|
||||
return new VtableDiscoveryResult(className,
|
||||
enumeration.TypeDescriptorVa, enumeration.ColVas.Count, 0, [],
|
||||
$"Type descriptor found @ 0x{enumeration.TypeDescriptorVa:X8} with " +
|
||||
$"{enumeration.ColVas.Count} COL(s) but no vtable preceded by a COL pointer.");
|
||||
}
|
||||
|
||||
var methods = enumeration.Methods
|
||||
.OrderBy(m => m.SlotIndex)
|
||||
.Select(m =>
|
||||
{
|
||||
int rva = m.Va - view.ImageBase;
|
||||
var snap = IcedDisassembler.Snapshot(view, rva);
|
||||
int vtableVa = enumeration.Vtables[0].VtableVa;
|
||||
return new VtableMethodCandidate(m.SlotIndex, m.Va, vtableVa, snap);
|
||||
})
|
||||
.ToList();
|
||||
|
||||
string summary =
|
||||
$"'{className}' → TypeDesc 0x{enumeration.TypeDescriptorVa:X8}, " +
|
||||
$"{enumeration.ColVas.Count} COL(s), {enumeration.Vtables.Count} vtable(s), " +
|
||||
$"{methods.Count} unique method(s).";
|
||||
|
||||
return new VtableDiscoveryResult(
|
||||
className,
|
||||
enumeration.TypeDescriptorVa,
|
||||
enumeration.ColVas.Count,
|
||||
enumeration.Vtables.Count,
|
||||
methods,
|
||||
summary);
|
||||
}
|
||||
}
|
||||
6
tools/HookResolver.Core/Offline/AcClientImage.cs
Normal file
6
tools/HookResolver.Core/Offline/AcClientImage.cs
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
using RynthCore.HookManifest.Scanning;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Offline;
|
||||
|
||||
public sealed record AcClientImage(AcClientImageView View, ManifestInput Input);
|
||||
147
tools/HookResolver.Core/Offline/AcClientImageLoader.cs
Normal file
147
tools/HookResolver.Core/Offline/AcClientImageLoader.cs
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using RynthCore.HookManifest.Scanning;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Offline;
|
||||
|
||||
public static class AcClientImageLoader
|
||||
{
|
||||
private const ushort DosSignature = 0x5A4D;
|
||||
private const uint NtSignature = 0x00004550;
|
||||
private const int DosPeOffset = 0x3C;
|
||||
private const int FileHeaderMachineOffset = 0x0;
|
||||
private const int FileHeaderNumSectionsOffset = 0x2;
|
||||
private const int FileHeaderOptionalSizeOffset = 0x10;
|
||||
private const int OptionalHeaderImageBaseOffset = 0x1C;
|
||||
private const int OptionalHeaderSizeOfImageOffset = 0x38;
|
||||
private const int SectionHeaderSize = 0x28;
|
||||
private const int SectionNameLength = 8;
|
||||
|
||||
public static async Task<AcClientImage> LoadAsync(string path, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
throw new ArgumentException("Path is required.", nameof(path));
|
||||
if (!File.Exists(path))
|
||||
throw new FileNotFoundException("acclient.exe not found.", path);
|
||||
|
||||
byte[] fileBytes = await File.ReadAllBytesAsync(path, ct).ConfigureAwait(false);
|
||||
if (fileBytes.Length < 0x200)
|
||||
throw new InvalidDataException("File is too small to be a valid PE.");
|
||||
|
||||
if (BitConverter.ToUInt16(fileBytes, 0) != DosSignature)
|
||||
throw new InvalidDataException("Missing MZ DOS signature.");
|
||||
|
||||
int peOffset = BitConverter.ToInt32(fileBytes, DosPeOffset);
|
||||
if (peOffset <= 0 || peOffset + 0x18 > fileBytes.Length)
|
||||
throw new InvalidDataException("Invalid PE header offset.");
|
||||
|
||||
if (BitConverter.ToUInt32(fileBytes, peOffset) != NtSignature)
|
||||
throw new InvalidDataException("Missing PE NT signature.");
|
||||
|
||||
int fileHeaderOffset = peOffset + 4;
|
||||
ushort machine = BitConverter.ToUInt16(fileBytes, fileHeaderOffset + FileHeaderMachineOffset);
|
||||
ushort numSections = BitConverter.ToUInt16(fileBytes, fileHeaderOffset + FileHeaderNumSectionsOffset);
|
||||
ushort optionalHeaderSize = BitConverter.ToUInt16(fileBytes, fileHeaderOffset + FileHeaderOptionalSizeOffset);
|
||||
|
||||
int optionalHeaderOffset = fileHeaderOffset + 0x14; // FILE_HEADER is 20 bytes
|
||||
int imageBase = BitConverter.ToInt32(fileBytes, optionalHeaderOffset + OptionalHeaderImageBaseOffset);
|
||||
int imageSize = BitConverter.ToInt32(fileBytes, optionalHeaderOffset + OptionalHeaderSizeOfImageOffset);
|
||||
|
||||
int sectionTableOffset = optionalHeaderOffset + optionalHeaderSize;
|
||||
if (!TryFindSection(fileBytes, sectionTableOffset, numSections, ".text",
|
||||
out int textRva, out int textRawOffset, out int textRawSize, out int textVirtualSize))
|
||||
{
|
||||
throw new InvalidDataException(".text section not found.");
|
||||
}
|
||||
|
||||
int textBytesLength = Math.Max(textVirtualSize, textRawSize);
|
||||
textBytesLength = Math.Min(textBytesLength, fileBytes.Length - textRawOffset);
|
||||
if (textBytesLength <= 0)
|
||||
throw new InvalidDataException(".text section is empty or truncated.");
|
||||
|
||||
byte[] textBytes = new byte[textBytesLength];
|
||||
Array.Copy(fileBytes, textRawOffset, textBytes, 0, Math.Min(textRawSize, textBytesLength));
|
||||
|
||||
int rdataRva = 0;
|
||||
byte[] rdataBytes = [];
|
||||
if (TryFindSection(fileBytes, sectionTableOffset, numSections, ".rdata",
|
||||
out int rRva, out int rRawOffset, out int rRawSize, out int rVirtualSize))
|
||||
{
|
||||
int rdataLen = Math.Max(rVirtualSize, rRawSize);
|
||||
rdataLen = Math.Min(rdataLen, fileBytes.Length - rRawOffset);
|
||||
if (rdataLen > 0)
|
||||
{
|
||||
rdataRva = rRva;
|
||||
rdataBytes = new byte[rdataLen];
|
||||
Array.Copy(fileBytes, rRawOffset, rdataBytes, 0, Math.Min(rRawSize, rdataLen));
|
||||
}
|
||||
}
|
||||
|
||||
string sha256 = ComputeSha256(fileBytes);
|
||||
|
||||
var view = new AcClientImageView(imageBase, imageSize, textRva, textBytes, rdataRva, rdataBytes);
|
||||
var input = new ManifestInput
|
||||
{
|
||||
Path = path,
|
||||
FileSizeBytes = fileBytes.Length,
|
||||
Sha256 = sha256,
|
||||
ImageBase = imageBase,
|
||||
ImageSizeRva = imageSize,
|
||||
TextRva = textRva,
|
||||
Machine = MachineName(machine)
|
||||
};
|
||||
|
||||
return new AcClientImage(view, input);
|
||||
}
|
||||
|
||||
private static bool TryFindSection(
|
||||
byte[] fileBytes, int sectionTableOffset, int numSections, string name,
|
||||
out int rva, out int rawOffset, out int rawSize, out int virtualSize)
|
||||
{
|
||||
rva = rawOffset = rawSize = virtualSize = 0;
|
||||
for (int i = 0; i < numSections; i++)
|
||||
{
|
||||
int sectionOffset = sectionTableOffset + i * SectionHeaderSize;
|
||||
if (sectionOffset + SectionHeaderSize > fileBytes.Length)
|
||||
return false;
|
||||
|
||||
string sectionName = ReadAsciiNullPadded(fileBytes, sectionOffset, SectionNameLength);
|
||||
if (!string.Equals(sectionName, name, StringComparison.Ordinal))
|
||||
continue;
|
||||
|
||||
virtualSize = BitConverter.ToInt32(fileBytes, sectionOffset + 0x08);
|
||||
rva = BitConverter.ToInt32(fileBytes, sectionOffset + 0x0C);
|
||||
rawSize = BitConverter.ToInt32(fileBytes, sectionOffset + 0x10);
|
||||
rawOffset = BitConverter.ToInt32(fileBytes, sectionOffset + 0x14);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string ReadAsciiNullPadded(byte[] data, int offset, int length)
|
||||
{
|
||||
int end = offset;
|
||||
while (end < offset + length && data[end] != 0) end++;
|
||||
return System.Text.Encoding.ASCII.GetString(data, offset, end - offset);
|
||||
}
|
||||
|
||||
private static string ComputeSha256(byte[] data)
|
||||
{
|
||||
byte[] hash = SHA256.HashData(data);
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
|
||||
private static string MachineName(ushort machine) => machine switch
|
||||
{
|
||||
0x014C => "x86",
|
||||
0x8664 => "x64",
|
||||
0x01C4 => "arm",
|
||||
0xAA64 => "arm64",
|
||||
_ => $"unknown(0x{machine:X4})"
|
||||
};
|
||||
}
|
||||
170
tools/HookResolver.Core/Resolution/HookResolveOrchestrator.cs
Normal file
170
tools/HookResolver.Core/Resolution/HookResolveOrchestrator.cs
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using RynthCore.HookManifest.Scanning;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using RynthCore.HookResolver.Core.Disassembly;
|
||||
using RynthCore.HookResolver.Core.Offline;
|
||||
using RynthCore.HookResolver.Core.Symbols;
|
||||
using RynthCore.HookResolver.Core.Validation;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Resolution;
|
||||
|
||||
public static class HookResolveOrchestrator
|
||||
{
|
||||
public static async IAsyncEnumerable<HookManifestEntry> ResolveAsync(
|
||||
AcClientImage image,
|
||||
IReadOnlyList<HookSymbol> symbols,
|
||||
[EnumeratorCancellation] CancellationToken ct = default)
|
||||
{
|
||||
foreach (var symbol in symbols)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var entry = ResolveSymbol(image.View, symbol);
|
||||
await Task.Yield();
|
||||
yield return entry;
|
||||
}
|
||||
}
|
||||
|
||||
private static HookManifestEntry ResolveSymbol(AcClientImageView image, HookSymbol symbol)
|
||||
{
|
||||
var candidates = FindCandidates(image, symbol).ToList();
|
||||
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
return new HookManifestEntry
|
||||
{
|
||||
SymbolId = symbol.Id,
|
||||
Status = ResolutionStatus.Unresolved,
|
||||
PatternId = symbol.PatternId,
|
||||
MatchedCandidates = 0,
|
||||
Reason = "no pattern matches in .text"
|
||||
};
|
||||
}
|
||||
|
||||
var passingCandidates = new List<(int Rva, int Va, List<ValidationRecord> Validations, List<ValidationRecord> Warnings)>();
|
||||
var rejectedCandidates = new List<(int Rva, int Va, List<ValidationRecord> Validations)>();
|
||||
|
||||
foreach (var (rva, va) in candidates)
|
||||
{
|
||||
var ctx = new ValidationContext(image, rva, va, symbol);
|
||||
var validations = new List<ValidationRecord>();
|
||||
var warnings = new List<ValidationRecord>();
|
||||
bool requiredPassed = true;
|
||||
|
||||
foreach (var rule in symbol.RequiredRules)
|
||||
{
|
||||
var outcome = rule.Evaluate(ctx);
|
||||
validations.Add(new ValidationRecord(outcome.RuleId, outcome.Passed, outcome.Detail));
|
||||
if (!outcome.Passed) requiredPassed = false;
|
||||
}
|
||||
|
||||
foreach (var rule in symbol.AdvisoryRules)
|
||||
{
|
||||
var outcome = rule.Evaluate(ctx);
|
||||
var rec = new ValidationRecord(outcome.RuleId, outcome.Passed, outcome.Detail);
|
||||
validations.Add(rec);
|
||||
if (!outcome.Passed) warnings.Add(rec);
|
||||
}
|
||||
|
||||
if (requiredPassed)
|
||||
passingCandidates.Add((rva, va, validations, warnings));
|
||||
else
|
||||
rejectedCandidates.Add((rva, va, validations));
|
||||
}
|
||||
|
||||
if (passingCandidates.Count == 1)
|
||||
{
|
||||
var c = passingCandidates[0];
|
||||
return new HookManifestEntry
|
||||
{
|
||||
SymbolId = symbol.Id,
|
||||
Status = ResolutionStatus.Resolved,
|
||||
Address = new ResolvedAddress(c.Va, c.Rva),
|
||||
PatternId = symbol.PatternId,
|
||||
MatchedCandidates = candidates.Count,
|
||||
ChosenCandidateReason = candidates.Count == 1 ? "single-match" : "single-passing",
|
||||
Validations = c.Validations,
|
||||
Warnings = c.Warnings,
|
||||
Snapshot = IcedDisassembler.Snapshot(image, c.Rva)
|
||||
};
|
||||
}
|
||||
|
||||
if (passingCandidates.Count > 1)
|
||||
{
|
||||
if (symbol.FallbackVa is { } fb)
|
||||
{
|
||||
var chosen = passingCandidates.OrderBy(c => Math.Abs(c.Va - fb)).First();
|
||||
return new HookManifestEntry
|
||||
{
|
||||
SymbolId = symbol.Id,
|
||||
Status = ResolutionStatus.Resolved,
|
||||
Address = new ResolvedAddress(chosen.Va, chosen.Rva),
|
||||
PatternId = symbol.PatternId,
|
||||
MatchedCandidates = candidates.Count,
|
||||
ChosenCandidateReason = $"multi-match nearest-fallback (of {passingCandidates.Count} passing)",
|
||||
Validations = chosen.Validations,
|
||||
Warnings = chosen.Warnings,
|
||||
Snapshot = IcedDisassembler.Snapshot(image, chosen.Rva)
|
||||
};
|
||||
}
|
||||
|
||||
var first = passingCandidates[0];
|
||||
return new HookManifestEntry
|
||||
{
|
||||
SymbolId = symbol.Id,
|
||||
Status = ResolutionStatus.Ambiguous,
|
||||
Address = new ResolvedAddress(first.Va, first.Rva),
|
||||
PatternId = symbol.PatternId,
|
||||
MatchedCandidates = candidates.Count,
|
||||
ChosenCandidateReason = "first-passing (no fallback)",
|
||||
Validations = first.Validations,
|
||||
Warnings = first.Warnings,
|
||||
Reason = $"{passingCandidates.Count} candidates passed; no fallback VA to disambiguate",
|
||||
Snapshot = IcedDisassembler.Snapshot(image, first.Rva)
|
||||
};
|
||||
}
|
||||
|
||||
var firstReject = rejectedCandidates[0];
|
||||
return new HookManifestEntry
|
||||
{
|
||||
SymbolId = symbol.Id,
|
||||
Status = ResolutionStatus.Unresolved,
|
||||
PatternId = symbol.PatternId,
|
||||
MatchedCandidates = candidates.Count,
|
||||
Validations = firstReject.Validations,
|
||||
Reason = $"{candidates.Count} pattern hits, none passed required rules"
|
||||
};
|
||||
}
|
||||
|
||||
private static IEnumerable<(int Rva, int Va)> FindCandidates(AcClientImageView image, HookSymbol symbol)
|
||||
{
|
||||
byte[] text = image.TextBytes;
|
||||
int start = 0;
|
||||
while (start < text.Length)
|
||||
{
|
||||
int hit = PatternScanner.FindPatternInRegion(text, symbol.Pattern, start, text.Length);
|
||||
if (hit < 0) yield break;
|
||||
|
||||
int resolvedOff = hit;
|
||||
if (symbol.WalkBack is { } walk)
|
||||
{
|
||||
int prologueOff = PatternScanner.FindPrologueBefore(text, hit, walk.Prologue, walk.MaxDistance);
|
||||
if (prologueOff < 0)
|
||||
{
|
||||
start = hit + 1;
|
||||
continue;
|
||||
}
|
||||
resolvedOff = prologueOff;
|
||||
}
|
||||
|
||||
int rva = image.TextRva + resolvedOff;
|
||||
int va = image.ImageBase + rva;
|
||||
yield return (rva, va);
|
||||
start = hit + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
46
tools/HookResolver.Core/Resolution/ManifestBuilder.cs
Normal file
46
tools/HookResolver.Core/Resolution/ManifestBuilder.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using Manifest = RynthCore.HookManifest.Schema.HookManifest;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Resolution;
|
||||
|
||||
public static class ManifestBuilder
|
||||
{
|
||||
public const string GeneratorName = "RynthCore.HookResolver 0.1.0";
|
||||
|
||||
public static Manifest Compose(
|
||||
ManifestInput input,
|
||||
IEnumerable<HookManifestEntry> entries,
|
||||
IReadOnlyDictionary<string, string>? labels = null)
|
||||
{
|
||||
var dict = new Dictionary<string, HookManifestEntry>();
|
||||
foreach (var e in entries)
|
||||
dict[e.SymbolId] = e;
|
||||
|
||||
return new Manifest
|
||||
{
|
||||
Generator = GeneratorName,
|
||||
GeneratedAtUtc = DateTime.UtcNow,
|
||||
Input = input,
|
||||
Labels = labels ?? new Dictionary<string, string>(),
|
||||
Symbols = dict
|
||||
};
|
||||
}
|
||||
|
||||
public static async Task WriteAsync(Manifest manifest, string path, CancellationToken ct = default)
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir))
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(
|
||||
manifest, HookManifestJsonContext.Default.HookManifest);
|
||||
|
||||
await File.WriteAllBytesAsync(path, bytes, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
21
tools/HookResolver.Core/RynthCore.HookResolver.Core.csproj
Normal file
21
tools/HookResolver.Core/RynthCore.HookResolver.Core.csproj
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>RynthCore.HookResolver.Core</RootNamespace>
|
||||
<AssemblyName>RynthCore.HookResolver.Core</AssemblyName>
|
||||
<LangVersion>latest</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Iced" Version="1.21.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\RynthCore.HookManifest\RynthCore.HookManifest.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
554
tools/HookResolver.Core/Symbols/AllSymbols.cs
Normal file
554
tools/HookResolver.Core/Symbols/AllSymbols.cs
Normal file
|
|
@ -0,0 +1,554 @@
|
|||
using System.Collections.Generic;
|
||||
using RynthCore.HookResolver.Core.Validation;
|
||||
using RynthCore.HookResolver.Core.Validation.Rules;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Symbols;
|
||||
|
||||
public static class AllSymbols
|
||||
{
|
||||
// Shared prologue used by all CombatActionHooks dispatch wrappers
|
||||
// (small functions: sub esp,0xC; push ebx; push esi; push edi; call rel32).
|
||||
private static readonly byte[] CombatActionPrologue = [0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8];
|
||||
|
||||
// The three helper functions every CombatActionHooks wrapper CALLs,
|
||||
// verified empirically across all 7 siblings (incl. CastSpell @0x006A3E60)
|
||||
// in the SHA-keyed manifest. A candidate that doesn't call all three is
|
||||
// NOT a combat-action wrapper — this is what rejects a bad walk-back.
|
||||
private static readonly int[] CombatDispatchers = [0x005473A0, 0x005DF0F0, 0x006B4010];
|
||||
|
||||
private static IReadOnlyList<IValidationRule> CombatCallCheck { get; } =
|
||||
[new CallTargetsRule(CombatDispatchers, minMatches: 3)];
|
||||
|
||||
public static IReadOnlyList<HookSymbol> Default { get; } =
|
||||
[
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "MultiClientHooks.Client::IsAlreadyRunning",
|
||||
PatternId = "iar-v1",
|
||||
FallbackVa = 0x004122A0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x56, 0x68, 0x30, 0x58, 0x79, 0x00, 0x6A, 0x01,
|
||||
0x6A, 0x00, 0x6A, 0x00, 0x8B, 0xF1, 0xFF, 0x15
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "MultiClientHooks.CLBlockAllocator::OpenDataFile",
|
||||
PatternId = "openDataFile-v1",
|
||||
FallbackVa = 0x00675920,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x10, 0x53, 0x55, 0x8B, 0x6C,
|
||||
0x24, 0x0C, 0x56, 0x57, 0x8B, 0xF1, 0x50, 0x8B,
|
||||
0xC8, 0x8B, 0x44, 0x24, 0x20, 0x6A, 0x00, 0x80,
|
||||
0xE1, 0x02, 0x80, 0xF9, 0x02, 0x50, 0x6A, 0x00
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "BusyCountHooks.IncrementBusyCount",
|
||||
PatternId = "busy-inc-v1",
|
||||
FallbackVa = 0x00565610,
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern =
|
||||
[
|
||||
0x8B, 0x51, 0x14, 0x42, 0x8B, 0xC2, 0x83, 0xF8,
|
||||
0x01, 0x89, 0x51, 0x14, 0x75, 0x05, 0xE9, null,
|
||||
null, null, null, 0xC3
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "BusyCountHooks.DecrementBusyCount",
|
||||
PatternId = "busy-dec-v1",
|
||||
FallbackVa = 0x00565630,
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern =
|
||||
[
|
||||
0xFF, 0x49, 0x14, 0x75, 0x05, 0xE9, null, null,
|
||||
null, null, 0xC3
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "BusyCountHooks.UpdateCursorState",
|
||||
PatternId = "busy-cursor-v1",
|
||||
FallbackVa = 0x005653D0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x83, 0xEC, 0x08, 0x53, 0x55, 0x56, 0x57, 0x89,
|
||||
0x4C, 0x24, 0x10, 0xE8, null, null, null, null,
|
||||
0x85, 0xC0, 0x0F, 0x95, 0xC3, 0x33, 0xC0, 0x84, 0xDB
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "CombatModeHooks.SetCombatMode",
|
||||
PatternId = "combatmode-v1",
|
||||
FallbackVa = 0x0056CB80,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x51, 0x53, 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x1C,
|
||||
0x57, 0x8B, 0x7C, 0x24, 0x14, 0x3B, 0xF8, 0x8B,
|
||||
0xD8, 0x0F, 0x84, 0xEA, 0x01, 0x00, 0x00, 0x8A,
|
||||
0x44, 0x24, 0x18, 0x84, 0xC0
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "LogoutLifecycle.ExecuteLogOff",
|
||||
PatternId = "logout-exec-v1",
|
||||
FallbackVa = 0x0055E4A0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x53, 0x56, 0x8B, 0xF1, 0x33, 0xDB, 0x88, 0x9E,
|
||||
0x13, 0x02, 0x00, 0x00, 0x88, 0x9E, 0x21, 0x02,
|
||||
0x00, 0x00, 0x8B, 0x0D, null, null, null, null,
|
||||
0xA1, null, null, null, null, 0x89, 0x86, 0x00,
|
||||
0x02, 0x00, 0x00
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "LogoutLifecycle.RecvNotice_Logoff",
|
||||
PatternId = "logout-recv-v1",
|
||||
FallbackVa = 0x004ECBA0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0x56, 0x8B,
|
||||
0xF1, 0xB0, 0x01, 0x8D, 0x4C, 0x24, 0x04, 0x88,
|
||||
0x46, 0x2D, 0x88, 0x46, 0x2E, 0xE8, null, null,
|
||||
null, null, 0xA1, null, null, null, null, 0x68,
|
||||
0x01, 0x00, 0x00, 0x10
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "DoMotionHooks.DoMotion",
|
||||
PatternId = "domotion-v1",
|
||||
FallbackVa = 0x00510AF0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x83, 0xEC, 0x64, 0x56, 0x8B, 0xF1, 0x8B, 0x8E,
|
||||
0xC4, 0x00, 0x00, 0x00, 0x33, 0xC0, 0x3B, 0xC8,
|
||||
0xC7, 0x86, 0xCC, 0x00, 0x00, 0x00, 0x01, 0x00,
|
||||
0x00, 0x00, 0x75, 0x0C
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "AccountHooks.SendNotice_WorldName",
|
||||
PatternId = "account-worldname-v1",
|
||||
FallbackVa = 0x00693A60,
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern =
|
||||
[
|
||||
0xE8, null, null, null, null, 0x8B, 0x10, 0x68,
|
||||
0xA2, 0x86, 0x01, 0x00, 0x8B, 0xC8, 0xFF, 0x52,
|
||||
0x10, 0x85, 0xC0, 0x74, 0x22, 0x56, 0x8B, 0x70, 0x04
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "PowerbarHooks.UIElement::SetVisible",
|
||||
PatternId = "uielement-setvisible-v1",
|
||||
FallbackVa = 0x00462390,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x51, 0x53, 0x56, 0x57, 0x8B, 0x3D, null, null,
|
||||
null, null, 0x8B, 0xF1, 0xE8, null, null, null,
|
||||
null, 0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00, 0x88,
|
||||
0x44, 0x24, 0x0F
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "PowerbarHooks.Begin",
|
||||
PatternId = "powerbar-begin-v1",
|
||||
FallbackVa = 0x004DB390,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x83, 0xEC, 0x10, 0x55, 0x8B, 0x6C, 0x24, 0x18,
|
||||
0x56, 0x8D, 0x45, 0xFF, 0x83, 0xF8, 0x03, 0x57,
|
||||
0x8B, 0xF1, 0x0F, 0x87, 0xBC, 0x00, 0x00, 0x00,
|
||||
0xFF, 0x24, 0x85, null, null, null, null
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "PowerbarHooks.Level",
|
||||
PatternId = "powerbar-level-v1",
|
||||
FallbackVa = 0x004DB1B0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x04, 0x75,
|
||||
0x23, 0x68, 0x34, 0x00, 0x00, 0x10, 0x81, 0xC1,
|
||||
0x08, 0xFA, 0xFF, 0xFF, 0xE8, null, null, null,
|
||||
null, 0x85, 0xC0, 0x74, 0x0F
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "PowerbarHooks.Finish",
|
||||
PatternId = "powerbar-finish-v1",
|
||||
FallbackVa = 0x004DB1E0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x04, 0x75,
|
||||
0x33, 0x56, 0x8D, 0xB1, 0x08, 0xFA, 0xFF, 0xFF,
|
||||
0xC7, 0x41, 0x04, 0x00, 0x00, 0x00, 0x00, 0x68,
|
||||
0x34, 0x00, 0x00, 0x10, 0x8B, 0xCE, 0xE8, null,
|
||||
null, null, null
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "ChatHooks.UIElement::SetVisible",
|
||||
PatternId = "uielement-setvisible-v1",
|
||||
FallbackVa = 0x00462390,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x51, 0x53, 0x56, 0x57, 0x8B, 0x3D, null, null,
|
||||
null, null, 0x8B, 0xF1, 0xE8, null, null, null,
|
||||
null, 0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00, 0x88,
|
||||
0x44, 0x24, 0x0F
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "ChatHooks.ListenToElementMessage",
|
||||
PatternId = "chat-listen-v1",
|
||||
FallbackVa = 0x004CE6F0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x56, 0x8B, 0x74, 0x24, 0x08, 0x8B, 0x46, 0x08,
|
||||
0x48, 0x57, 0x8B, 0xF9, 0x74, 0x72, 0x83, 0xE8,
|
||||
0x06, 0x75, 0x7D, 0x8B, 0x4E, 0x04, 0x8B, 0x01,
|
||||
0x6A, 0x06, 0xFF, 0x90, 0x94, 0x00, 0x00, 0x00
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "RadarHooks.UIElement::SetVisible",
|
||||
PatternId = "uielement-setvisible-v1",
|
||||
FallbackVa = 0x00462390,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x51, 0x53, 0x56, 0x57, 0x8B, 0x3D, null, null,
|
||||
null, null, 0x8B, 0xF1, 0xE8, null, null, null,
|
||||
null, 0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00, 0x88,
|
||||
0x44, 0x24, 0x0F
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "RadarHooks.UIElement::GetSurfaceBox",
|
||||
PatternId = "uielement-surfacebox-v1",
|
||||
FallbackVa = 0x00462220,
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern =
|
||||
[
|
||||
0xF6, 0x81, 0x56, 0x05, 0x00, 0x00, 0x01, 0x74,
|
||||
0x11, 0x56, 0x8B, 0x74, 0x24, 0x08, 0x56, 0xE8,
|
||||
null, null, null, null, 0x8B, 0xC6, 0x5E, 0xC2,
|
||||
0x04, 0x00
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "RadarHooks.DrawObjects",
|
||||
PatternId = "radar-drawobjects-v1",
|
||||
FallbackVa = 0x004D9FE0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x81, 0xEC, 0xDC, 0x00, 0x00, 0x00, 0x53, 0x55,
|
||||
0x56, 0x8B, 0xF1, 0xD9, 0x86, 0x00, 0x06, 0x00,
|
||||
0x00, 0x8B, 0x86, 0x0C, 0x06, 0x00, 0x00, 0xD8,
|
||||
0x25, null, null, null, null, 0x33, 0xDB, 0x3B, 0xC3
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "RadarHooks.DrawChildren",
|
||||
PatternId = "radar-drawchildren-v1",
|
||||
FallbackVa = 0x004DA380,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x0C, 0x8B, 0x54, 0x24, 0x04,
|
||||
0x53, 0x55, 0x56, 0x8B, 0x74, 0x24, 0x1C, 0x57,
|
||||
0x56, 0x8B, 0xF9, 0x8B, 0x4C, 0x24, 0x1C, 0x50,
|
||||
0x51, 0x52, 0x8B, 0xCF, 0xE8, null, null, null,
|
||||
null, 0x56
|
||||
]
|
||||
},
|
||||
// ── Hooks NOT routed through HookResolver.Resolve. The engine still finds
|
||||
// these via PatternScanner.FindPattern + FindPrologueBefore (or
|
||||
// pattern-or-fixed-VA verify). Engine VA column will show "—" for all
|
||||
// of these because they don't emit HookResolver[...] log lines.
|
||||
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "LoginLifecycle.SendLoginCompleteNotification",
|
||||
PatternId = "loginComplete-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnCallSite,
|
||||
Pattern =
|
||||
[
|
||||
0x6A, 0x01, 0xC6, 0x86, null, null, null, null,
|
||||
0x01, 0xE8, null, null, null, null, 0x8B, 0x0D,
|
||||
null, null, null, null, 0x83, 0xC4, 0x04, 0x6A,
|
||||
0x00, 0x6A, 0x0B, 0xE8
|
||||
],
|
||||
WalkBack = new PrologueWalkBack([0x56, 0x8B, 0xF1], MaxDistance: 0x100)
|
||||
},
|
||||
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "SmartBoxHooks.DispatchSmartBoxEvent",
|
||||
PatternId = "smartbox-dispatch-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x83, 0xEC, 0x08, 0x53, 0x8B, 0x5C, 0x24, 0x10,
|
||||
0x8B, 0x53, 0x30, 0x83, 0xFA, 0x04, 0x8B, 0x43,
|
||||
0x2C, 0x56, 0x8B, 0xF1, 0x89, 0x44, 0x24, 0x14,
|
||||
0x89, 0x54, 0x24, 0x08, 0x72, null, 0x8B, 0x08
|
||||
]
|
||||
},
|
||||
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "SmartBoxHooks.DispatchGameEvent",
|
||||
PatternId = "smartbox-dispatch-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x83, 0xEC, 0x08, 0x53, 0x8B, 0x5C, 0x24, 0x10,
|
||||
0x8B, 0x53, 0x30, 0x83, 0xFA, 0x04, 0x8B, 0x43,
|
||||
0x2C, 0x56, 0x8B, 0xF1, 0x89, 0x44, 0x24, 0x14,
|
||||
0x89, 0x54, 0x24, 0x08, 0x72, null, 0x8B, 0x08
|
||||
]
|
||||
},
|
||||
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "UiLifecycleHooks.SetUIReady",
|
||||
PatternId = "setUIReady-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x56, 0x8B, 0x74, 0x24, 0x08, 0x85, 0xF6, 0x75,
|
||||
0x16, 0x8B, 0x0D, null, null, null, null, 0x85,
|
||||
0xC9, 0x74, 0x0C, 0x8B, 0x41, 0x04, 0x85, 0xC0,
|
||||
0x74, 0x05, 0xE8, null, null, null, null, 0x89,
|
||||
0x35, null, null, null, null, 0x5E, 0xC3
|
||||
]
|
||||
},
|
||||
|
||||
// ── MovementActionHooks: tiny `mov [edx], ACTION_CODE` wrappers. Each
|
||||
// pattern is the unique action-code write; walk back to the shared
|
||||
// 7-byte combat-family prologue (sub esp,0xC; push regs; call).
|
||||
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "MovementActionHooks.StopMovement",
|
||||
PatternId = "movement-stop-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0x61, 0xF6, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300)
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "MovementActionHooks.DoMovement",
|
||||
PatternId = "movement-do-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0x1E, 0xF6, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300)
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "MovementActionHooks.JumpNonAutonomous",
|
||||
PatternId = "movement-jump-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0xC9, 0xF7, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300)
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "MovementActionHooks.SetAutonomyLevel",
|
||||
PatternId = "movement-autonomy-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0x52, 0xF7, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300)
|
||||
},
|
||||
|
||||
// ── CombatActionHooks: same wrapper shape as Movement. CastSpell is
|
||||
// known-fragile (engine has it disabled); the snapshot will tell us
|
||||
// if the walk-back lands on a sane function.
|
||||
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "CombatActionHooks.CancelAttack",
|
||||
PatternId = "combat-cancel-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0xB7, 0x01, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300),
|
||||
AdvisoryRules = CombatCallCheck
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "CombatActionHooks.ChangeCombatMode",
|
||||
PatternId = "combat-change-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0x53, 0x00, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300),
|
||||
AdvisoryRules = CombatCallCheck
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "CombatActionHooks.QueryHealth",
|
||||
PatternId = "combat-queryhealth-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0xBF, 0x01, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300),
|
||||
AdvisoryRules = CombatCallCheck
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "CombatActionHooks.MeleeAttack",
|
||||
PatternId = "combat-melee-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0x08, 0x00, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300),
|
||||
AdvisoryRules = CombatCallCheck
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "CombatActionHooks.MissileAttack",
|
||||
PatternId = "combat-missile-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0x0A, 0x00, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300),
|
||||
AdvisoryRules = CombatCallCheck
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "CombatActionHooks.RequestId",
|
||||
PatternId = "combat-requestid-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0xC8, 0x00, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300),
|
||||
AdvisoryRules = CombatCallCheck
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "CombatActionHooks.CastSpell",
|
||||
PatternId = "combat-castspell-v1",
|
||||
Anchor = SymbolAnchor.AnchorOnBody,
|
||||
Pattern = [0xC7, 0x02, 0x4A, 0x00, 0x00, 0x00],
|
||||
WalkBack = new PrologueWalkBack(CombatActionPrologue, MaxDistance: 300),
|
||||
// Required (not advisory): if the walk-back ever lands on a
|
||||
// non-combat function, this flips CastSpell to Unresolved instead
|
||||
// of silently emitting a wrong VA — the whole point of the tool.
|
||||
RequiredRules = CombatCallCheck
|
||||
},
|
||||
|
||||
// ── ChatCallbackHooks: hardcoded VA + signature verify in the engine.
|
||||
// Tool just pattern-scans; if it resolves to the same VA the engine
|
||||
// uses, the pattern is sound.
|
||||
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "ChatCallbackHooks.IncomingChatAddTextToScroll",
|
||||
PatternId = "chat-incoming-scroll-v1",
|
||||
FallbackVa = 0x005649F0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84,
|
||||
0x24, 0x54, 0x09, 0x00, 0x00, 0x53, 0x55, 0x56,
|
||||
0x33, 0xF6, 0x84, 0xC0, 0x57, 0x8B, 0xBC, 0x24,
|
||||
0x5C, 0x09, 0x00, 0x00, 0x89, 0x4C, 0x24, 0x24
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "ChatCallbackHooks.IncomingChatWrapper",
|
||||
PatternId = "chat-incoming-wrapper-v1",
|
||||
FallbackVa = 0x0058A000,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0xA1, 0xE4, 0x0B, 0x87, 0x00, 0x85, 0xC0, 0x75,
|
||||
0x06, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x56,
|
||||
0x8B, 0x74, 0x24, 0x10, 0x83, 0xFE, 0x01, 0x74, 0x0F
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "ChatCallbackHooks.OutgoingChat",
|
||||
PatternId = "chat-outgoing-v1",
|
||||
FallbackVa = 0x005821A0,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x83, 0xEC, 0x0C, 0x53, 0x55, 0x56, 0x57, 0x8B,
|
||||
0xF9, 0xE8, null, null, null, null, 0x85, 0xC0,
|
||||
0x8B, 0x74, 0x24, 0x20, 0x74, 0x30, 0x8B, 0x06,
|
||||
0x50, 0xFF, 0x15, null, null, null, null, 0x8B,
|
||||
0xD8, 0xC7, 0x44, 0x24, 0x20, 0x00, 0x00, 0x00,
|
||||
0x00, 0xE8, null, null, null, null, 0x8B, 0x08,
|
||||
0x8D, 0x54, 0x24, 0x20, 0x52, 0x53, 0x50, 0xFF,
|
||||
0x51, 0x20, 0x8B, 0x44, 0x24, 0x20, 0x85, 0xC0,
|
||||
0x0F, 0x85, null, null, null, null, 0x8B, 0x44,
|
||||
0x24, 0x24, 0x6A, 0x00
|
||||
]
|
||||
},
|
||||
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "UpdateObjectInventoryHooks.UpdateObjectInventory",
|
||||
PatternId = "updateInv-v1",
|
||||
FallbackVa = 0x0055A190,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x04, 0x50, 0xE8, 0x96, 0xE7,
|
||||
0xFA, 0xFF, 0x8B, 0x4C, 0x24, 0x08, 0x51, 0x8D,
|
||||
0x48, 0x3C, 0xE8, 0x69, 0xFF, 0xFF, 0xFF, 0xC2,
|
||||
0x08, 0x00
|
||||
]
|
||||
},
|
||||
new HookSymbol
|
||||
{
|
||||
Id = "SalvageHooks.OpenSalvagePanel",
|
||||
PatternId = "salvage-open-v1",
|
||||
FallbackVa = 0x004CBF70,
|
||||
Anchor = SymbolAnchor.AnchorOnPrologue,
|
||||
Pattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x04, 0x56, 0x8B, 0xF1, 0x8B,
|
||||
0x8E, 0x00, 0x06, 0x00, 0x00, 0x51, 0x8B, 0xCE,
|
||||
0x89, 0x86, 0x08, 0x06, 0x00, 0x00, 0xE8, null,
|
||||
null, null, null, 0x8B, 0x8E, 0x00, 0x06, 0x00,
|
||||
0x00, 0xE8, null, null, null, null
|
||||
]
|
||||
}
|
||||
];
|
||||
}
|
||||
26
tools/HookResolver.Core/Symbols/HookSymbol.cs
Normal file
26
tools/HookResolver.Core/Symbols/HookSymbol.cs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
using System.Collections.Generic;
|
||||
using RynthCore.HookResolver.Core.Validation;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Symbols;
|
||||
|
||||
public enum SymbolAnchor
|
||||
{
|
||||
AnchorOnPrologue,
|
||||
AnchorOnBody,
|
||||
AnchorOnCallSite,
|
||||
AnchorOnStringRef
|
||||
}
|
||||
|
||||
public sealed record PrologueWalkBack(byte[] Prologue, int MaxDistance = 0x100);
|
||||
|
||||
public sealed record HookSymbol
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
public required string PatternId { get; init; }
|
||||
public required byte?[] Pattern { get; init; }
|
||||
public int? FallbackVa { get; init; }
|
||||
public required SymbolAnchor Anchor { get; init; }
|
||||
public PrologueWalkBack? WalkBack { get; init; }
|
||||
public IReadOnlyList<IValidationRule> RequiredRules { get; init; } = [];
|
||||
public IReadOnlyList<IValidationRule> AdvisoryRules { get; init; } = [];
|
||||
}
|
||||
18
tools/HookResolver.Core/Validation/IValidationRule.cs
Normal file
18
tools/HookResolver.Core/Validation/IValidationRule.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
using RynthCore.HookManifest.Scanning;
|
||||
using RynthCore.HookResolver.Core.Symbols;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Validation;
|
||||
|
||||
public readonly record struct ValidationContext(
|
||||
AcClientImageView Image,
|
||||
int CandidateRva,
|
||||
int CandidateVa,
|
||||
HookSymbol Symbol);
|
||||
|
||||
public readonly record struct ValidationOutcome(bool Passed, string RuleId, string Detail);
|
||||
|
||||
public interface IValidationRule
|
||||
{
|
||||
string RuleId { get; }
|
||||
ValidationOutcome Evaluate(in ValidationContext ctx);
|
||||
}
|
||||
51
tools/HookResolver.Core/Validation/Rules/CallTargetsRule.cs
Normal file
51
tools/HookResolver.Core/Validation/Rules/CallTargetsRule.cs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.HookResolver.Core.Disassembly;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Validation.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the candidate function with Iced and asserts that at least
|
||||
/// <see cref="_minMatches"/> of the <see cref="_expectedTargets"/> VAs appear
|
||||
/// as CALL targets in its body. This is the rule that distinguishes a real
|
||||
/// combat-action wrapper (which calls the shared dispatcher trio) from a
|
||||
/// look-alike the bare pattern happened to match.
|
||||
/// </summary>
|
||||
public sealed class CallTargetsRule : IValidationRule
|
||||
{
|
||||
private readonly int[] _expectedTargets;
|
||||
private readonly int _minMatches;
|
||||
private readonly int _scanBytes;
|
||||
|
||||
public CallTargetsRule(int[] expectedTargets, int minMatches, int scanBytes = 0x400)
|
||||
{
|
||||
_expectedTargets = expectedTargets;
|
||||
_minMatches = minMatches;
|
||||
_scanBytes = scanBytes;
|
||||
RuleId = "calltargets:[" +
|
||||
string.Join(",", expectedTargets.Select(v => $"0x{v:X8}")) +
|
||||
$"]>={minMatches}";
|
||||
}
|
||||
|
||||
public string RuleId { get; }
|
||||
|
||||
public ValidationOutcome Evaluate(in ValidationContext ctx)
|
||||
{
|
||||
var snap = IcedDisassembler.Snapshot(ctx.Image, ctx.CandidateRva, maxBytes: _scanBytes);
|
||||
var present = new HashSet<int>(snap.CallTargets.Select(c => c.Va));
|
||||
|
||||
var matched = _expectedTargets.Where(present.Contains).ToArray();
|
||||
bool pass = matched.Length >= _minMatches;
|
||||
|
||||
string matchedHex = matched.Length == 0
|
||||
? "none"
|
||||
: string.Join(",", matched.Select(v => $"0x{v:X8}"));
|
||||
|
||||
return new ValidationOutcome(
|
||||
pass,
|
||||
RuleId,
|
||||
$"{matched.Length}/{_expectedTargets.Length} expected dispatchers present " +
|
||||
$"({matchedHex}); needed >= {_minMatches}");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
using System;
|
||||
using RynthCore.HookManifest.Scanning;
|
||||
|
||||
namespace RynthCore.HookResolver.Core.Validation.Rules;
|
||||
|
||||
public sealed class PrologueBytesRule : IValidationRule
|
||||
{
|
||||
private readonly byte?[] _expected;
|
||||
|
||||
public PrologueBytesRule(byte?[] expected)
|
||||
{
|
||||
_expected = expected;
|
||||
RuleId = "prologue:" + FormatPattern(expected);
|
||||
}
|
||||
|
||||
public string RuleId { get; }
|
||||
|
||||
public ValidationOutcome Evaluate(in ValidationContext ctx)
|
||||
{
|
||||
int offset = ctx.CandidateRva - ctx.Image.TextRva;
|
||||
bool ok = PatternScanner.VerifyPattern(ctx.Image.TextBytes, offset, _expected);
|
||||
if (ok)
|
||||
return new ValidationOutcome(true, RuleId, "prologue matches");
|
||||
|
||||
int len = Math.Min(_expected.Length, ctx.Image.TextBytes.Length - offset);
|
||||
string actual = "";
|
||||
if (offset >= 0 && len > 0)
|
||||
{
|
||||
Span<byte> slice = ctx.Image.TextBytes.AsSpan(offset, len);
|
||||
actual = Convert.ToHexString(slice);
|
||||
}
|
||||
|
||||
return new ValidationOutcome(false, RuleId,
|
||||
$"prologue mismatch (saw {actual}, expected {FormatPattern(_expected)})");
|
||||
}
|
||||
|
||||
private static string FormatPattern(byte?[] pattern)
|
||||
{
|
||||
var sb = new System.Text.StringBuilder(pattern.Length * 2);
|
||||
foreach (var b in pattern)
|
||||
sb.Append(b.HasValue ? b.Value.ToString("X2") : "??");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
18
tools/HookResolver.SmokeTest/HookResolver.SmokeTest.csproj
Normal file
18
tools/HookResolver.SmokeTest/HookResolver.SmokeTest.csproj
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<AssemblyName>HookResolver.SmokeTest</AssemblyName>
|
||||
<RootNamespace>HookResolver.SmokeTest</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HookResolver.Core\RynthCore.HookResolver.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
110
tools/HookResolver.SmokeTest/Program.cs
Normal file
110
tools/HookResolver.SmokeTest/Program.cs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
using System.Globalization;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using RynthCore.HookResolver.Core.Offline;
|
||||
using RynthCore.HookResolver.Core.Resolution;
|
||||
using RynthCore.HookResolver.Core.Symbols;
|
||||
|
||||
string[] candidatePaths =
|
||||
[
|
||||
@"C:\Games\RynthCore\AcClient\acclient.exe",
|
||||
@"C:\Turbine\Asheron's Call\acclient.exe",
|
||||
];
|
||||
|
||||
string? path = candidatePaths.FirstOrDefault(File.Exists);
|
||||
if (path is null)
|
||||
{
|
||||
Console.WriteLine("ERROR: no acclient.exe found at any candidate path:");
|
||||
foreach (var p in candidatePaths) Console.WriteLine(" - " + p);
|
||||
return 2;
|
||||
}
|
||||
|
||||
Console.WriteLine("=== HookResolver smoke test ===");
|
||||
Console.WriteLine("acclient.exe path: " + path);
|
||||
|
||||
AcClientImage image = await AcClientImageLoader.LoadAsync(path);
|
||||
var input = image.Input;
|
||||
|
||||
Console.WriteLine("SHA256 : " + input.Sha256);
|
||||
Console.WriteLine("FileSizeBytes : " + input.FileSizeBytes);
|
||||
Console.WriteLine("Machine : " + input.Machine);
|
||||
Console.WriteLine($"ImageBase : 0x{input.ImageBase:X8}");
|
||||
Console.WriteLine($".text RVA : 0x{input.TextRva:X8}");
|
||||
Console.WriteLine($".text BaseVA : 0x{image.View.TextBaseVa:X8}");
|
||||
Console.WriteLine($".text bytes : {image.View.TextBytes.Length}");
|
||||
Console.WriteLine();
|
||||
|
||||
var symbols = AllSymbols.Default;
|
||||
var fallbackById = symbols.ToDictionary(s => s.Id, s => s.FallbackVa);
|
||||
|
||||
var entries = new List<HookManifestEntry>();
|
||||
await foreach (var e in HookResolveOrchestrator.ResolveAsync(image, symbols))
|
||||
entries.Add(e);
|
||||
|
||||
int total = entries.Count;
|
||||
int resolved = entries.Count(e => e.Status == ResolutionStatus.Resolved);
|
||||
int ambiguous = entries.Count(e => e.Status == ResolutionStatus.Ambiguous);
|
||||
int unresolved = entries.Count(e => e.Status == ResolutionStatus.Unresolved);
|
||||
int notApplicable = entries.Count(e => e.Status == ResolutionStatus.NotApplicable);
|
||||
|
||||
Console.WriteLine("=== BREAKDOWN ===");
|
||||
Console.WriteLine($"Total symbols : {total}");
|
||||
Console.WriteLine($"Resolved : {resolved}");
|
||||
Console.WriteLine($"Ambiguous : {ambiguous}");
|
||||
Console.WriteLine($"Unresolved : {unresolved}");
|
||||
Console.WriteLine($"NotApplicable : {notApplicable}");
|
||||
Console.WriteLine();
|
||||
|
||||
Console.WriteLine("=== NON-RESOLVED (Ambiguous / Unresolved / NotApplicable) ===");
|
||||
var bad = entries.Where(e => e.Status != ResolutionStatus.Resolved).ToList();
|
||||
if (bad.Count == 0)
|
||||
{
|
||||
Console.WriteLine("(none)");
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var e in bad)
|
||||
{
|
||||
Console.WriteLine($"- {e.SymbolId}");
|
||||
Console.WriteLine($" Status : {e.Status}");
|
||||
Console.WriteLine($" MatchedCandidates : {e.MatchedCandidates}");
|
||||
Console.WriteLine($" PatternId : {e.PatternId}");
|
||||
Console.WriteLine($" Reason : {e.Reason ?? "(null)"}");
|
||||
if (e.ChosenCandidateReason is { } ccr)
|
||||
Console.WriteLine($" ChosenReason : {ccr}");
|
||||
if (e.Address is { } a)
|
||||
Console.WriteLine($" (partial)Address : 0x{a.Va:X8}");
|
||||
foreach (var w in e.Warnings)
|
||||
Console.WriteLine($" Warning : [{w.RuleId}] passed={w.Passed} {w.Detail}");
|
||||
}
|
||||
}
|
||||
Console.WriteLine();
|
||||
|
||||
Console.WriteLine("=== RESOLVED (SymbolId -> VA) ===");
|
||||
foreach (var e in entries.Where(e => e.Status == ResolutionStatus.Resolved))
|
||||
{
|
||||
int? va = e.Address?.Va;
|
||||
string vaStr = va is { } v ? $"0x{v:X8}" : "(no addr)";
|
||||
string line = $" {e.SymbolId,-52} {vaStr}";
|
||||
|
||||
fallbackById.TryGetValue(e.SymbolId, out int? fb);
|
||||
if (fb is { } fbv)
|
||||
{
|
||||
if (va is { } v2 && v2 != fbv)
|
||||
line += $" [DELTA fallback=0x{fbv:X8} diff={(v2 - fbv):+#;-#;0}]";
|
||||
else if (va is { } v3 && v3 == fbv)
|
||||
line += " [==fallback]";
|
||||
}
|
||||
else
|
||||
{
|
||||
line += " [no-fallback]";
|
||||
}
|
||||
|
||||
// surface any advisory warnings even on resolved entries
|
||||
if (e.Warnings.Count > 0)
|
||||
line += $" (warnings={e.Warnings.Count})";
|
||||
|
||||
Console.WriteLine(line);
|
||||
}
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("=== DONE ===");
|
||||
return 0;
|
||||
8
tools/HookResolver.UI/App.axaml
Normal file
8
tools/HookResolver.UI/App.axaml
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="RynthCore.HookResolver.UI.App"
|
||||
RequestedThemeVariant="Dark">
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
20
tools/HookResolver.UI/App.axaml.cs
Normal file
20
tools/HookResolver.UI/App.axaml.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace RynthCore.HookResolver.UI;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
desktop.MainWindow = new MainWindow();
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
49
tools/HookResolver.UI/DiscoveryCandidateRow.cs
Normal file
49
tools/HookResolver.UI/DiscoveryCandidateRow.cs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
using System.Linq;
|
||||
using System.Text;
|
||||
using Avalonia.Media;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using RynthCore.HookResolver.Core.Discovery;
|
||||
|
||||
namespace RynthCore.HookResolver.UI;
|
||||
|
||||
public sealed class DiscoveryCandidateRow
|
||||
{
|
||||
public DiscoveryCandidateRow(StringDiscoveryCandidate candidate)
|
||||
{
|
||||
Candidate = candidate;
|
||||
Va = $"0x{candidate.Va:X8}";
|
||||
PushSiteVa = $"push @ 0x{candidate.PushSiteVa:X8}";
|
||||
|
||||
var s = candidate.Snapshot;
|
||||
Summary = $"{s.LengthBytes} bytes • {s.InstructionCount} instr • " +
|
||||
(s.EndsAtReturn ? "ends RET" : "no RET");
|
||||
PrologueDisplay = FormatHex(s.PrologueHex);
|
||||
CallTargetsDisplay = s.CallTargets.Count == 0
|
||||
? "(none)"
|
||||
: string.Join(" ", s.CallTargets.Take(5).Select(ct => $"+0x{ct.Offset:X3}→0x{ct.Va:X8}"));
|
||||
|
||||
AccentBrush = s.EndsAtReturn && s.LengthBytes > 16
|
||||
? new SolidColorBrush(Color.Parse("#26C1A6"))
|
||||
: new SolidColorBrush(Color.Parse("#E0B040"));
|
||||
}
|
||||
|
||||
public StringDiscoveryCandidate Candidate { get; }
|
||||
public FunctionSnapshot Snapshot => Candidate.Snapshot;
|
||||
public string Va { get; }
|
||||
public string PushSiteVa { get; }
|
||||
public string Summary { get; }
|
||||
public string PrologueDisplay { get; }
|
||||
public string CallTargetsDisplay { get; }
|
||||
public IBrush AccentBrush { get; }
|
||||
|
||||
private static string FormatHex(string raw)
|
||||
{
|
||||
var sb = new StringBuilder(raw.Length + raw.Length / 2);
|
||||
for (int i = 0; i < raw.Length; i += 2)
|
||||
{
|
||||
if (i > 0) sb.Append(' ');
|
||||
sb.Append(raw, i, 2);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
123
tools/HookResolver.UI/HookRow.cs
Normal file
123
tools/HookResolver.UI/HookRow.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using System.Linq;
|
||||
using System.Text;
|
||||
using Avalonia.Media;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using RynthCore.HookResolver.Core.Diff;
|
||||
|
||||
namespace RynthCore.HookResolver.UI;
|
||||
|
||||
public sealed class HookRow
|
||||
{
|
||||
public HookRow(HookManifestEntry entry, EngineResolution? engine)
|
||||
{
|
||||
Entry = entry;
|
||||
SymbolId = entry.SymbolId;
|
||||
Status = entry.Status.ToString();
|
||||
Va = entry.Address?.Hex ?? "—";
|
||||
Detail = entry.Reason
|
||||
?? entry.ChosenCandidateReason
|
||||
?? (entry.Validations.Count > 0 ? entry.Validations[0].Detail : "");
|
||||
|
||||
StatusBrush = entry.Status switch
|
||||
{
|
||||
ResolutionStatus.Resolved => new SolidColorBrush(Color.Parse("#26C1A6")),
|
||||
ResolutionStatus.Ambiguous => new SolidColorBrush(Color.Parse("#E0B040")),
|
||||
ResolutionStatus.Unresolved => new SolidColorBrush(Color.Parse("#D24F4F")),
|
||||
_ => new SolidColorBrush(Color.Parse("#8896A0")),
|
||||
};
|
||||
|
||||
if (engine is null)
|
||||
{
|
||||
EngineVa = "—";
|
||||
DiffSymbol = "·";
|
||||
DiffBrush = new SolidColorBrush(Color.Parse("#56646D"));
|
||||
DiffTooltip = "no engine-log entry for this symbol";
|
||||
}
|
||||
else if (engine.Va is null)
|
||||
{
|
||||
EngineVa = "unavailable";
|
||||
DiffSymbol = "⊘";
|
||||
DiffBrush = new SolidColorBrush(Color.Parse("#D24F4F"));
|
||||
DiffTooltip = "engine logged UNAVAILABLE";
|
||||
}
|
||||
else
|
||||
{
|
||||
int engineVa = engine.Va.Value;
|
||||
EngineVa = $"0x{engineVa:X8}";
|
||||
|
||||
if (entry.Address is { } toolAddr && toolAddr.Va == engineVa)
|
||||
{
|
||||
DiffSymbol = "✓";
|
||||
DiffBrush = new SolidColorBrush(Color.Parse("#26C1A6"));
|
||||
DiffTooltip = $"match ({engine.Kind})";
|
||||
}
|
||||
else if (entry.Address is null)
|
||||
{
|
||||
DiffSymbol = "?";
|
||||
DiffBrush = new SolidColorBrush(Color.Parse("#E0B040"));
|
||||
DiffTooltip = "tool unresolved, engine has VA";
|
||||
}
|
||||
else
|
||||
{
|
||||
DiffSymbol = "✗";
|
||||
DiffBrush = new SolidColorBrush(Color.Parse("#D24F4F"));
|
||||
int delta = entry.Address.Va - engineVa;
|
||||
DiffTooltip = $"mismatch — tool/engine delta {delta:+#;-#;0}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public HookManifestEntry Entry { get; }
|
||||
public string SymbolId { get; }
|
||||
public string Status { get; }
|
||||
public string Va { get; }
|
||||
public string EngineVa { get; }
|
||||
public string DiffSymbol { get; }
|
||||
public string DiffTooltip { get; }
|
||||
public string Detail { get; }
|
||||
public IBrush StatusBrush { get; }
|
||||
public IBrush DiffBrush { get; }
|
||||
|
||||
public bool HasSnapshot => Entry.Snapshot is not null;
|
||||
|
||||
public string SnapshotSummary
|
||||
{
|
||||
get
|
||||
{
|
||||
var s = Entry.Snapshot;
|
||||
if (s is null) return "(no snapshot — symbol unresolved)";
|
||||
return $"{s.LengthBytes} bytes • {s.InstructionCount} instructions • " +
|
||||
(s.EndsAtReturn ? "ends at RET" : "no RET in range");
|
||||
}
|
||||
}
|
||||
|
||||
public string SnapshotPrologue =>
|
||||
Entry.Snapshot is { PrologueHex: var hex } ? FormatHex(hex) : "—";
|
||||
|
||||
public string SnapshotCallTargets
|
||||
{
|
||||
get
|
||||
{
|
||||
var s = Entry.Snapshot;
|
||||
if (s is null || s.CallTargets.Count == 0) return "(none captured)";
|
||||
var sb = new StringBuilder();
|
||||
foreach (var ct in s.CallTargets.Take(8))
|
||||
sb.AppendLine($" +0x{ct.Offset:X3} → 0x{ct.Va:X8}");
|
||||
return sb.ToString().TrimEnd();
|
||||
}
|
||||
}
|
||||
|
||||
public string SnapshotNote => Entry.Snapshot?.Note ?? "";
|
||||
public bool HasSnapshotNote => !string.IsNullOrEmpty(Entry.Snapshot?.Note);
|
||||
|
||||
private static string FormatHex(string raw)
|
||||
{
|
||||
var sb = new StringBuilder(raw.Length + raw.Length / 2);
|
||||
for (int i = 0; i < raw.Length; i += 2)
|
||||
{
|
||||
if (i > 0) sb.Append(' ');
|
||||
sb.Append(raw, i, 2);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
301
tools/HookResolver.UI/MainViewModel.cs
Normal file
301
tools/HookResolver.UI/MainViewModel.cs
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.HookResolver.Core.Diff;
|
||||
using RynthCore.HookResolver.Core.Discovery;
|
||||
|
||||
namespace RynthCore.HookResolver.UI;
|
||||
|
||||
public sealed class MainViewModel : INotifyPropertyChanged
|
||||
{
|
||||
public const string DefaultAcClientPath = @"C:\Games\RynthCore\AcClient\acclient.exe";
|
||||
public const string DefaultManifestPath = @"C:\Games\RynthCore\hooks.json";
|
||||
|
||||
private string _acClientPath = DefaultAcClientPath;
|
||||
private string _manifestPath = DefaultManifestPath;
|
||||
private string _logPath = EngineLogParser.ResolveDefaultLogPath();
|
||||
private string _statusText = "Ready.";
|
||||
private string _sha256 = "—";
|
||||
private int _resolvedCount;
|
||||
private int _ambiguousCount;
|
||||
private int _unresolvedCount;
|
||||
private int _matchCount;
|
||||
private int _mismatchCount;
|
||||
private int _totalCount;
|
||||
private bool _isResolving;
|
||||
private bool _canSave;
|
||||
private HookRow? _selectedRow;
|
||||
|
||||
public ObservableCollection<HookRow> Hooks { get; } = new();
|
||||
|
||||
public string AcClientPath
|
||||
{
|
||||
get => _acClientPath;
|
||||
set
|
||||
{
|
||||
if (_acClientPath == value) return;
|
||||
_acClientPath = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(CanResolve));
|
||||
}
|
||||
}
|
||||
|
||||
public string ManifestPath
|
||||
{
|
||||
get => _manifestPath;
|
||||
set { if (_manifestPath != value) { _manifestPath = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public string LogPath
|
||||
{
|
||||
get => _logPath;
|
||||
set { if (_logPath != value) { _logPath = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public string StatusText
|
||||
{
|
||||
get => _statusText;
|
||||
set { if (_statusText != value) { _statusText = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public string Sha256Display
|
||||
{
|
||||
get => _sha256;
|
||||
set { if (_sha256 != value) { _sha256 = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public string CountsDisplay => _totalCount == 0
|
||||
? ""
|
||||
: $"resolved {_resolvedCount} ambiguous {_ambiguousCount} unresolved {_unresolvedCount} ({Hooks.Count}/{_totalCount})";
|
||||
|
||||
public string DiffDisplay => (_matchCount + _mismatchCount) == 0
|
||||
? ""
|
||||
: $"vs engine log: match {_matchCount} mismatch {_mismatchCount}";
|
||||
|
||||
public bool IsResolving
|
||||
{
|
||||
get => _isResolving;
|
||||
set
|
||||
{
|
||||
if (_isResolving == value) return;
|
||||
_isResolving = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(CanResolve));
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanResolve => !_isResolving && File.Exists(_acClientPath);
|
||||
|
||||
public bool CanSave
|
||||
{
|
||||
get => _canSave;
|
||||
set { if (_canSave != value) { _canSave = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public HookRow? SelectedRow
|
||||
{
|
||||
get => _selectedRow;
|
||||
set
|
||||
{
|
||||
if (ReferenceEquals(_selectedRow, value)) return;
|
||||
_selectedRow = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(HasSelection));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasSelection => _selectedRow is not null;
|
||||
|
||||
// ── Discovery tab state ──────────────────────────────────────────────
|
||||
|
||||
private string _searchLiteral = "ChatBarEnter";
|
||||
private ProloguePreset _selectedPreset = StringDiscoveryService.Presets[0];
|
||||
private int _maxBackward = 0x2000;
|
||||
private bool _looseMatch;
|
||||
private StringReferenceMode _referenceMode = StringReferenceMode.PushImm32;
|
||||
private string _discoveryStatus = "Enter a string and click Search.";
|
||||
private DiscoveryCandidateRow? _selectedCandidate;
|
||||
private bool _isDiscovering;
|
||||
|
||||
public ObservableCollection<DiscoveryCandidateRow> DiscoveryCandidates { get; } = new();
|
||||
public IReadOnlyList<ProloguePreset> Presets => StringDiscoveryService.Presets;
|
||||
|
||||
public string SearchLiteral
|
||||
{
|
||||
get => _searchLiteral;
|
||||
set
|
||||
{
|
||||
if (_searchLiteral == value) return;
|
||||
_searchLiteral = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(CanSearch));
|
||||
}
|
||||
}
|
||||
|
||||
public ProloguePreset SelectedPreset
|
||||
{
|
||||
get => _selectedPreset;
|
||||
set
|
||||
{
|
||||
if (ReferenceEquals(_selectedPreset, value)) return;
|
||||
_selectedPreset = value;
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public int MaxBackward
|
||||
{
|
||||
get => _maxBackward;
|
||||
set { if (_maxBackward != value) { _maxBackward = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public bool LooseMatch
|
||||
{
|
||||
get => _looseMatch;
|
||||
set { if (_looseMatch != value) { _looseMatch = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public StringReferenceMode[] ReferenceModes { get; } =
|
||||
(StringReferenceMode[])System.Enum.GetValues(typeof(StringReferenceMode));
|
||||
|
||||
public StringReferenceMode SelectedReferenceMode
|
||||
{
|
||||
get => _referenceMode;
|
||||
set { if (_referenceMode != value) { _referenceMode = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public string DiscoveryStatus
|
||||
{
|
||||
get => _discoveryStatus;
|
||||
set { if (_discoveryStatus != value) { _discoveryStatus = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public DiscoveryCandidateRow? SelectedCandidate
|
||||
{
|
||||
get => _selectedCandidate;
|
||||
set
|
||||
{
|
||||
if (ReferenceEquals(_selectedCandidate, value)) return;
|
||||
_selectedCandidate = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(HasDiscoverySelection));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasDiscoverySelection => _selectedCandidate is not null;
|
||||
|
||||
public bool IsDiscovering
|
||||
{
|
||||
get => _isDiscovering;
|
||||
set
|
||||
{
|
||||
if (_isDiscovering == value) return;
|
||||
_isDiscovering = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(CanSearch));
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanSearch => !_isDiscovering && !string.IsNullOrWhiteSpace(_searchLiteral);
|
||||
|
||||
// ── Class/vtable discovery state ─────────────────────────────────────
|
||||
|
||||
private string _searchClass = "gmRadarUI";
|
||||
private string _classDiscoveryStatus = "Enter a class name (e.g. gmRadarUI) and click Find.";
|
||||
private VtableMethodRow? _selectedVtableMethod;
|
||||
private bool _isVtableDiscovering;
|
||||
|
||||
public ObservableCollection<VtableMethodRow> VtableMethods { get; } = new();
|
||||
|
||||
public string SearchClass
|
||||
{
|
||||
get => _searchClass;
|
||||
set
|
||||
{
|
||||
if (_searchClass == value) return;
|
||||
_searchClass = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(CanSearchClass));
|
||||
}
|
||||
}
|
||||
|
||||
public string ClassDiscoveryStatus
|
||||
{
|
||||
get => _classDiscoveryStatus;
|
||||
set { if (_classDiscoveryStatus != value) { _classDiscoveryStatus = value; OnPropertyChanged(); } }
|
||||
}
|
||||
|
||||
public VtableMethodRow? SelectedVtableMethod
|
||||
{
|
||||
get => _selectedVtableMethod;
|
||||
set
|
||||
{
|
||||
if (ReferenceEquals(_selectedVtableMethod, value)) return;
|
||||
_selectedVtableMethod = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(HasVtableSelection));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasVtableSelection => _selectedVtableMethod is not null;
|
||||
|
||||
public bool IsVtableDiscovering
|
||||
{
|
||||
get => _isVtableDiscovering;
|
||||
set
|
||||
{
|
||||
if (_isVtableDiscovering == value) return;
|
||||
_isVtableDiscovering = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(CanSearchClass));
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanSearchClass => !_isVtableDiscovering && !string.IsNullOrWhiteSpace(_searchClass);
|
||||
|
||||
public void BeginResolve(int totalSymbols)
|
||||
{
|
||||
_resolvedCount = _ambiguousCount = _unresolvedCount = 0;
|
||||
_matchCount = _mismatchCount = 0;
|
||||
_totalCount = totalSymbols;
|
||||
Hooks.Clear();
|
||||
CanSave = false;
|
||||
IsResolving = true;
|
||||
StatusText = $"Resolving {totalSymbols} symbol(s)…";
|
||||
Sha256Display = "—";
|
||||
OnPropertyChanged(nameof(CountsDisplay));
|
||||
OnPropertyChanged(nameof(DiffDisplay));
|
||||
}
|
||||
|
||||
public void AddRow(HookRow row)
|
||||
{
|
||||
Hooks.Add(row);
|
||||
switch (row.Entry.Status)
|
||||
{
|
||||
case RynthCore.HookManifest.Schema.ResolutionStatus.Resolved: _resolvedCount++; break;
|
||||
case RynthCore.HookManifest.Schema.ResolutionStatus.Ambiguous: _ambiguousCount++; break;
|
||||
case RynthCore.HookManifest.Schema.ResolutionStatus.Unresolved: _unresolvedCount++; break;
|
||||
}
|
||||
switch (row.DiffSymbol)
|
||||
{
|
||||
case "✓": _matchCount++; break;
|
||||
case "✗": _mismatchCount++; break;
|
||||
}
|
||||
OnPropertyChanged(nameof(CountsDisplay));
|
||||
OnPropertyChanged(nameof(DiffDisplay));
|
||||
}
|
||||
|
||||
public void EndResolve(bool success, string message, string? sha256 = null)
|
||||
{
|
||||
IsResolving = false;
|
||||
StatusText = message;
|
||||
if (sha256 is not null) Sha256Display = sha256;
|
||||
CanSave = success && Hooks.Count > 0;
|
||||
}
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
private void OnPropertyChanged([CallerMemberName] string? name = null)
|
||||
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
|
||||
}
|
||||
540
tools/HookResolver.UI/MainWindow.axaml
Normal file
540
tools/HookResolver.UI/MainWindow.axaml
Normal file
|
|
@ -0,0 +1,540 @@
|
|||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:RynthCore.HookResolver.UI"
|
||||
xmlns:disc="clr-namespace:RynthCore.HookResolver.Core.Discovery;assembly=RynthCore.HookResolver.Core"
|
||||
x:Class="RynthCore.HookResolver.UI.MainWindow"
|
||||
x:DataType="local:MainViewModel"
|
||||
Width="1440"
|
||||
Height="820"
|
||||
MinWidth="1000"
|
||||
MinHeight="560"
|
||||
Title="RynthCore Hook Resolver"
|
||||
Background="#0B1218">
|
||||
<Window.Styles>
|
||||
<Style Selector="TextBlock">
|
||||
<Setter Property="FontSize" Value="12.5" />
|
||||
<Setter Property="Foreground" Value="#D6DDE3" />
|
||||
</Style>
|
||||
<Style Selector="TextBox">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Background" Value="#0F161D" />
|
||||
<Setter Property="Foreground" Value="#D6DDE3" />
|
||||
<Setter Property="BorderBrush" Value="#243742" />
|
||||
</Style>
|
||||
<Style Selector="ComboBox">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Background" Value="#0F161D" />
|
||||
<Setter Property="Foreground" Value="#D6DDE3" />
|
||||
<Setter Property="BorderBrush" Value="#243742" />
|
||||
</Style>
|
||||
<Style Selector="Button">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Padding" Value="14,8" />
|
||||
<Setter Property="Background" Value="#1A2E38" />
|
||||
<Setter Property="Foreground" Value="#26C1A6" />
|
||||
<Setter Property="BorderBrush" Value="#26C1A6" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="CornerRadius" Value="6" />
|
||||
</Style>
|
||||
<Style Selector="Button:pointerover /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="#26C1A6" />
|
||||
<Setter Property="TextElement.Foreground" Value="#0B1218" />
|
||||
</Style>
|
||||
<Style Selector="Button:disabled">
|
||||
<Setter Property="Opacity" Value="0.4" />
|
||||
</Style>
|
||||
<Style Selector="ListBox">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
</Style>
|
||||
<Style Selector="ListBoxItem">
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
</Style>
|
||||
<Style Selector="ListBoxItem:selected /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="#152633" />
|
||||
</Style>
|
||||
<Style Selector="ListBoxItem:pointerover /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="#12202A" />
|
||||
</Style>
|
||||
<Style Selector="TabItem">
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="MinHeight" Value="32" />
|
||||
<Setter Property="Padding" Value="14,6" />
|
||||
<Setter Property="Foreground" Value="#8896A0" />
|
||||
</Style>
|
||||
<Style Selector="TabItem:selected">
|
||||
<Setter Property="Foreground" Value="#26C1A6" />
|
||||
</Style>
|
||||
</Window.Styles>
|
||||
|
||||
<Grid RowDefinitions="Auto,Auto,*,Auto" Margin="14">
|
||||
|
||||
<Border Grid.Row="0"
|
||||
Padding="14"
|
||||
CornerRadius="14"
|
||||
Background="#132028"
|
||||
BorderBrush="#26C1A6"
|
||||
BorderThickness="1"
|
||||
Margin="0,0,0,10">
|
||||
<StackPanel>
|
||||
<TextBlock Text="RynthCore Hook Resolver"
|
||||
FontSize="18"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="#26C1A6" />
|
||||
<TextBlock Text="Offline resolver — pattern-scan known hooks (Hooks tab) or discover new ones by string reference (Discover tab)."
|
||||
Margin="0,4,0,0"
|
||||
Foreground="#8896A0"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Row="1"
|
||||
Padding="12"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1"
|
||||
Margin="0,0,0,10">
|
||||
<StackPanel>
|
||||
<Grid ColumnDefinitions="Auto,*,Auto,Auto" RowDefinitions="Auto">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="acclient.exe:"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,10,0"
|
||||
MinWidth="100" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding AcClientPath, Mode=TwoWay}"
|
||||
VerticalAlignment="Center" />
|
||||
<Button Grid.Column="2"
|
||||
Content="…"
|
||||
Margin="8,0,0,0"
|
||||
MinWidth="38"
|
||||
Click="OnBrowseAcClient" />
|
||||
<Button Grid.Column="3"
|
||||
Content="Resolve"
|
||||
Margin="8,0,0,0"
|
||||
IsEnabled="{Binding CanResolve}"
|
||||
Click="OnResolveClick" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="Auto,*,Auto" RowDefinitions="Auto" Margin="0,8,0,0">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="engine log:"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,10,0"
|
||||
MinWidth="100"
|
||||
Foreground="#8896A0" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding LogPath, Mode=TwoWay}"
|
||||
VerticalAlignment="Center" />
|
||||
<Button Grid.Column="2"
|
||||
Content="…"
|
||||
Margin="8,0,0,0"
|
||||
MinWidth="38"
|
||||
Click="OnBrowseLog" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<TabControl Grid.Row="2" Background="Transparent" BorderThickness="0" Padding="0">
|
||||
|
||||
<!-- ───────────── HOOKS TAB ───────────── -->
|
||||
<TabItem Header="Hooks">
|
||||
<Grid ColumnDefinitions="*,12,420" Margin="0,8,0,0">
|
||||
|
||||
<Border Grid.Column="0"
|
||||
Padding="0"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1">
|
||||
<Grid RowDefinitions="Auto,*">
|
||||
<Grid Grid.Row="0"
|
||||
ColumnDefinitions="2.4*,0.9*,1.3*,1.3*,0.4*,2.2*"
|
||||
Margin="14,10,14,8">
|
||||
<TextBlock Grid.Column="0" Text="Symbol" FontWeight="SemiBold" Foreground="#8896A0" />
|
||||
<TextBlock Grid.Column="1" Text="Status" FontWeight="SemiBold" Foreground="#8896A0" />
|
||||
<TextBlock Grid.Column="2" Text="Tool VA" FontWeight="SemiBold" Foreground="#8896A0" />
|
||||
<TextBlock Grid.Column="3" Text="Engine VA" FontWeight="SemiBold" Foreground="#8896A0" />
|
||||
<TextBlock Grid.Column="4" Text="Diff" FontWeight="SemiBold" Foreground="#8896A0" HorizontalAlignment="Center" />
|
||||
<TextBlock Grid.Column="5" Text="Detail" FontWeight="SemiBold" Foreground="#8896A0" />
|
||||
</Grid>
|
||||
|
||||
<ListBox Grid.Row="1"
|
||||
ItemsSource="{Binding Hooks}"
|
||||
SelectedItem="{Binding SelectedRow, Mode=TwoWay}"
|
||||
SelectionMode="Single">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="local:HookRow">
|
||||
<Border BorderBrush="#1A2730"
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="14,8">
|
||||
<Grid ColumnDefinitions="2.4*,0.9*,1.3*,1.3*,0.4*,2.2*">
|
||||
<TextBlock Grid.Column="0" Text="{Binding SymbolId}" VerticalAlignment="Center" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Status}" Foreground="{Binding StatusBrush}" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="2" Text="{Binding Va}" VerticalAlignment="Center" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
<TextBlock Grid.Column="3" Text="{Binding EngineVa}" VerticalAlignment="Center" FontFamily="Cascadia Mono, Consolas, monospace" Foreground="#A8B2BB" />
|
||||
<TextBlock Grid.Column="4" Text="{Binding DiffSymbol}" Foreground="{Binding DiffBrush}" FontWeight="SemiBold" VerticalAlignment="Center" HorizontalAlignment="Center" ToolTip.Tip="{Binding DiffTooltip}" />
|
||||
<TextBlock Grid.Column="5" Text="{Binding Detail}" VerticalAlignment="Center" TextWrapping="Wrap" Foreground="#A8B2BB" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Column="2"
|
||||
Padding="14"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1">
|
||||
<ScrollViewer>
|
||||
<StackPanel>
|
||||
<TextBlock Text="Function context" FontSize="14" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock Text="Click a row to inspect the resolved function."
|
||||
Margin="0,4,0,0"
|
||||
IsVisible="{Binding !HasSelection}"
|
||||
Foreground="#8896A0" />
|
||||
|
||||
<StackPanel IsVisible="{Binding HasSelection}" Margin="0,8,0,0">
|
||||
<TextBlock Text="{Binding SelectedRow.SymbolId}" FontFamily="Cascadia Mono, Consolas, monospace" FontWeight="SemiBold" TextWrapping="Wrap" />
|
||||
|
||||
<Grid ColumnDefinitions="Auto,*" RowDefinitions="Auto,Auto,Auto" Margin="0,8,0,0">
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Text="status: " Foreground="#8896A0" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding SelectedRow.Status}" Foreground="{Binding SelectedRow.StatusBrush}" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Text="tool VA: " Foreground="#8896A0" />
|
||||
<SelectableTextBlock Grid.Row="1" Grid.Column="1" Text="{Binding SelectedRow.Va}" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" Text="engine VA: " Foreground="#8896A0" />
|
||||
<SelectableTextBlock Grid.Row="2" Grid.Column="1" Text="{Binding SelectedRow.EngineVa}" FontFamily="Cascadia Mono, Consolas, monospace" Foreground="#A8B2BB" />
|
||||
</Grid>
|
||||
|
||||
<Separator Margin="0,10,0,8" Background="#1A2730" />
|
||||
<TextBlock Text="snapshot" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock Text="{Binding SelectedRow.SnapshotSummary}" Margin="0,4,0,0" />
|
||||
|
||||
<TextBlock Text="prologue (8 bytes)" Margin="0,10,0,4" Foreground="#8896A0" />
|
||||
<Border Background="#091017" BorderBrush="#1A2730" BorderThickness="1" CornerRadius="4" Padding="8,6">
|
||||
<SelectableTextBlock Text="{Binding SelectedRow.SnapshotPrologue}" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
</Border>
|
||||
|
||||
<TextBlock Text="CALL targets (offset → VA)" Margin="0,10,0,4" Foreground="#8896A0" />
|
||||
<Border Background="#091017" BorderBrush="#1A2730" BorderThickness="1" CornerRadius="4" Padding="8,6">
|
||||
<SelectableTextBlock Text="{Binding SelectedRow.SnapshotCallTargets}" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
<!-- ───────────── DISCOVER TAB ───────────── -->
|
||||
<TabItem Header="Discover by string">
|
||||
<Grid RowDefinitions="Auto,Auto,*" Margin="0,8,0,0">
|
||||
|
||||
<Border Grid.Row="0"
|
||||
Padding="12"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1">
|
||||
<StackPanel>
|
||||
<Grid ColumnDefinitions="Auto,*,Auto" RowDefinitions="Auto">
|
||||
<TextBlock Grid.Column="0" Text="string:" VerticalAlignment="Center" Margin="0,0,8,0" MinWidth="60" />
|
||||
<TextBox Grid.Column="1" Text="{Binding SearchLiteral, Mode=TwoWay}" VerticalAlignment="Center" />
|
||||
<Button Grid.Column="2"
|
||||
Content="Search"
|
||||
Margin="14,0,0,0"
|
||||
IsEnabled="{Binding CanSearch}"
|
||||
Click="OnSearchClick" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="Auto,1.4*,Auto,1.2*,Auto,70,Auto" RowDefinitions="Auto" Margin="0,8,0,0">
|
||||
<TextBlock Grid.Column="0" Text="prologue:" VerticalAlignment="Center" Margin="0,0,8,0" MinWidth="60" />
|
||||
<ComboBox Grid.Column="1"
|
||||
ItemsSource="{Binding Presets}"
|
||||
SelectedItem="{Binding SelectedPreset, Mode=TwoWay}"
|
||||
VerticalAlignment="Center"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate DataType="disc:ProloguePreset">
|
||||
<TextBlock Text="{Binding Name}" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
|
||||
<TextBlock Grid.Column="2" Text="reference:" VerticalAlignment="Center" Margin="14,0,8,0" />
|
||||
<ComboBox Grid.Column="3"
|
||||
ItemsSource="{Binding ReferenceModes}"
|
||||
SelectedItem="{Binding SelectedReferenceMode, Mode=TwoWay}"
|
||||
VerticalAlignment="Center"
|
||||
HorizontalAlignment="Stretch"
|
||||
ToolTip.Tip="PushImm32 = printf-style string arg (precise). AnyImm32InText = mov/lea/cmp immediate (broad). DataPointer = string used as a .rdata table entry (no function)." />
|
||||
|
||||
<TextBlock Grid.Column="4" Text="walk back:" VerticalAlignment="Center" Margin="14,0,8,0" />
|
||||
<TextBox Grid.Column="5" Text="{Binding MaxBackward, Mode=TwoWay}" VerticalAlignment="Center" />
|
||||
|
||||
<CheckBox Grid.Column="6"
|
||||
Content="loose"
|
||||
IsChecked="{Binding LooseMatch, Mode=TwoWay}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="14,0,0,0"
|
||||
Foreground="#D6DDE3"
|
||||
ToolTip.Tip="Match the string even if it isn't NUL-terminated (finds substrings embedded in longer strings)." />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Row="1"
|
||||
Margin="0,10,0,10"
|
||||
Padding="12,10"
|
||||
CornerRadius="10"
|
||||
Background="#091017"
|
||||
BorderBrush="#1A2730"
|
||||
BorderThickness="1">
|
||||
<SelectableTextBlock Text="{Binding DiscoveryStatus}" TextWrapping="Wrap" Foreground="#D6DDE3" />
|
||||
</Border>
|
||||
|
||||
<Grid Grid.Row="2" ColumnDefinitions="*,12,420">
|
||||
|
||||
<Border Grid.Column="0"
|
||||
Padding="0"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1">
|
||||
<ListBox ItemsSource="{Binding DiscoveryCandidates}"
|
||||
SelectedItem="{Binding SelectedCandidate, Mode=TwoWay}"
|
||||
SelectionMode="Single">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="local:DiscoveryCandidateRow">
|
||||
<Border BorderBrush="#1A2730"
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="14,10">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Grid.Column="0">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding Va}"
|
||||
FontFamily="Cascadia Mono, Consolas, monospace"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="{Binding AccentBrush}" />
|
||||
<TextBlock Text=" "/>
|
||||
<TextBlock Text="{Binding Summary}" Foreground="#A8B2BB" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding PushSiteVa}"
|
||||
Margin="0,2,0,0"
|
||||
FontFamily="Cascadia Mono, Consolas, monospace"
|
||||
Foreground="#56646D" />
|
||||
<TextBlock Text="{Binding CallTargetsDisplay}"
|
||||
Margin="0,2,0,0"
|
||||
FontFamily="Cascadia Mono, Consolas, monospace"
|
||||
FontSize="11"
|
||||
Foreground="#56646D"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1"
|
||||
Content="Promote"
|
||||
VerticalAlignment="Center"
|
||||
Margin="10,0,0,0"
|
||||
Click="OnPromoteStringCandidate" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Column="2"
|
||||
Padding="14"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1">
|
||||
<ScrollViewer>
|
||||
<StackPanel>
|
||||
<TextBlock Text="Candidate context" FontSize="14" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock Text="Search for a string, then click a candidate to inspect."
|
||||
Margin="0,4,0,0"
|
||||
IsVisible="{Binding !HasDiscoverySelection}"
|
||||
Foreground="#8896A0" />
|
||||
|
||||
<StackPanel IsVisible="{Binding HasDiscoverySelection}" Margin="0,8,0,0">
|
||||
<SelectableTextBlock Text="{Binding SelectedCandidate.Va}" FontFamily="Cascadia Mono, Consolas, monospace" FontSize="14" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{Binding SelectedCandidate.Summary}" Margin="0,6,0,0" />
|
||||
|
||||
<TextBlock Text="prologue (8 bytes)" Margin="0,10,0,4" Foreground="#8896A0" />
|
||||
<Border Background="#091017" BorderBrush="#1A2730" BorderThickness="1" CornerRadius="4" Padding="8,6">
|
||||
<SelectableTextBlock Text="{Binding SelectedCandidate.PrologueDisplay}" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
</Border>
|
||||
|
||||
<TextBlock Text="CALL targets" Margin="0,10,0,4" Foreground="#8896A0" />
|
||||
<Border Background="#091017" BorderBrush="#1A2730" BorderThickness="1" CornerRadius="4" Padding="8,6">
|
||||
<SelectableTextBlock Text="{Binding SelectedCandidate.CallTargetsDisplay}" FontFamily="Cascadia Mono, Consolas, monospace" TextWrapping="Wrap" />
|
||||
</Border>
|
||||
|
||||
<TextBlock Text="push site" Margin="0,10,0,4" Foreground="#8896A0" />
|
||||
<SelectableTextBlock Text="{Binding SelectedCandidate.PushSiteVa}" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
<!-- ───────────── DISCOVER BY CLASS (RTTI) TAB ───────────── -->
|
||||
<TabItem Header="Discover by class">
|
||||
<Grid RowDefinitions="Auto,Auto,*" Margin="0,8,0,0">
|
||||
|
||||
<Border Grid.Row="0"
|
||||
Padding="12"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto" RowDefinitions="Auto">
|
||||
<TextBlock Grid.Column="0" Text="class name:" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding SearchClass, Mode=TwoWay}"
|
||||
VerticalAlignment="Center" />
|
||||
<Button Grid.Column="2"
|
||||
Content="Find vtable methods"
|
||||
Margin="14,0,0,0"
|
||||
IsEnabled="{Binding CanSearchClass}"
|
||||
Click="OnSearchClassClick" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Row="1"
|
||||
Margin="0,10,0,10"
|
||||
Padding="12,10"
|
||||
CornerRadius="10"
|
||||
Background="#091017"
|
||||
BorderBrush="#1A2730"
|
||||
BorderThickness="1">
|
||||
<SelectableTextBlock Text="{Binding ClassDiscoveryStatus}" TextWrapping="Wrap" Foreground="#D6DDE3" />
|
||||
</Border>
|
||||
|
||||
<Grid Grid.Row="2" ColumnDefinitions="*,12,420">
|
||||
|
||||
<Border Grid.Column="0"
|
||||
Padding="0"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1">
|
||||
<ListBox ItemsSource="{Binding VtableMethods}"
|
||||
SelectedItem="{Binding SelectedVtableMethod, Mode=TwoWay}"
|
||||
SelectionMode="Single">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="local:VtableMethodRow">
|
||||
<Border BorderBrush="#1A2730"
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="14,8">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Grid.Column="0">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding Slot}"
|
||||
FontFamily="Cascadia Mono, Consolas, monospace"
|
||||
Foreground="#56646D"
|
||||
Width="40" />
|
||||
<TextBlock Text="{Binding Va}"
|
||||
FontFamily="Cascadia Mono, Consolas, monospace"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="{Binding AccentBrush}" />
|
||||
<TextBlock Text=" "/>
|
||||
<TextBlock Text="{Binding Summary}" Foreground="#A8B2BB" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding CallTargetsDisplay}"
|
||||
Margin="40,2,0,0"
|
||||
FontFamily="Cascadia Mono, Consolas, monospace"
|
||||
FontSize="11"
|
||||
Foreground="#56646D"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1"
|
||||
Content="Promote"
|
||||
VerticalAlignment="Center"
|
||||
Margin="10,0,0,0"
|
||||
Click="OnPromoteVtableMethod" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Column="2"
|
||||
Padding="14"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1">
|
||||
<ScrollViewer>
|
||||
<StackPanel>
|
||||
<TextBlock Text="Vtable method" FontSize="14" FontWeight="SemiBold" Foreground="#26C1A6" />
|
||||
<TextBlock Text="Find a class, then click a slot to inspect."
|
||||
Margin="0,4,0,0"
|
||||
IsVisible="{Binding !HasVtableSelection}"
|
||||
Foreground="#8896A0" />
|
||||
|
||||
<StackPanel IsVisible="{Binding HasVtableSelection}" Margin="0,8,0,0">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding SelectedVtableMethod.Slot}"
|
||||
FontFamily="Cascadia Mono, Consolas, monospace"
|
||||
Foreground="#56646D" />
|
||||
<TextBlock Text=" " />
|
||||
<SelectableTextBlock Text="{Binding SelectedVtableMethod.Va}"
|
||||
FontFamily="Cascadia Mono, Consolas, monospace"
|
||||
FontSize="14"
|
||||
FontWeight="SemiBold" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding SelectedVtableMethod.Summary}" Margin="0,6,0,0" />
|
||||
|
||||
<TextBlock Text="prologue (8 bytes)" Margin="0,10,0,4" Foreground="#8896A0" />
|
||||
<Border Background="#091017" BorderBrush="#1A2730" BorderThickness="1" CornerRadius="4" Padding="8,6">
|
||||
<SelectableTextBlock Text="{Binding SelectedVtableMethod.PrologueDisplay}" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
</Border>
|
||||
|
||||
<TextBlock Text="CALL targets" Margin="0,10,0,4" Foreground="#8896A0" />
|
||||
<Border Background="#091017" BorderBrush="#1A2730" BorderThickness="1" CornerRadius="4" Padding="8,6">
|
||||
<SelectableTextBlock Text="{Binding SelectedVtableMethod.CallTargetsDisplay}" FontFamily="Cascadia Mono, Consolas, monospace" TextWrapping="Wrap" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
|
||||
<Border Grid.Row="3"
|
||||
Padding="12"
|
||||
CornerRadius="12"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
BorderThickness="1"
|
||||
Margin="0,10,0,0">
|
||||
<Grid ColumnDefinitions="*,Auto,Auto">
|
||||
<StackPanel Grid.Column="0" VerticalAlignment="Center">
|
||||
<SelectableTextBlock Text="{Binding StatusText}" />
|
||||
<StackPanel Orientation="Horizontal" Margin="0,4,0,0">
|
||||
<TextBlock Text="{Binding CountsDisplay}" Foreground="#8896A0" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,2,0,0">
|
||||
<TextBlock Text="{Binding DiffDisplay}" Foreground="#8896A0" />
|
||||
<TextBlock Text=" • SHA-256: " Foreground="#56646D" Margin="8,0,0,0" />
|
||||
<TextBlock Text="{Binding Sha256Display}" Foreground="#56646D" FontFamily="Cascadia Mono, Consolas, monospace" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
<TextBox Grid.Column="1" Text="{Binding ManifestPath, Mode=TwoWay}" Width="320" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<Button Grid.Column="2" Content="Save Manifest" VerticalAlignment="Center" IsEnabled="{Binding CanSave}" Click="OnSaveClick" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
</Grid>
|
||||
</Window>
|
||||
283
tools/HookResolver.UI/MainWindow.axaml.cs
Normal file
283
tools/HookResolver.UI/MainWindow.axaml.cs
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using RynthCore.HookResolver.Core.Diff;
|
||||
using RynthCore.HookResolver.Core.Discovery;
|
||||
using RynthCore.HookResolver.Core.Offline;
|
||||
using RynthCore.HookResolver.Core.Resolution;
|
||||
using RynthCore.HookResolver.Core.Symbols;
|
||||
using Manifest = RynthCore.HookManifest.Schema.HookManifest;
|
||||
|
||||
namespace RynthCore.HookResolver.UI;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
private readonly MainViewModel _vm = new();
|
||||
private readonly List<HookManifestEntry> _promotedEntries = new();
|
||||
private Manifest? _lastManifest;
|
||||
private AcClientImage? _cachedImage;
|
||||
private CancellationTokenSource? _cts;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
DataContext = _vm;
|
||||
}
|
||||
|
||||
private async void OnBrowseAcClient(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Choose acclient.exe",
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter =
|
||||
[
|
||||
new FilePickerFileType("AC client executable") { Patterns = ["acclient.exe", "*.exe"] }
|
||||
]
|
||||
});
|
||||
if (files.Count > 0)
|
||||
{
|
||||
string? path = files[0].TryGetLocalPath();
|
||||
if (!string.IsNullOrEmpty(path)) _vm.AcClientPath = path;
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnBrowseLog(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Choose RynthCore.log",
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter =
|
||||
[
|
||||
new FilePickerFileType("RynthCore log") { Patterns = ["*.log", "*.*"] }
|
||||
]
|
||||
});
|
||||
if (files.Count > 0)
|
||||
{
|
||||
string? path = files[0].TryGetLocalPath();
|
||||
if (!string.IsNullOrEmpty(path)) _vm.LogPath = path;
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnResolveClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
_cts?.Cancel();
|
||||
_cts = new CancellationTokenSource();
|
||||
var ct = _cts.Token;
|
||||
|
||||
var symbols = AllSymbols.Default;
|
||||
_vm.BeginResolve(symbols.Count);
|
||||
|
||||
AcClientImage? image = null;
|
||||
try
|
||||
{
|
||||
image = await AcClientImageLoader.LoadAsync(_vm.AcClientPath, ct);
|
||||
_cachedImage = image;
|
||||
_vm.Sha256Display = image.Input.Sha256;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_vm.EndResolve(false, $"Load failed: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
IReadOnlyDictionary<string, EngineResolution> engineLog;
|
||||
try
|
||||
{
|
||||
engineLog = await EngineLogParser.ParseAsync(_vm.LogPath, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
engineLog = new Dictionary<string, EngineResolution>();
|
||||
_vm.StatusText = $"Log parse warning: {ex.Message}";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await foreach (var entry in HookResolveOrchestrator.ResolveAsync(image, symbols, ct))
|
||||
{
|
||||
engineLog.TryGetValue(entry.SymbolId, out var engineRes);
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
_vm.AddRow(new HookRow(entry, engineRes)));
|
||||
}
|
||||
|
||||
// Re-attach anything promoted from the Discover tabs so a re-resolve
|
||||
// doesn't drop it.
|
||||
foreach (var promoted in _promotedEntries)
|
||||
_vm.AddRow(new HookRow(promoted, null));
|
||||
|
||||
_lastManifest = ManifestBuilder.Compose(image.Input, BuildEntries());
|
||||
string logNote = engineLog.Count > 0
|
||||
? $" • {engineLog.Count} engine log entries compared."
|
||||
: " • (no engine log found at the configured path)";
|
||||
_vm.EndResolve(true, $"Done. Manifest ready ({image.Input.Sha256[..12]}…).{logNote}");
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_vm.EndResolve(false, "Cancelled.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_vm.EndResolve(false, $"Resolve failed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<HookManifestEntry> BuildEntries()
|
||||
{
|
||||
foreach (var row in _vm.Hooks)
|
||||
yield return row.Entry;
|
||||
}
|
||||
|
||||
private void PromoteEntry(string symbolId, int va, int rva, FunctionSnapshot snap, string reason)
|
||||
{
|
||||
if (_promotedEntries.Exists(e => e.Address?.Va == va))
|
||||
{
|
||||
_vm.StatusText = $"Already promoted: 0x{va:X8}.";
|
||||
return;
|
||||
}
|
||||
|
||||
var entry = new HookManifestEntry
|
||||
{
|
||||
SymbolId = symbolId,
|
||||
Status = ResolutionStatus.Resolved,
|
||||
Address = new ResolvedAddress(va, rva),
|
||||
PatternId = "promoted",
|
||||
MatchedCandidates = 1,
|
||||
ChosenCandidateReason = reason,
|
||||
Snapshot = snap
|
||||
};
|
||||
|
||||
_promotedEntries.Add(entry);
|
||||
_vm.AddRow(new HookRow(entry, null));
|
||||
|
||||
if (_cachedImage is not null)
|
||||
{
|
||||
_lastManifest = ManifestBuilder.Compose(_cachedImage.Input, BuildEntries());
|
||||
_vm.CanSave = true;
|
||||
}
|
||||
|
||||
_vm.StatusText = $"Promoted {symbolId} → manifest now has {_vm.Hooks.Count} entries (Save to write).";
|
||||
}
|
||||
|
||||
private void OnPromoteStringCandidate(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (sender is Control { DataContext: DiscoveryCandidateRow row })
|
||||
{
|
||||
string literal = _vm.SearchLiteral.Trim();
|
||||
var c = row.Candidate;
|
||||
PromoteEntry(
|
||||
$"discovered.str:{literal}@0x{c.Va:X8}",
|
||||
c.Va, c.Rva, c.Snapshot,
|
||||
$"promoted from string-ref '{literal}' (push @ 0x{c.PushSiteVa:X8})");
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPromoteVtableMethod(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (sender is Control { DataContext: VtableMethodRow row })
|
||||
{
|
||||
string cls = _vm.SearchClass.Trim();
|
||||
var c = row.Candidate;
|
||||
int rva = c.Va - (_cachedImage?.View.ImageBase ?? 0x00400000);
|
||||
PromoteEntry(
|
||||
$"discovered.vt:{cls}[{c.SlotIndex}]@0x{c.Va:X8}",
|
||||
c.Va, rva, c.Snapshot,
|
||||
$"promoted from {cls} vtable slot {c.SlotIndex} (vtable 0x{c.VtableVa:X8})");
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnSearchClassClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
_vm.IsVtableDiscovering = true;
|
||||
_vm.VtableMethods.Clear();
|
||||
_vm.SelectedVtableMethod = null;
|
||||
_vm.ClassDiscoveryStatus = $"Loading acclient.exe and walking RTTI for '{_vm.SearchClass}'…";
|
||||
|
||||
try
|
||||
{
|
||||
if (_cachedImage is null || _cachedImage.Input.Path != _vm.AcClientPath)
|
||||
{
|
||||
_cachedImage = await AcClientImageLoader.LoadAsync(_vm.AcClientPath);
|
||||
_vm.Sha256Display = _cachedImage.Input.Sha256;
|
||||
}
|
||||
|
||||
string className = _vm.SearchClass.Trim();
|
||||
var result = await Task.Run(() => VtableDiscoveryService.Discover(_cachedImage!, className));
|
||||
|
||||
_vm.ClassDiscoveryStatus = result.Summary;
|
||||
foreach (var method in result.Methods)
|
||||
_vm.VtableMethods.Add(new VtableMethodRow(method));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_vm.ClassDiscoveryStatus = $"Search failed: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
_vm.IsVtableDiscovering = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnSearchClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
_vm.IsDiscovering = true;
|
||||
_vm.DiscoveryCandidates.Clear();
|
||||
_vm.SelectedCandidate = null;
|
||||
_vm.DiscoveryStatus = $"Loading acclient.exe and searching for '{_vm.SearchLiteral}'…";
|
||||
|
||||
try
|
||||
{
|
||||
if (_cachedImage is null || _cachedImage.Input.Path != _vm.AcClientPath)
|
||||
{
|
||||
_cachedImage = await AcClientImageLoader.LoadAsync(_vm.AcClientPath);
|
||||
_vm.Sha256Display = _cachedImage.Input.Sha256;
|
||||
}
|
||||
|
||||
var request = new StringDiscoveryRequest(
|
||||
_vm.SearchLiteral.Trim(),
|
||||
_vm.SelectedPreset.Bytes,
|
||||
_vm.MaxBackward,
|
||||
_vm.LooseMatch,
|
||||
_vm.SelectedReferenceMode);
|
||||
|
||||
var result = await Task.Run(() => StringDiscoveryService.Discover(_cachedImage!, request));
|
||||
|
||||
_vm.DiscoveryStatus = result.Summary;
|
||||
foreach (var candidate in result.Candidates)
|
||||
_vm.DiscoveryCandidates.Add(new DiscoveryCandidateRow(candidate));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_vm.DiscoveryStatus = $"Search failed: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
_vm.IsDiscovering = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnSaveClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (_lastManifest is null)
|
||||
{
|
||||
_vm.StatusText = "Nothing to save — run Resolve first.";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await ManifestBuilder.WriteAsync(_lastManifest, _vm.ManifestPath);
|
||||
_vm.StatusText = $"Saved → {_vm.ManifestPath}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_vm.StatusText = $"Save failed: {ex.Message}";
|
||||
}
|
||||
}
|
||||
}
|
||||
16
tools/HookResolver.UI/Program.cs
Normal file
16
tools/HookResolver.UI/Program.cs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
using Avalonia;
|
||||
|
||||
namespace RynthCore.HookResolver.UI;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
[System.STAThread]
|
||||
public static int Main(string[] args)
|
||||
=> BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
.WithInterFont()
|
||||
.LogToTrace();
|
||||
}
|
||||
28
tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj
Normal file
28
tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||
<RootNamespace>RynthCore.HookResolver.UI</RootNamespace>
|
||||
<AssemblyName>RynthCore.HookResolver.UI</AssemblyName>
|
||||
<LangVersion>latest</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="11.2.3" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HookResolver.Core\RynthCore.HookResolver.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\RynthCore.HookManifest\RynthCore.HookManifest.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
49
tools/HookResolver.UI/VtableMethodRow.cs
Normal file
49
tools/HookResolver.UI/VtableMethodRow.cs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
using System.Linq;
|
||||
using System.Text;
|
||||
using Avalonia.Media;
|
||||
using RynthCore.HookManifest.Schema;
|
||||
using RynthCore.HookResolver.Core.Discovery;
|
||||
|
||||
namespace RynthCore.HookResolver.UI;
|
||||
|
||||
public sealed class VtableMethodRow
|
||||
{
|
||||
public VtableMethodRow(VtableMethodCandidate candidate)
|
||||
{
|
||||
Candidate = candidate;
|
||||
Slot = $"[{candidate.SlotIndex:D2}]";
|
||||
Va = $"0x{candidate.Va:X8}";
|
||||
|
||||
var s = candidate.Snapshot;
|
||||
Summary = $"{s.LengthBytes} bytes • {s.InstructionCount} instr • " +
|
||||
(s.EndsAtReturn ? "ends RET" : "no RET");
|
||||
PrologueDisplay = FormatHex(s.PrologueHex);
|
||||
CallTargetsDisplay = s.CallTargets.Count == 0
|
||||
? "(none)"
|
||||
: string.Join(" ", s.CallTargets.Take(5).Select(ct => $"+0x{ct.Offset:X3}→0x{ct.Va:X8}"));
|
||||
|
||||
AccentBrush = s.EndsAtReturn && s.LengthBytes > 8
|
||||
? new SolidColorBrush(Color.Parse("#26C1A6"))
|
||||
: new SolidColorBrush(Color.Parse("#E0B040"));
|
||||
}
|
||||
|
||||
public VtableMethodCandidate Candidate { get; }
|
||||
public FunctionSnapshot Snapshot => Candidate.Snapshot;
|
||||
public string Slot { get; }
|
||||
public string Va { get; }
|
||||
public string Summary { get; }
|
||||
public string PrologueDisplay { get; }
|
||||
public string CallTargetsDisplay { get; }
|
||||
public IBrush AccentBrush { get; }
|
||||
|
||||
private static string FormatHex(string raw)
|
||||
{
|
||||
var sb = new StringBuilder(raw.Length + raw.Length / 2);
|
||||
for (int i = 0; i < raw.Length; i += 2)
|
||||
{
|
||||
if (i > 0) sb.Append(' ');
|
||||
sb.Append(raw, i, 2);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
17
tools/HookResolver.UI/app.manifest
Normal file
17
tools/HookResolver.UI/app.manifest
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="RynthCore.HookResolver.UI"/>
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
|
||||
<security>
|
||||
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
</assembly>
|
||||
28
tools/check-patterns.ps1
Normal file
28
tools/check-patterns.ps1
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<#
|
||||
.SYNOPSIS
|
||||
Pre-deploy / CI gate: verify every acclient.exe address pattern embedded in the engine
|
||||
source still resolves uniquely and correctly against the target client binary.
|
||||
|
||||
Exits 0 if all patterns verify, non-zero if any drifted (binary changed) or is wrong
|
||||
(transcription typo). Wire this into the deploy script or CI BEFORE publishing the engine,
|
||||
so a future AC patch / ACE rebuild can't silently ship a hook that falls back to a stale VA.
|
||||
|
||||
.PARAMETER AcClient
|
||||
Path to the acclient.exe to verify against. Defaults to the fingerprinted reference client.
|
||||
Point it at whatever binary the engine will actually be injected into.
|
||||
|
||||
.EXAMPLE
|
||||
pwsh tools\check-patterns.ps1
|
||||
pwsh tools\check-patterns.ps1 -AcClient "C:\Games\RynthCore\AcClient\acclient.exe"
|
||||
#>
|
||||
param(
|
||||
[string]$AcClient = "C:\Turbine\Asheron's Call\acclient.exe"
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $AcClient)) {
|
||||
Write-Error "acclient.exe not found at: $AcClient"
|
||||
exit 2
|
||||
}
|
||||
|
||||
python "$PSScriptRoot\pe_pattern.py" $AcClient CHECK
|
||||
exit $LASTEXITCODE
|
||||
173
tools/check_offthread_mutators.py
Normal file
173
tools/check_offthread_mutators.py
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
check_offthread_mutators.py - static guard against the off-thread AC-mutation
|
||||
AV class (the root of the entire 2026-06-11..13 crash week).
|
||||
|
||||
INVARIANT (hard-won): any engine code that mutates AC's internal state must run
|
||||
on AC's main thread. The established pattern in Compatibility/*Hooks.cs is:
|
||||
|
||||
public static bool DoThing(...) {
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueDoThing(...); // marshal
|
||||
... call the native AC delegate directly ... // on main thread
|
||||
}
|
||||
|
||||
Every off-thread AC mutator that slipped past this gate produced a corruption
|
||||
AV: SetSelectedObject (0x460D1D UIElement UAF), ForceResetBusyCount, the
|
||||
CommandInterpreter movement calls, UseObject (CSequence), etc. SelectItem was
|
||||
the last holdout and it shipped because nothing CHECKED the invariant.
|
||||
|
||||
This tool checks it statically (read-only, stdlib-only, out-of-process):
|
||||
|
||||
CHECK A (precise, curation-free): every method that CALLS
|
||||
`AcMainThreadQueue.Enqueue...` must also contain
|
||||
`MainThreadGuard.IsOnMainThread` in the same method body. Catches a
|
||||
marshalled helper whose gate was removed/botched.
|
||||
|
||||
CHECK B (curated): every invocation of a known AC-STATE-MUTATOR native
|
||||
delegate (the hand-listed set below) must sit in a method that contains the
|
||||
gate - OR in an allow-listed context (the detour bodies and the
|
||||
AcMainThreadQueue drain executor, which run on the main thread by
|
||||
construction). Catches a NEW mutator added with no marshal at all (the
|
||||
SelectItem-before-74f6d8c situation).
|
||||
|
||||
Exit 0 = invariant holds, 1 = a violation (an AC mutator reachable off-thread),
|
||||
2 = could not read the source tree. Wire into CI next to the golden tests /
|
||||
pe_pattern gate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import os, re, sys
|
||||
|
||||
# Resolve the engine Compatibility dir relative to this script so it works both
|
||||
# locally (C:\Projects\RynthCore\tools\..) and in CI ($GITHUB_WORKSPACE\tools\..).
|
||||
# Override order: argv[1] > $RC_HOOKS_DIR > derived-from-script-location.
|
||||
_DERIVED_HOOKS = os.path.normpath(os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)), "..", "src", "RynthCore.Engine", "Compatibility"))
|
||||
HOOKS_DIR = (sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("-")
|
||||
else os.environ.get("RC_HOOKS_DIR") or _DERIVED_HOOKS)
|
||||
|
||||
# Curated AC-STATE-MUTATOR native delegate fields. Hand-maintained: add a field
|
||||
# here when a new hook calls an AC function that WRITES client state (selection,
|
||||
# item move/use, motion, combat-mode, busy count). Readers (Inq*/Get*) are NOT
|
||||
# listed - they have their own pointer-validation, not a thread gate.
|
||||
MUTATOR_DELEGATES = {
|
||||
"_setSelectedObject", "_useObject", "_useObjectOn", "_useWithTargetEvent",
|
||||
"_useEquippedItem", "_moveItemExternal", "_moveItemInternal",
|
||||
"_eventStackableMerge", "_addTextToScroll",
|
||||
"_setAutoRun", "_turnToHeading", "_stopCompletely", "_setMotion",
|
||||
"_changeCombatMode",
|
||||
"_sendShopEvent", # VendorTrade: gmVendorUI::SendShopEvent (vendor buy/sell + busy count)
|
||||
}
|
||||
GATE = "MainThreadGuard.IsOnMainThread"
|
||||
ENQUEUE = "AcMainThreadQueue.Enqueue"
|
||||
|
||||
# Pure off-thread PRODUCERS: Timer/pump callbacks that ONLY enqueue (never call an
|
||||
# AC mutator directly), so they legitimately lack the dual-mode IsOnMainThread gate.
|
||||
# The marshalled AC call always runs on the main thread in AcMainThreadQueue.Drain*.
|
||||
# (file, method) pairs, each verified to do no off-thread AC mutation.
|
||||
ENQUEUE_PRODUCER_ALLOW = {
|
||||
("AutoIdService.cs", "DrainTick"), # appraisal: enqueues 0xC8, sent on main thread in DrainRequestIds
|
||||
}
|
||||
|
||||
# Methods that run on AC's main thread BY CONSTRUCTION and may call mutators
|
||||
# without a gate: the [UnmanagedCallersOnly] detour bodies (invoked by AC on its
|
||||
# own thread) and the hook install/probe/resolve scaffolding. Matched by name
|
||||
# substring or by an [UnmanagedCallersOnly] attribute on the method.
|
||||
ALLOW_METHOD_SUBSTR = ("Detour", "Install", "Initialize", "Probe", "Resolve",
|
||||
"Shutdown", "Uninstall")
|
||||
|
||||
|
||||
def split_methods(src):
|
||||
"""Yield (name, start_line, body_text, attrs_above) for each method via
|
||||
brace counting. attrs_above = the few lines immediately preceding the
|
||||
signature (to catch [UnmanagedCallersOnly])."""
|
||||
lines = src.splitlines()
|
||||
sig = re.compile(
|
||||
r"^\s*(?:\[[^\]]*\]\s*)*(?:public|private|internal|protected)\b[^;=]*\b([A-Za-z_]\w*)\s*\([^;]*\)\s*$")
|
||||
i = 0
|
||||
n = len(lines)
|
||||
while i < n:
|
||||
m = sig.match(lines[i])
|
||||
# signature may end with the opening brace on the next non-blank line
|
||||
if m:
|
||||
name = m.group(1)
|
||||
# find opening brace
|
||||
j = i + 1
|
||||
while j < n and lines[j].strip() == "":
|
||||
j += 1
|
||||
if j < n and lines[j].strip().startswith("{"):
|
||||
depth = 0
|
||||
body = []
|
||||
k = j
|
||||
started = False
|
||||
while k < n:
|
||||
depth += lines[k].count("{") - lines[k].count("}")
|
||||
body.append(lines[k])
|
||||
if lines[k].count("{") > 0:
|
||||
started = True
|
||||
if started and depth <= 0:
|
||||
break
|
||||
k += 1
|
||||
attrs = "\n".join(lines[max(0, i - 4):i])
|
||||
yield name, i + 1, "\n".join(body), attrs
|
||||
i = k + 1
|
||||
continue
|
||||
i += 1
|
||||
|
||||
|
||||
def is_allowed(name, attrs):
|
||||
if "UnmanagedCallersOnly" in attrs:
|
||||
return True
|
||||
return any(s in name for s in ALLOW_METHOD_SUBSTR)
|
||||
|
||||
|
||||
def main():
|
||||
print(f"=== off-thread AC-mutator gate check ===\nscanning: {HOOKS_DIR}")
|
||||
if not os.path.isdir(HOOKS_DIR):
|
||||
print(f"cannot read {HOOKS_DIR}")
|
||||
return 2
|
||||
|
||||
violations = []
|
||||
checked_a = checked_b = 0
|
||||
|
||||
deleg_call = re.compile(r"(" + "|".join(re.escape(d) for d in MUTATOR_DELEGATES) + r")\s*\(")
|
||||
|
||||
for fn in sorted(os.listdir(HOOKS_DIR)):
|
||||
if not fn.endswith(".cs"):
|
||||
continue
|
||||
path = os.path.join(HOOKS_DIR, fn)
|
||||
src = open(path, encoding="utf-8", errors="replace").read()
|
||||
# AcMainThreadQueue.cs defines Enqueue* and IS the main-thread drain
|
||||
# executor - exempt it from both checks.
|
||||
is_queue = fn == "AcMainThreadQueue.cs"
|
||||
for name, line, body, attrs in split_methods(src):
|
||||
gated = GATE in body
|
||||
allowed = is_allowed(name, attrs) or is_queue
|
||||
|
||||
# CHECK A: calls Enqueue but lacks the gate (unless it's a known pure producer).
|
||||
if (ENQUEUE in body) and not gated and not is_queue \
|
||||
and (fn, name) not in ENQUEUE_PRODUCER_ALLOW:
|
||||
checked_a += 1
|
||||
violations.append((fn, line, name, "calls AcMainThreadQueue.Enqueue* without a MainThreadGuard gate"))
|
||||
|
||||
# CHECK B: invokes a curated mutator delegate without the gate.
|
||||
if not allowed and deleg_call.search(body) and not gated:
|
||||
hit = deleg_call.search(body).group(1)
|
||||
checked_b += 1
|
||||
violations.append((fn, line, name, f"invokes AC-mutator delegate {hit}() without a MainThreadGuard gate"))
|
||||
|
||||
if violations:
|
||||
for fn, line, name, why in violations:
|
||||
print(f" [VIOLATION] {fn}:{line} {name}() - {why}")
|
||||
print(f"\nFAIL: {len(violations)} AC mutator(s) reachable off-thread. "
|
||||
f"Gate them on MainThreadGuard.IsOnMainThread() + marshal via AcMainThreadQueue, "
|
||||
f"or add the method to the allow-list if it is a main-thread-only detour.")
|
||||
return 1
|
||||
|
||||
print(f"PASS: every marshalled helper is gated and every curated AC-mutator "
|
||||
f"delegate is invoked behind the main-thread gate.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
412
tools/pe_pattern.py
Normal file
412
tools/pe_pattern.py
Normal file
|
|
@ -0,0 +1,412 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Offline byte-pattern extractor / uniqueness verifier for acclient.exe hook hardening.
|
||||
|
||||
Verifies over the EXACT window the engine's AcClientModule.TryReadTextSection builds at
|
||||
runtime: the live virtual image from RVA 0x1000, length min(SizeOfImage-0x1000, 0x400000).
|
||||
That window spans .text AND the start of .rdata/.data, so "unique here" == "unique at runtime"
|
||||
(stronger than checking .text alone). For each (symbol, VA) it:
|
||||
1. maps VA -> window offset,
|
||||
2. cuts a prologue window, wildcarding rel32 operands of E8/E9 (call/jmp) and 0F 8x (jcc),
|
||||
3. finds the SHORTEST prefix that occurs exactly once in the window,
|
||||
4. confirms that single match lands at the requested VA,
|
||||
5. prints a ready-to-paste C# byte?[] literal.
|
||||
|
||||
Usage: python pe_pattern.py "<path-to-acclient.exe>" [group|ALL]
|
||||
Only FUNCTION (.text) VAs belong here. Data/global addresses (.data/.rdata singletons,
|
||||
RecvFrom slot, s_NullBuffer, selection globals) are Phase B — string/vtable discovery, not
|
||||
.text pattern scan.
|
||||
"""
|
||||
import sys, struct, re, os, glob
|
||||
|
||||
DEFAULT_TEXT_RVA = 0x1000
|
||||
MAX_TEXT_BYTES = 0x400000
|
||||
SUSPICIOUS = 0x500000
|
||||
|
||||
def read_window(path):
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
e = struct.unpack_from("<I", data, 0x3C)[0]
|
||||
coff = e + 4
|
||||
num_sec = struct.unpack_from("<H", data, coff + 2)[0]
|
||||
size_opt = struct.unpack_from("<H", data, coff + 16)[0]
|
||||
opt = coff + 20
|
||||
if struct.unpack_from("<H", data, opt)[0] != 0x10B:
|
||||
raise SystemExit("expected PE32 (x86)")
|
||||
image_base = struct.unpack_from("<I", data, opt + 28)[0]
|
||||
size_of_image = struct.unpack_from("<I", data, opt + 56)[0]
|
||||
sec_tbl = opt + size_opt
|
||||
virt = bytearray(size_of_image)
|
||||
for i in range(num_sec):
|
||||
b = sec_tbl + i * 40
|
||||
vaddr = struct.unpack_from("<I", data, b + 12)[0]
|
||||
rawsize = struct.unpack_from("<I", data, b + 16)[0]
|
||||
rawptr = struct.unpack_from("<I", data, b + 20)[0]
|
||||
end = min(vaddr + rawsize, size_of_image)
|
||||
chunk = data[rawptr:rawptr + (end - vaddr)]
|
||||
virt[vaddr:vaddr + len(chunk)] = chunk
|
||||
raw_text = size_of_image - DEFAULT_TEXT_RVA
|
||||
if raw_text <= 0 or raw_text > SUSPICIOUS:
|
||||
textsize = min(max(0, raw_text), MAX_TEXT_BYTES)
|
||||
else:
|
||||
textsize = min(raw_text, MAX_TEXT_BYTES)
|
||||
window = bytes(virt[DEFAULT_TEXT_RVA:DEFAULT_TEXT_RVA + textsize])
|
||||
return window, image_base + DEFAULT_TEXT_RVA
|
||||
|
||||
def wildcard_window(buf, off, n=160):
|
||||
win = list(buf[off:off + n])
|
||||
pat = list(win)
|
||||
i = 0
|
||||
while i < len(win):
|
||||
b = win[i]
|
||||
if b in (0xE8, 0xE9):
|
||||
for k in range(1, 5):
|
||||
if i + k < len(pat): pat[i + k] = None
|
||||
i += 5
|
||||
elif b == 0x0F and i + 1 < len(win) and 0x80 <= win[i + 1] <= 0x8F:
|
||||
for k in range(2, 6):
|
||||
if i + k < len(pat): pat[i + k] = None
|
||||
i += 6
|
||||
else:
|
||||
i += 1
|
||||
return pat
|
||||
|
||||
def matches(text_b, pat, limit=6):
|
||||
first_wc = next((k for k, p in enumerate(pat) if p is None), len(pat))
|
||||
if first_wc == 0:
|
||||
return [-2]
|
||||
prefix = bytes(pat[:first_wc])
|
||||
out, start = [], 0
|
||||
while True:
|
||||
idx = text_b.find(prefix, start)
|
||||
if idx < 0: break
|
||||
ok = all(pat[j] is None or text_b[idx + j] == pat[j] for j in range(first_wc, len(pat)))
|
||||
if ok:
|
||||
out.append(idx)
|
||||
if len(out) > limit: break
|
||||
start = idx + 1
|
||||
return out
|
||||
|
||||
def shortest_unique(text_b, full_pat, text_base, lo=8):
|
||||
for L in range(lo, len(full_pat) + 1):
|
||||
pat = full_pat[:L]
|
||||
while pat and pat[-1] is None:
|
||||
pat = pat[:-1]
|
||||
if not pat: continue
|
||||
ms = matches(text_b, pat)
|
||||
if len(ms) == 1:
|
||||
return pat, text_base + ms[0]
|
||||
ms = matches(text_b, full_pat)
|
||||
return full_pat, (text_base + ms[0] if ms else -1)
|
||||
|
||||
def cs(pat):
|
||||
return "[ " + ", ".join("null" if p is None else f"0x{p:02X}" for p in pat) + " ]"
|
||||
|
||||
# FUNCTION (.text) VAs only, grouped by the engine hook file that binds them.
|
||||
# Dups across files (same VA) are noted; resolve once in the catalog.
|
||||
GROUPS = {
|
||||
"ClientObjectHooks": [
|
||||
("GetWeenieObject", 0x005583F0), ("GetNumContainedItems", 0x0058CCE0),
|
||||
("GetNumContainedContainers", 0x0058CCF0), ("GetObjectNameStatic", 0x0058F840),
|
||||
("GetObjectNameInstance", 0x0058F510), ("InqType", 0x0058D700),
|
||||
("InqInt", 0x00590C20), ("InqFloat", 0x00590CD0), ("InqInt64", 0x00590C70),
|
||||
("InqAttribute2ndBaseLevel", 0x00592D20), ("InqBool", 0x00590CA0),
|
||||
("InqString", 0x005919F0), ("GetCombatSystem", 0x0056B210),
|
||||
("ObjectIsAttackable", 0x0056B340), ("IsSpellKnown", 0x0058FCF0),
|
||||
("InqSkillLevel", 0x00593380), ("InqSkillAdvancementClass", 0x00592B70),
|
||||
("InqAttribute", 0x00592700), ("GetVitaeValue", 0x0058FE80),
|
||||
],
|
||||
"ClientHelperHooks": [
|
||||
("SetSelectedObject", 0x0058D110), ("GetAcPlugin", 0x0055A740),
|
||||
("UseObjectOn", 0x0055A8C0), ("UseEquippedItem", 0x0055A910),
|
||||
("MoveItemExternal", 0x0055A9E0), ("MoveItemInternal", 0x0055AA00),
|
||||
("Event_StackableMerge", 0x006ACDD0), ("Event_GiveObjectRequest", 0x006ACA60),
|
||||
("ClientUISystem_UseObject", 0x00565750),
|
||||
("InqPlayerCoords", 0x00560E00), ("GetPlayerId", 0x0048E5F0),
|
||||
("AddTextToScroll", 0x005649F0), ("UseWithTargetEvent", 0x006AD3E0),
|
||||
("SendNotice_OpenSalvagePanel", 0x006AD4F0), ("gmSalvageUI_AddNewItem", 0x004CC020),
|
||||
("gmSalvageUI_Salvage", 0x004CC430), ("PStringBaseW_ctor", 0x00402730),
|
||||
("PStringBaseW_dtor", 0x004011B0),
|
||||
],
|
||||
"PlayerVitalsHooks": [
|
||||
("UpdateAttribute2nd", 0x00559900), ("UpdateAttribute2ndLevel", 0x00559920),
|
||||
("PrivateUpdateAttribute2nd", 0x00559B20), ("PrivateUpdateAttribute2ndLevel", 0x00559B50),
|
||||
("OnStatUpdatedInt", 0x0058ED50), ("InqAttribute2nd_struct", 0x005927F0),
|
||||
("SendNotice_PlayerDescReceived", 0x0047A200), ("InqAttribute2nd_uint", 0x00592D20),
|
||||
],
|
||||
"ClientCombatHooks": [
|
||||
("GetCombatSystem", 0x0056B210), ("SetRequestedAttackHeight", 0x0056D640),
|
||||
("StartAttackRequest", 0x0056CD90), ("EndAttackRequest", 0x0056CE30),
|
||||
("PlayerInReadyPosition", 0x0056C570), ("AutoTarget", 0x0056C9D0),
|
||||
("SendAttackHeightChanged", 0x006AAE10),
|
||||
],
|
||||
"CharacterManagementHooks": [
|
||||
("UIFlow_GetPersistantData", 0x0051DFB0), ("GetPlayerSystem", 0x0055E1D0),
|
||||
("LogOnCharacter", 0x00560600), ("CharacterSet_GetIdentity", 0x004E8B20),
|
||||
("CharacterSet_GetName", 0x004FE980), ("CharacterSet_GetGid", 0x004FE9B0),
|
||||
],
|
||||
"ChatCommandDispatcher": [
|
||||
("Event_Talk", 0x006A53E0), ("Event_Emote", 0x006A4F40),
|
||||
("Event_SoulEmote", 0x006A5320), ("Event_TalkDirectByName", 0x006A55A0),
|
||||
("Event_ChannelBroadcast", 0x006A4E50), ("PStringBaseC_ctor", 0x0048C3E0),
|
||||
("PStringBaseC_Clear", 0x004AB990),
|
||||
],
|
||||
"CombatActionHooks": [
|
||||
("Handle_Combat_QueryHealthResponse", 0x006AA900), ("CastSpell", 0x00568DE0),
|
||||
("GetMagicSystem", 0x00567C00), ("FreeHandsAndCastSpell", 0x00567C90),
|
||||
],
|
||||
"PlayerPhysicsHooks": [
|
||||
("CPhysicsObj_get_heading", 0x00512010), ("CPhysicsObj_set_heading", 0x00514C60),
|
||||
("CMotionInterp_get_max_speed", 0x005288C0),
|
||||
],
|
||||
"GameTickHooks": [
|
||||
("Client_UseTime", 0x00411FA0),
|
||||
],
|
||||
"TimeSyncHooks": [
|
||||
("ClientNet_HandleTimeSynch", 0x005448F0),
|
||||
],
|
||||
}
|
||||
|
||||
def best_pattern(text_b, text_base, va, off):
|
||||
"""Prefer a drift-tolerant wildcarded pattern; if template-siblings share it (the rel32
|
||||
call target being the only differentiator), fall back to a literal pattern. Returns
|
||||
(mode, pat) where mode is 'wild' | 'lit', or (None, None) if no unique prologue exists."""
|
||||
for mode in ("wild", "lit"):
|
||||
full = wildcard_window(text_b, off) if mode == "wild" else list(text_b[off:off + 160])
|
||||
pat, mva = shortest_unique(text_b, full, text_base)
|
||||
if len(matches(text_b, pat)) == 1 and mva == va:
|
||||
return mode, pat
|
||||
return None, None
|
||||
|
||||
# DATA/global addresses (.data/.rdata) — resolved by code-xref: find a unique .text site
|
||||
# that references the address as an absolute operand, wildcard the 4 operand bytes, and read
|
||||
# the address back from the matched operand at runtime. Robust if the global moves.
|
||||
GROUPS_DATA = [
|
||||
("CPlayerSystem", 0x0087119C), ("ClientUISystem", 0x00871354),
|
||||
("CommunicationSystem", 0x00870BE4), ("s_pCombatSystem", 0x0087166C),
|
||||
("CObjectMaint_s_pcInstance", 0x00842ADC), ("UIFlow", 0x0083E72C),
|
||||
("s_selected_id", 0x00871E54), ("s_previous_selected_id", 0x00871E58),
|
||||
("split_amount", 0x0081D7EC), ("total_stack", 0x0081D7F0),
|
||||
("PStringChar_s_NullBuffer", 0x008EF11C), ("PStringWide_s_NullBuffer", 0x00818340),
|
||||
("RecvFrom_slot", 0x007935AC),
|
||||
]
|
||||
|
||||
def _find_all(text_b, needle, limit=80):
|
||||
out, start = [], 0
|
||||
while True:
|
||||
i = text_b.find(needle, start)
|
||||
if i < 0: break
|
||||
out.append(i); start = i + 1
|
||||
if len(out) > limit: break
|
||||
return out
|
||||
|
||||
def data_xref(text_b, va):
|
||||
"""Unique .text code site referencing data VA as an absolute operand.
|
||||
Returns (pattern with the 4 operand bytes wildcarded, operand_offset) or None."""
|
||||
needle = struct.pack("<I", va & 0xFFFFFFFF)
|
||||
best = None
|
||||
for idx in _find_all(text_b, needle):
|
||||
for lead in (2, 1, 3, 5, 8, 12):
|
||||
if idx - lead < 0: continue
|
||||
done = False
|
||||
for tail in range(0, 26, 2):
|
||||
pat = list(text_b[idx - lead:idx]) + [None] * 4 + list(text_b[idx + 4:idx + 4 + tail])
|
||||
ms = matches(text_b, pat)
|
||||
if len(ms) == 1:
|
||||
if struct.unpack_from("<I", text_b, ms[0] + lead)[0] == (va & 0xFFFFFFFF):
|
||||
if best is None or len(pat) < best[0]:
|
||||
best = (len(pat), pat, lead)
|
||||
done = True
|
||||
break
|
||||
if done: break
|
||||
return (best[1], best[2]) if best else None
|
||||
|
||||
def process_data(text_b):
|
||||
print("=== DATA (.data/.rdata globals via code-xref) ===")
|
||||
ok = bad = 0
|
||||
for name, va in GROUPS_DATA:
|
||||
res = data_xref(text_b, va)
|
||||
if res is None:
|
||||
bad += 1
|
||||
print(f"[!! ] {name:28} 0x{va:08X} no unique code-xref found"); continue
|
||||
pat, off = res
|
||||
ok += 1
|
||||
print(f"[OK ] {name:28} 0x{va:08X} operandOffset={off} len={len(pat)}")
|
||||
print(f" {cs(pat)}")
|
||||
print(f"\nData xrefs found: {ok}/{ok + bad}")
|
||||
return ok, bad
|
||||
|
||||
def _parse_vas(args):
|
||||
out = []
|
||||
for a in args:
|
||||
a = a.strip().rstrip(",")
|
||||
if a:
|
||||
out.append(int(a, 16))
|
||||
return out
|
||||
|
||||
def process_gen(text_b, text_base, vas):
|
||||
"""Ad-hoc: cut a unique FUNCTION pattern for each VA passed on the command line
|
||||
(read-only; does NOT touch GROUPS). For converting a fixed-VA+VerifyBytes hook to
|
||||
HookResolver.Resolve without first editing this file. Prints a paste-ready byte?[]."""
|
||||
print("=== GEN (ad-hoc function patterns) ===")
|
||||
for va in vas:
|
||||
off = va - text_base
|
||||
if off < 0 or off >= len(text_b):
|
||||
print(f"[SKIP] 0x{va:08X} not in window"); continue
|
||||
mode, pat = best_pattern(text_b, text_base, va, off)
|
||||
if pat is None:
|
||||
print(f"[TB!] 0x{va:08X} no unique prologue in 160B -> TIER-B (keep fixed VA + VerifyBytes)")
|
||||
continue
|
||||
print(f"[{'OK ' if mode == 'wild' else 'LIT'}] 0x{va:08X} unique len={len(pat)} mode={mode}")
|
||||
print(f" {cs(pat)}")
|
||||
|
||||
def process_gendata(text_b, vas):
|
||||
"""Ad-hoc: cut a code-xref pattern for each DATA/global VA on the command line."""
|
||||
print("=== GENDATA (ad-hoc data globals via code-xref) ===")
|
||||
for va in vas:
|
||||
res = data_xref(text_b, va)
|
||||
if res is None:
|
||||
print(f"[!! ] 0x{va:08X} no unique code-xref found"); continue
|
||||
pat, off = res
|
||||
print(f"[OK ] 0x{va:08X} operandOffset={off} len={len(pat)}")
|
||||
print(f" {cs(pat)}")
|
||||
|
||||
def process(text_b, text_base, group):
|
||||
print(f"=== {group} ===")
|
||||
ok = bad = 0
|
||||
for name, va in GROUPS[group]:
|
||||
off = va - text_base
|
||||
if off < 0 or off >= len(text_b):
|
||||
print(f"[SKIP] {name:34} 0x{va:08X} not in window"); bad += 1; continue
|
||||
mode, pat = best_pattern(text_b, text_base, va, off)
|
||||
if pat is None:
|
||||
bad += 1
|
||||
print(f"[TB!] {name:34} VA=0x{va:08X} no unique prologue in 160B -> TIER-B (fixed VA + VerifyBytes)")
|
||||
continue
|
||||
ok += 1
|
||||
print(f"[{'OK ' if mode == 'wild' else 'LIT'}] {name:34} VA=0x{va:08X} unique len={len(pat)} mode={mode}")
|
||||
print(f" {cs(pat)}")
|
||||
return ok, bad
|
||||
|
||||
# ── CHECK mode: verify the patterns ACTUALLY EMBEDDED in the engine source still resolve
|
||||
# uniquely + correctly against a given acclient.exe. Catches binary drift AND transcription
|
||||
# typos before deploy. Exits non-zero on any failure (usable as a CI / pre-deploy gate).
|
||||
def _compat_dir():
|
||||
return os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||
"src", "RynthCore.Engine", "Compatibility")
|
||||
|
||||
def parse_engine_patterns():
|
||||
srcs = {}
|
||||
for f in glob.glob(os.path.join(_compat_dir(), "*.cs")):
|
||||
with open(f, "r", encoding="utf-8") as fh:
|
||||
# Strip // line comments so commas / brackets inside an inline disasm
|
||||
# comment (e.g. `0x84, 0xC0 // MOV AL,[ESP+4]; TEST AL,AL`) can't corrupt
|
||||
# the byte?[] split or truncate the array match at a `]` inside the comment.
|
||||
srcs[f] = re.sub(r'//[^\n]*', '', fh.read())
|
||||
consts = {}
|
||||
for s in srcs.values():
|
||||
for m in re.finditer(r'const\s+u?int\s+(\w+)\s*=\s*[^;]*?0x([0-9A-Fa-f]+)', s):
|
||||
consts[m.group(1)] = int(m.group(2), 16)
|
||||
patterns = {}
|
||||
for s in srcs.values():
|
||||
for m in re.finditer(r'byte\?\[\]\s+(\w+)\s*=\s*\[(.*?)\]\s*;', s, re.DOTALL):
|
||||
pat, ok = [], True
|
||||
for t in m.group(2).split(','):
|
||||
t = t.strip()
|
||||
if not t:
|
||||
continue
|
||||
if t == 'null':
|
||||
pat.append(None)
|
||||
elif re.fullmatch(r'0x[0-9A-Fa-f]+', t):
|
||||
pat.append(int(t, 16))
|
||||
else:
|
||||
ok = False; break
|
||||
if ok and pat:
|
||||
patterns[m.group(1)] = pat
|
||||
def resolve_va(tail):
|
||||
for name, val in consts.items():
|
||||
if re.search(r'\b' + re.escape(name) + r'\b', tail):
|
||||
return val
|
||||
m = re.search(r'0x([0-9A-Fa-f]+)', tail)
|
||||
return int(m.group(1), 16) if m else None
|
||||
items = []
|
||||
seen = set()
|
||||
def add(kind, name, patvar, va, off, fn):
|
||||
key = (name, patvar, fn)
|
||||
if patvar in patterns and va is not None and key not in seen:
|
||||
seen.add(key)
|
||||
items.append({'kind': kind, 'name': name, 'pattern': patterns[patvar], 'va': va, 'off': off, 'file': fn})
|
||||
for f, s in srcs.items():
|
||||
fn = os.path.basename(f)
|
||||
for m in re.finditer(r'ResolveData(?:Va)?\(\s*(?:\w+,\s*)?"([^"]+)",\s*(\w+)\s*,\s*(\d+)\s*,\s*([^;]+?)[;\n]', s):
|
||||
add('data', m.group(1), m.group(2), resolve_va(m.group(4)), int(m.group(3)), fn)
|
||||
for m in re.finditer(r'(?:HookResolver\.Resolve|Bind(?:Resolved)?<[^>]+>|ResolveAddr)\(\s*\w+,\s*"([^"]+)",\s*(\w+)\s*,\s*([^;]+?)[;\n]', s):
|
||||
add('fn', m.group(1), m.group(2), resolve_va(m.group(3)), 0, fn)
|
||||
for m in re.finditer(r'Resolve(?:Va|FnVa)\(\s*"([^"]+)",\s*(\w+)\s*,\s*([^;]+?)[;\n]', s):
|
||||
add('fn', m.group(1), m.group(2), resolve_va(m.group(3)), 0, fn)
|
||||
return items
|
||||
|
||||
# Fail CLOSED: if the source-parsing regexes in parse_engine_patterns() ever
|
||||
# stop matching after an engine refactor (renamed Resolve, reordered args,
|
||||
# new pattern syntax), items silently shrinks toward 0 and CHECK would print
|
||||
# "PASS - all 0 embedded patterns" with exit 0 - a green gate verifying
|
||||
# nothing. As of 2026-06-11 the engine embeds 120 patterns; a parse count
|
||||
# below this floor means the PARSER broke, not that patterns were removed.
|
||||
# Raise/lower deliberately when the real pattern count changes.
|
||||
CHECK_MIN_PATTERNS = 100
|
||||
|
||||
def process_check(text_b, text_base):
|
||||
items = parse_engine_patterns()
|
||||
if len(items) < CHECK_MIN_PATTERNS:
|
||||
print(f"FAIL - only {len(items)} embedded patterns parsed from the engine source "
|
||||
f"(floor: {CHECK_MIN_PATTERNS}). The CHECK parser has likely drifted from the "
|
||||
f"engine's Resolve-site syntax - fix parse_engine_patterns() before trusting this gate.")
|
||||
return 1
|
||||
print(f"Verifying {len(items)} embedded engine patterns against this acclient.exe...\n")
|
||||
fails = 0
|
||||
for it in sorted(items, key=lambda i: (i['file'], i['name'])):
|
||||
ms = matches(text_b, it['pattern'], limit=16)
|
||||
if it['kind'] == 'fn':
|
||||
ok = (it['va'] - text_base) in set(ms)
|
||||
why = "" if ok else ("pattern NOT FOUND" if not ms else f"matches {len(ms)} site(s), none at VA")
|
||||
else:
|
||||
if len(ms) == 1 and ms[0] + it['off'] + 4 <= len(text_b):
|
||||
operand = struct.unpack_from('<I', text_b, ms[0] + it['off'])[0]
|
||||
ok = operand == (it['va'] & 0xFFFFFFFF)
|
||||
why = "" if ok else f"operand 0x{operand:08X} != expected 0x{it['va']:08X}"
|
||||
else:
|
||||
ok = False; why = f"{len(ms)} matches (data-xref needs exactly 1)"
|
||||
if not ok:
|
||||
fails += 1
|
||||
print(f"[FAIL] {it['file']:30} {it['name']:38} VA=0x{it['va']:08X} {why}")
|
||||
print("=" * 60)
|
||||
if fails == 0:
|
||||
print(f"PASS - all {len(items)} embedded patterns unique & correct on this acclient.exe.")
|
||||
return 0
|
||||
print(f"FAIL - {fails}/{len(items)} embedded patterns did NOT verify. Re-cut with pe_pattern.py ALL/DATA, fix the source, rebuild.")
|
||||
return 1
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
raise SystemExit("usage: pe_pattern.py <acclient.exe> [group|ALL|DATA|CHECK|GEN <va...>|GENDATA <va...>]")
|
||||
text_b, text_base = read_window(sys.argv[1])
|
||||
sel = sys.argv[2] if len(sys.argv) > 2 else "ALL"
|
||||
print(f"window base VA = 0x{text_base:08X}, window size = {len(text_b)} bytes\n")
|
||||
if sel.upper() == "CHECK":
|
||||
sys.exit(process_check(text_b, text_base))
|
||||
if sel.upper() == "GEN":
|
||||
process_gen(text_b, text_base, _parse_vas(sys.argv[3:])); return
|
||||
if sel.upper() == "GENDATA":
|
||||
process_gendata(text_b, _parse_vas(sys.argv[3:])); return
|
||||
if sel.upper() == "DATA":
|
||||
process_data(text_b); return
|
||||
groups = list(GROUPS) if sel.upper() == "ALL" else [sel]
|
||||
tok = tbad = 0
|
||||
for g in groups:
|
||||
ok, bad = process(text_b, text_base, g)
|
||||
tok += ok; tbad += bad
|
||||
print()
|
||||
print(f"TOTAL unique+correct: {tok}/{tok + tbad}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
350
tools/soak_scorecard.py
Normal file
350
tools/soak_scorecard.py
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
soak_scorecard.py - out-of-process soak verdict for RynthCore clients.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
A 12-hour soak on 2026-06-12 was declared "solid" because the client never
|
||||
crashed - but combat was 100% broken the entire time (a predicted-kill-swap
|
||||
aborted every cast; nothing died for 12h). "Alive" is not "healthy." This tool
|
||||
reads the per-PID logs + native-crash.log and produces a verdict across THREE
|
||||
axes so that blind spot can't recur:
|
||||
|
||||
1. LIVENESS - heartbeat continuity, fps, plugin-pump rate, wedge signature.
|
||||
2. STABILITY - crash blocks, hang dumps, force-clear / reconcile counters.
|
||||
3. PRODUCTIVITY - kills, casts that LANDED ("You cast"), loot completed.
|
||||
A client that is up but killing nothing FAILS here.
|
||||
|
||||
Read-only. No deps beyond the stdlib. Run after (or during) a soak:
|
||||
|
||||
python tools/soak_scorecard.py # newest per-PID log
|
||||
python tools/soak_scorecard.py --pid 6560 # a specific client
|
||||
python tools/soak_scorecard.py --all # every client in THIS soak
|
||||
python tools/soak_scorecard.py --since 14:46 # window starts at 14:46 today
|
||||
python tools/soak_scorecard.py --max-age-h 8 # window = last 8h
|
||||
python tools/soak_scorecard.py --watch 60 # re-verdict every 60s
|
||||
|
||||
SOAK WINDOW (why this matters): the log dir accumulates per-PID logs across
|
||||
DAYS, and native-crash.log is shared and has no per-block timestamps. Scoring
|
||||
the whole pile makes a clean current run FAIL on yesterday's pre-fix crashes
|
||||
(observed 2026-06-13: a healthy 7h client failed because morning pre-fix logs
|
||||
and a 10h-stale crash block were counted). So by default the window starts at
|
||||
the CURRENT soak's start (first heartbeat of the newest live log); older logs
|
||||
are excluded as previous soaks, and crash blocks count only if native-crash.log
|
||||
was written inside the window. Override with --since / --max-age-h.
|
||||
|
||||
Exit code 0 = PASS, 1 = FAIL, 2 = no log found. So it can gate CI / a
|
||||
launcher hook later.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, glob, os, re, sys, time
|
||||
from datetime import datetime
|
||||
|
||||
LOG_DIR = r"C:\Games\RynthCore\Logs"
|
||||
DUMP_DIR = os.path.join(LOG_DIR, "dumps")
|
||||
CRASH_LOG = os.path.join(LOG_DIR, "native-crash.log")
|
||||
|
||||
# hb #N up=Ss fps=F plug=P/s ws=MMB login=1 qd=Q rec=R fcl=C
|
||||
HB = re.compile(
|
||||
r"hb #(?P<n>\d+) up=(?P<up>\d+)s fps=(?P<fps>\d+) plug=(?P<plug>\d+)/s "
|
||||
r"ws=(?P<ws>\d+)MB login=(?P<login>\d)(?: qd=(?P<qd>\d+))?(?: rec=(?P<rec>\d+))?(?: fcl=(?P<fcl>\d+))?"
|
||||
)
|
||||
TS = re.compile(r"^\[(\d\d):(\d\d):(\d\d)\.\d+\]")
|
||||
|
||||
|
||||
def _secs(line: str):
|
||||
m = TS.match(line)
|
||||
if not m:
|
||||
return None
|
||||
h, mn, s = (int(x) for x in m.groups())
|
||||
return h * 3600 + mn * 60 + s
|
||||
|
||||
|
||||
def pid_log_groups():
|
||||
"""Map pid -> [its log files sorted oldest-first], covering rotations
|
||||
(RynthCore.<pid>.log plus .log.old / .log.N). The engine rotates at ~5 MB:
|
||||
right after a rotation the live .log is a tiny fragment and the soak's
|
||||
history is in .log.old, so scoring only .log would miss the whole run.
|
||||
Each pid is analyzed over its concatenated files in chronological order."""
|
||||
groups = {}
|
||||
for f in glob.glob(os.path.join(LOG_DIR, "RynthCore.*.log*")):
|
||||
m = re.search(r"RynthCore\.(\d+)\.log", os.path.basename(f))
|
||||
if not m:
|
||||
continue
|
||||
groups.setdefault(m.group(1), []).append(f)
|
||||
for pid in groups:
|
||||
groups[pid].sort(key=os.path.getmtime) # oldest first = chronological
|
||||
return groups
|
||||
|
||||
|
||||
def count(path, pat):
|
||||
c = 0
|
||||
rx = re.compile(re.escape(pat))
|
||||
with open(path, encoding="utf-8", errors="replace") as fh:
|
||||
for ln in fh:
|
||||
if rx.search(ln):
|
||||
c += 1
|
||||
return c
|
||||
|
||||
|
||||
def analyze(paths):
|
||||
if isinstance(paths, str):
|
||||
paths = [paths]
|
||||
pid = re.search(r"RynthCore\.(\d+)\.log", os.path.basename(paths[0])).group(1)
|
||||
last_hb = None
|
||||
hb_count = 0
|
||||
fps0_inworld = 0 # wedge signature: fps=0 with login=1
|
||||
max_hb_gap = 0.0
|
||||
prev_t = None
|
||||
kills = casts_landed = loot_done = force_clears = 0
|
||||
combat_casts = 0
|
||||
buffstance = coma = stance_stuck = 0
|
||||
first_t = last_t = None
|
||||
|
||||
for path in paths:
|
||||
with open(path, encoding="utf-8", errors="replace") as fh:
|
||||
for ln in fh:
|
||||
t = _secs(ln)
|
||||
if t is not None:
|
||||
if first_t is None:
|
||||
first_t = t
|
||||
last_t = t
|
||||
m = HB.search(ln)
|
||||
if m:
|
||||
last_hb = m.groupdict()
|
||||
hb_count += 1
|
||||
if m["fps"] == "0" and m["login"] == "1":
|
||||
fps0_inworld += 1
|
||||
if t is not None and prev_t is not None:
|
||||
gap = t - prev_t
|
||||
if gap < 0:
|
||||
gap += 86400 # midnight wrap
|
||||
max_hb_gap = max(max_hb_gap, gap)
|
||||
if t is not None:
|
||||
prev_t = t
|
||||
# productivity / health signals
|
||||
if "KillerNotification" in ln:
|
||||
kills += 1
|
||||
if "[CombatCast]" in ln:
|
||||
combat_casts += 1
|
||||
if "You cast" in ln: # buffs/life only; war magic emits none
|
||||
casts_landed += 1
|
||||
if "Corpse loot: completed" in ln:
|
||||
loot_done += 1
|
||||
if "force-clearing" in ln:
|
||||
force_clears += 1
|
||||
if "BuffStance" in ln:
|
||||
buffstance += 1
|
||||
if "BUFFING COMA" in ln:
|
||||
coma += 1
|
||||
if "STANCE STUCK" in ln:
|
||||
stance_stuck += 1
|
||||
|
||||
up_h = (last_t - first_t) / 3600.0 if (first_t is not None and last_t is not None and last_t >= first_t) else 0.0
|
||||
return dict(pid=pid, path=path, last_hb=last_hb, hb_count=hb_count,
|
||||
fps0_inworld=fps0_inworld, max_hb_gap=max_hb_gap, up_h=up_h,
|
||||
kills=kills, combat_casts=combat_casts, casts_landed=casts_landed,
|
||||
loot_done=loot_done, force_clears=force_clears, buffstance=buffstance,
|
||||
coma=coma, stance_stuck=stance_stuck)
|
||||
|
||||
|
||||
def crash_blocks_for_pid(pid):
|
||||
"""Attribute native-crash.log blocks to a specific client by the embedded
|
||||
`RynthCore.Engine.p<PID>.genN.dll` stack frame each block carries. The
|
||||
crash log is SHARED across all multi-boxed clients, so file mtime can't
|
||||
pin a crash to one PID — but the engine module frame names the PID exactly.
|
||||
Returns (mine, unattributed): `mine` = block-header lines whose engine
|
||||
frame matches `pid` (a real crash in THIS client, even if first-chance and
|
||||
survived); `unattributed` = blocks with no engine frame (pure acclient/
|
||||
system stack) which can't be tied to a PID from a shared log."""
|
||||
if not os.path.exists(CRASH_LOG):
|
||||
return [], []
|
||||
txt = open(CRASH_LOG, encoding="utf-8", errors="replace").read()
|
||||
mine, unattr = [], []
|
||||
for raw in txt.split("NATIVE CRASH LOGGER")[1:]:
|
||||
header = next((l.strip() for l in raw.splitlines() if "exAddr=" in l), None)
|
||||
if header is None:
|
||||
continue
|
||||
m = re.search(r"RynthCore\.Engine\.p(\d+)\.", raw)
|
||||
if m:
|
||||
if m.group(1) == str(pid):
|
||||
mine.append(header)
|
||||
else:
|
||||
unattr.append(header)
|
||||
return mine[-5:], unattr[-3:]
|
||||
|
||||
|
||||
def since_epoch(hhmm):
|
||||
"""Parse an HH:MM soak-window start (today; yesterday if it's still future)."""
|
||||
hh, mm = (int(x) for x in hhmm.split(":"))
|
||||
now = datetime.now()
|
||||
ws = now.replace(hour=hh, minute=mm, second=0, microsecond=0)
|
||||
return (ws.timestamp() - 86400) if ws > now else ws.timestamp()
|
||||
|
||||
|
||||
def session_start_epoch(path):
|
||||
"""Current-soak start = first heartbeat time of the newest (active) log,
|
||||
dated by that log's mtime. Logs/crashes before this belong to a PREVIOUS
|
||||
soak. Returns None if unparseable (caller falls back to a fixed max-age)."""
|
||||
try:
|
||||
mt = os.path.getmtime(path)
|
||||
mdt = datetime.fromtimestamp(mt)
|
||||
first = None
|
||||
with open(path, encoding="utf-8", errors="replace") as fh:
|
||||
for ln in fh:
|
||||
s = _secs(ln)
|
||||
if s is not None:
|
||||
first = s
|
||||
break
|
||||
if first is None:
|
||||
return None
|
||||
start = mdt.replace(hour=first // 3600, minute=(first % 3600) // 60,
|
||||
second=first % 60, microsecond=0).timestamp()
|
||||
return start - 86400 if start > mt else start
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def verdict(a):
|
||||
fails, warns = [], []
|
||||
# LIVENESS
|
||||
if a["last_hb"] is None:
|
||||
fails.append("no heartbeat lines (engine never ran / log empty)")
|
||||
else:
|
||||
if a["fps0_inworld"] > 5:
|
||||
fails.append(f"WEDGE: {a['fps0_inworld']} heartbeats at fps=0 while login=1")
|
||||
if a["max_hb_gap"] > 15:
|
||||
warns.append(f"heartbeat gap up to {a['max_hb_gap']:.0f}s (stall or rotation)")
|
||||
# STABILITY
|
||||
if a["coma"]:
|
||||
fails.append(f"{a['coma']} BUFFING COMA event(s)")
|
||||
if a["stance_stuck"]:
|
||||
warns.append(f"{a['stance_stuck']} STANCE STUCK recovery(ies)")
|
||||
fcl_per_h = a["force_clears"] / a["up_h"] if a["up_h"] > 0.1 else a["force_clears"]
|
||||
if fcl_per_h > 60:
|
||||
warns.append(f"{fcl_per_h:.0f} force-clears/hr (busy still leaking - should be near-flat)")
|
||||
# PRODUCTIVITY - the axis that today's 12h soak would have FAILED.
|
||||
# KILLS (KillerNotification) are the reliable truth signal. "You cast" is
|
||||
# NOT logged for war-magic combat (and only logged for buffs during a
|
||||
# buff-pending window), so it is informational only - never a FAIL.
|
||||
# The real "casting but not landing" regression (2026-06-13) shows as
|
||||
# many CombatCast ATTEMPTS with ZERO kills.
|
||||
if a["up_h"] >= 0.25: # only judge productivity once it's run >15 min
|
||||
kph = a["kills"] / a["up_h"]
|
||||
if a["kills"] == 0:
|
||||
if a["combat_casts"] >= 15:
|
||||
fails.append(f"{a['combat_casts']} cast attempts but ZERO kills - casts not landing "
|
||||
f"(the 2026-06-13 swap-aborts-cast regression)")
|
||||
elif a["loot_done"] > 0:
|
||||
warns.append("kills=0 but looting - passive/escort mode? verify it should be fighting")
|
||||
else:
|
||||
warns.append("kills=0 and almost no combat - idle, no spawns, or not engaging (check the bot)")
|
||||
elif kph < 10:
|
||||
warns.append(f"only {kph:.1f} kills/hr (low for a grind)")
|
||||
return fails, warns
|
||||
|
||||
|
||||
def report(a):
|
||||
f, w = verdict(a)
|
||||
status = "FAIL" if f else ("WARN" if w else "PASS")
|
||||
hb = a["last_hb"] or {}
|
||||
print(f"\n=== pid {a['pid']} - {status} ===")
|
||||
print(f" uptime ~{a['up_h']:.1f}h | {a['hb_count']} heartbeats | last fps={hb.get('fps','?')} "
|
||||
f"plug={hb.get('plug','?')}/s qd={hb.get('qd','?')} rec={hb.get('rec','?')} fcl={hb.get('fcl','?')}")
|
||||
print(f" PRODUCTIVITY: {a['kills']} kills | {a['combat_casts']} cast attempts | {a['loot_done']} corpses looted "
|
||||
f"| {a['casts_landed']} 'You cast' (buff-window log only; not a combat signal)")
|
||||
print(f" STABILITY: {a['force_clears']} force-clears | {a['stance_stuck']} stance-stuck | {a['coma']} coma "
|
||||
f"| max hb gap {a['max_hb_gap']:.0f}s | {a['fps0_inworld']} fps0-inworld")
|
||||
for x in f:
|
||||
print(f" [FAIL] {x}")
|
||||
for x in w:
|
||||
print(f" [warn] {x}")
|
||||
return status
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--pid")
|
||||
ap.add_argument("--all", action="store_true")
|
||||
ap.add_argument("--since", help="soak-window start as HH:MM (today). Logs/crashes before this are a previous soak")
|
||||
ap.add_argument("--max-age-h", type=float, help="window = last N hours (overrides the auto current-soak window)")
|
||||
ap.add_argument("--watch", type=int, default=0, help="re-verdict every N seconds")
|
||||
args = ap.parse_args()
|
||||
|
||||
def run_once():
|
||||
groups = pid_log_groups() # pid -> [files oldest-first]
|
||||
if args.pid:
|
||||
files = groups.get(args.pid) or [os.path.join(LOG_DIR, f"RynthCore.{args.pid}.log")]
|
||||
groups = {args.pid: [f for f in files if os.path.exists(f)]}
|
||||
if not groups or all(not v for v in groups.values()):
|
||||
print("no client logs found in", LOG_DIR)
|
||||
return 2
|
||||
last_seen = {pid: max(os.path.getmtime(f) for f in fs) for pid, fs in groups.items() if fs}
|
||||
anchor = max(last_seen, key=last_seen.get) # most recently active client
|
||||
|
||||
# --- soak window start ---
|
||||
if args.since:
|
||||
ws = since_epoch(args.since)
|
||||
elif args.max_age_h:
|
||||
ws = time.time() - args.max_age_h * 3600.0
|
||||
else: # auto: start of the active soak
|
||||
ws = session_start_epoch(groups[anchor][0]) or (time.time() - 12 * 3600.0)
|
||||
print(f"soak window: since {datetime.fromtimestamp(ws):%Y-%m-%d %H:%M}"
|
||||
f" (older logs/crashes = previous soak, excluded)")
|
||||
|
||||
# --- which clients fall in the window ---
|
||||
in_window = sorted([p for p in last_seen if last_seen[p] >= ws], key=lambda p: last_seen[p], reverse=True)
|
||||
stale = sorted([p for p in last_seen if last_seen[p] < ws], key=lambda p: last_seen[p], reverse=True)
|
||||
if args.pid:
|
||||
chosen = [args.pid]
|
||||
elif in_window:
|
||||
chosen = in_window if args.all else in_window[:1]
|
||||
else: # nothing fresh: show newest, flagged
|
||||
age_h = (time.time() - last_seen[anchor]) / 3600.0
|
||||
print(f" ! no logs within the window; newest (pid {anchor}) is {age_h:.1f}h old - PREVIOUS soak.")
|
||||
chosen, stale = [anchor], [p for p in stale if p != anchor]
|
||||
if stale:
|
||||
print(f" excluded {len(stale)} stale client(s) from prior soaks: "
|
||||
+ ", ".join(stale[:12]) + (" ..." if len(stale) > 12 else ""))
|
||||
if not args.all and not args.pid and len(in_window) > 1:
|
||||
print(f" ({len(in_window) - 1} other in-window client(s) not shown; use --all)")
|
||||
|
||||
# --- crash-log freshness: file mtime is the only time signal it has ---
|
||||
crash_fresh = os.path.exists(CRASH_LOG) and os.path.getmtime(CRASH_LOG) >= ws
|
||||
if os.path.exists(CRASH_LOG):
|
||||
cm = f"{datetime.fromtimestamp(os.path.getmtime(CRASH_LOG)):%Y-%m-%d %H:%M}"
|
||||
print(f" native-crash.log last written {cm} "
|
||||
+ ("(IN window - blocks below are this soak)" if crash_fresh
|
||||
else "(BEFORE window - 0 crashes this soak)"))
|
||||
|
||||
worst = "PASS"
|
||||
for pid in chosen:
|
||||
fs = groups[pid]
|
||||
a = analyze(fs)
|
||||
if len(fs) > 1:
|
||||
print(f"\n(aggregating {len(fs)} rotated files for pid {pid})", end="")
|
||||
st = report(a)
|
||||
if crash_fresh:
|
||||
mine, _unattr = crash_blocks_for_pid(a["pid"])
|
||||
if mine:
|
||||
print(f" [FAIL] {len(mine)} crash block(s) attributed to THIS client (pid {a['pid']}) "
|
||||
f"in-window - corruption:")
|
||||
for c in mine:
|
||||
print(f" {c}")
|
||||
st = "FAIL"
|
||||
if st == "FAIL" or (st == "WARN" and worst == "PASS"):
|
||||
worst = st
|
||||
print(f"\nVERDICT: {worst}")
|
||||
return 0 if worst != "FAIL" else 1
|
||||
|
||||
if args.watch:
|
||||
while True:
|
||||
print("\n" + "=" * 60 + f" {datetime.now():%H:%M:%S}")
|
||||
run_once()
|
||||
time.sleep(max(15, args.watch))
|
||||
else:
|
||||
sys.exit(run_once())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
8
tools/symbolicate.ps1
Normal file
8
tools/symbolicate.ps1
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
# Thin wrapper around symbolicate.py. Forwards all args.
|
||||
# .\symbolicate.ps1 # newest log -> console
|
||||
# .\symbolicate.ps1 C:\path\to\some.log # specific log
|
||||
# .\symbolicate.ps1 -o out.txt --only-crash
|
||||
$py = (Get-Command python -ErrorAction SilentlyContinue)
|
||||
if (-not $py) { $py = (Get-Command py -ErrorAction SilentlyContinue) }
|
||||
if (-not $py) { Write-Error "Python not found on PATH."; exit 1 }
|
||||
& $py.Source (Join-Path $PSScriptRoot "symbolicate.py") @args
|
||||
204
tools/symbolicate.py
Normal file
204
tools/symbolicate.py
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
#!/usr/bin/env python3
|
||||
# ============================================================================
|
||||
# symbolicate.py - turn RynthCore crash/hang logs into readable stacks.
|
||||
#
|
||||
# RynthCore's CrashLogger / MainThreadHangWatchdog emit native frames as
|
||||
# "<module>+0xRVA" (e.g. "acclient.exe+0x15FA24") because NativeAOT has no
|
||||
# symbols for acclient.exe at runtime. We DO have a full Ghidra decompile of
|
||||
# the same binary (GhidraTools/symbols.csv, ~48k named functions), so this
|
||||
# offline tool post-processes a log and rewrites every acclient frame into
|
||||
# "ClientCombatSystem::Foo+0x12 [acclient.exe+0x15FA24]"
|
||||
# It also flags addresses that match the catalogue of known recurring AVs.
|
||||
#
|
||||
# Pure post-processing of a text file vs a CSV. Out-of-process, zero runtime
|
||||
# risk to the injected engine. Re-runnable.
|
||||
#
|
||||
# Usage:
|
||||
# python symbolicate.py [LOGFILE] [-o OUT] [--symbols PATH] [--base 0x400000]
|
||||
#
|
||||
# LOGFILE defaults to the newest C:\Games\RynthCore\Logs\RynthCore*.log.
|
||||
# With no -o, annotated output goes to stdout.
|
||||
# ============================================================================
|
||||
|
||||
import argparse
|
||||
import bisect
|
||||
import csv
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
# Logs contain non-ASCII (em-dashes, etc). Force UTF-8 on the streams so piping
|
||||
# a large annotated log to a Windows console/pipe doesn't UnicodeEncodeError.
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
DEFAULT_SYMBOLS = r"C:\Projects\GhidraTools\symbols.csv"
|
||||
DEFAULT_LOGDIR = r"C:\Games\RynthCore\Logs"
|
||||
DEFAULT_BASE = 0x400000 # Ghidra image base for acclient.exe (no-ASLR)
|
||||
SYMBOL_MODULE = "acclient.exe" # the only module we have symbols for
|
||||
|
||||
# module+0xRVA tokens, e.g. "acclient.exe+0x15FA24" or " ebp[03] ret=... acclient.exe+0x1234"
|
||||
FRAME_RE = re.compile(r"\b([A-Za-z0-9_.\-]+\.(?:exe|dll))\+0x([0-9A-Fa-f]+)\b")
|
||||
|
||||
# Catalogue of known recurring faults, keyed by absolute VA (base + rva).
|
||||
# Sourced from the RynthCore crash-investigation notes; extend as new ones land.
|
||||
KNOWN_CRASHES = {
|
||||
0x0055FA24: "object-teardown corruption (DBOCache::DestroyObj / "
|
||||
"List<ObjectRangeInfo>::remove) from OFF-THREAD AC mutation "
|
||||
"-> marshal mutations onto the AC tick. [rynthcore_crash_investigation]",
|
||||
0x00416C86: "object-teardown class (NOT a CastSpell fault, despite "
|
||||
"appearances). [rynthcore_castspell_fallback_pitfall]",
|
||||
0x0056547B: "ClientUISystem::UpdateCursorState reading the freed combat "
|
||||
"singleton on a trailing mouse/cursor msg after WM_CLOSE -> "
|
||||
"swallow mouse input once WM_CLOSE seen. [rynthcore_freeze_on_close_fix]",
|
||||
0x00460D1D: "UIElement::GetAttribute_Bool (0x460CC0+0x5D) smart-ptr refcount "
|
||||
"writeback into read-only .text: AC's selection/targeting UIElement "
|
||||
"subtree was corrupted by an OFF-THREAD SetSelectedObject (0x58D110) "
|
||||
"racing AC's main-thread UI walk during corpse-loot SelectItem. "
|
||||
"regs eax/dataAddr=0x472175 ecx=0x472171 edi=0xD; often two threads "
|
||||
"faulting at once. FIXED 74f6d8c (main-thread marshal). NOT "
|
||||
"AddTextToScroll / NOT the 'too busy' chat spam -- that was a stale "
|
||||
"misattribution, corrected 2026-06-13. [rynthcore_offthread_av_class]",
|
||||
}
|
||||
|
||||
|
||||
def load_symbols(path):
|
||||
"""Return (sorted_vas, names_by_index) for nearest-preceding lookup."""
|
||||
pairs = []
|
||||
with open(path, "r", encoding="utf-8-sig", newline="") as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
addr = (row.get("address") or "").strip().strip('"')
|
||||
name = (row.get("name") or "").strip().strip('"')
|
||||
if not addr or not name:
|
||||
continue
|
||||
try:
|
||||
va = int(addr, 16) if addr.lower().startswith("0x") else int(addr, 16)
|
||||
except ValueError:
|
||||
continue
|
||||
pairs.append((va, name))
|
||||
pairs.sort(key=lambda p: p[0])
|
||||
vas = [p[0] for p in pairs]
|
||||
names = [p[1] for p in pairs]
|
||||
return vas, names
|
||||
|
||||
|
||||
def resolve(va, vas, names):
|
||||
"""Nearest preceding symbol for an absolute VA -> 'name+0xNN' or None."""
|
||||
i = bisect.bisect_right(vas, va) - 1
|
||||
if i < 0:
|
||||
return None
|
||||
base = vas[i]
|
||||
off = va - base
|
||||
# Guard against absurd offsets (address past the last symbol / in another section)
|
||||
if off > 0x20000:
|
||||
return None
|
||||
return f"{names[i]}+0x{off:X}" if off else names[i]
|
||||
|
||||
|
||||
def newest_log(logdir):
|
||||
cands = glob.glob(os.path.join(logdir, "RynthCore*.log"))
|
||||
cands = [c for c in cands if not c.endswith(".old")]
|
||||
if not cands:
|
||||
cands = glob.glob(os.path.join(logdir, "RynthCore*.log*"))
|
||||
if not cands:
|
||||
return None
|
||||
return max(cands, key=os.path.getmtime)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Symbolicate RynthCore crash/hang logs.")
|
||||
ap.add_argument("logfile", nargs="?", help="log to annotate (default: newest in %s)" % DEFAULT_LOGDIR)
|
||||
ap.add_argument("-o", "--out", help="write annotated log here (default: stdout)")
|
||||
ap.add_argument("--symbols", default=DEFAULT_SYMBOLS, help="Ghidra symbols.csv (default: %(default)s)")
|
||||
ap.add_argument("--base", default=hex(DEFAULT_BASE), help="acclient.exe image base (default: %(default)s)")
|
||||
ap.add_argument("--only-crash", action="store_true",
|
||||
help="emit only lines belonging to a CRASH/HANG/EXCEPTION block")
|
||||
args = ap.parse_args()
|
||||
|
||||
base = int(args.base, 16) if args.base.lower().startswith("0x") else int(args.base, 16)
|
||||
|
||||
logfile = args.logfile or newest_log(DEFAULT_LOGDIR)
|
||||
if not logfile or not os.path.exists(logfile):
|
||||
sys.exit(f"error: log file not found ({logfile!r}). Pass one explicitly.")
|
||||
|
||||
if not os.path.exists(args.symbols):
|
||||
sys.exit(f"error: symbols file not found: {args.symbols}")
|
||||
|
||||
vas, names = load_symbols(args.symbols)
|
||||
sys.stderr.write(f"[symbolicate] {len(vas)} symbols from {args.symbols}\n")
|
||||
sys.stderr.write(f"[symbolicate] annotating {logfile} (base=0x{base:X})\n")
|
||||
|
||||
out_lines = []
|
||||
hits = 0
|
||||
known_hits = []
|
||||
block_markers = ("CRASH", "HANG", "EXCEPTION", "PROCESS-KILLER", "SUEF", "VEH")
|
||||
in_block = False
|
||||
|
||||
with open(logfile, "r", encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
line = line.rstrip("\n")
|
||||
|
||||
# Track crash/hang blocks for --only-crash filtering.
|
||||
upper = line.upper()
|
||||
if any(m in upper for m in block_markers):
|
||||
in_block = True
|
||||
elif line.startswith("====") and "====" in line[4:]:
|
||||
in_block = False
|
||||
|
||||
def repl(m):
|
||||
nonlocal hits
|
||||
module, rva_hex = m.group(1), m.group(2)
|
||||
if module.lower() != SYMBOL_MODULE:
|
||||
return m.group(0) # we only have acclient symbols
|
||||
rva = int(rva_hex, 16)
|
||||
va = base + rva
|
||||
name = resolve(va, vas, names)
|
||||
if name is None:
|
||||
return m.group(0)
|
||||
hits += 1
|
||||
tag = ""
|
||||
if va in KNOWN_CRASHES:
|
||||
tag = " <<< KNOWN"
|
||||
known_hits.append((va, name, KNOWN_CRASHES[va]))
|
||||
return f"{name} [{m.group(0)}]{tag}"
|
||||
|
||||
annotated = FRAME_RE.sub(repl, line)
|
||||
|
||||
if not args.only_crash or in_block:
|
||||
out_lines.append(annotated)
|
||||
|
||||
body = "\n".join(out_lines) + "\n"
|
||||
|
||||
# Footer summary of known-crash matches.
|
||||
footer = []
|
||||
if known_hits:
|
||||
footer.append("")
|
||||
footer.append("================ KNOWN-CRASH MATCHES ================")
|
||||
seen = set()
|
||||
for va, name, note in known_hits:
|
||||
if va in seen:
|
||||
continue
|
||||
seen.add(va)
|
||||
footer.append(f" 0x{va:08X} {name}")
|
||||
footer.append(f" -> {note}")
|
||||
footer.append("====================================================")
|
||||
footer.append(f"[symbolicate] resolved {hits} acclient frame(s); "
|
||||
f"{len(set(v for v, _, _ in known_hits))} known-crash address(es).")
|
||||
|
||||
text = body + "\n".join(footer) + "\n"
|
||||
|
||||
if args.out:
|
||||
with open(args.out, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
sys.stderr.write(f"[symbolicate] wrote {args.out}\n")
|
||||
else:
|
||||
sys.stdout.write(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in a new issue