using System.Text;
using System.Text.Json;
namespace XFEWarframe.Client;
/// <summary>Resolved native contracts. An unknown build must satisfy the same independent contracts.</summary>
public sealed class ExperimentalAbi
{
public sealed record Binding(string Name, int Rva, string Bytes, string Pattern, bool Function);
public Dictionary<string, Binding> Bindings { get; } = new(StringComparer.Ordinal);
public Dictionary<uint, uint> Aliases { get; } = [];
public Dictionary<int, int> Relocations { get; } = [];
public Dictionary<string, HashSet<int>> NamedMethods { get; } = new(StringComparer.Ordinal);
public List<string> Problems { get; } = [];
public bool Legacy { get; private init; }
public bool AuditedBuild { get; private init; }
public int SuitDelta { get; private set; }
public int TypeBase { get; private set; }
public int EmptyReference { get; private set; }
public int SpecialItemMetadata { get; private set; }
public int AnimationGetVirtual { get; private set; } = 0x8C0;
public int AnimationSetVirtual { get; private set; } = 0x970;
public uint HashSeed { get; private set; } = 0x7E5AF8E9;
public int ScriptState { get; private set; } = 0x2734D40;
public int ProfileVtable { get; private set; } = 0x214BA70;
public HashSet<int> ProfileVtables { get; } = [];
public int LuaInterruptOffset { get; private set; }
public int LuaCClosureUpvalueOffset { get; private set; }
public bool MultiAbilities => Problems.Count == 0;
private bool luaVerified;
private static readonly string[] LuaContracts = ["LuaPCall", "LuaGetHash", "LuaSetTop", "LuaCreateTable", "LuaCopy", "LuaFindMethod", "LuaPushFunction", "LuaGetMetatable", "LuaGetString", "LuaPushString", "LuaEnsureStack", "LuaClose", "LuaPushThread", "HashBytes", "ProfileUpdate"];
public bool LuaAvailable => LuaInterruptOffset != 0 && Bindings.ContainsKey("LuaInstructionGuard") && Bindings.ContainsKey("LuaInterruptCounter") && (Legacy ? MultiAbilities : luaVerified && LuaContracts.All(Bindings.ContainsKey));
public bool FetchAvailable => LuaAvailable && (Legacy || Aliases.ContainsKey(0xB2A2BA51) && new[] { "GetKubrowPets", "GetRadius", "SetRadius" }.All(name => NamedMethods.TryGetValue(name, out var methods) && methods.Count > 0));
public bool CardRenderingAvailable => LuaAvailable && (Legacy || Bindings.ContainsKey("NativeMovieDraw") && Aliases.ContainsKey(0x297A9947));
public int Address(string name) => Bindings.TryGetValue(name, out var entry) ? entry.Rva : throw new InvalidDataException("Native binding unavailable: " + name);
public int Relocate(int legacyRva) => Legacy ? legacyRva : Relocations.TryGetValue(legacyRva, out var rva) ? rva : throw new InvalidDataException($"Native binding unavailable: 0x{legacyRva:X}");
public uint Alias(uint legacyHash) => Legacy ? legacyHash : Aliases.TryGetValue(legacyHash, out var hash) ? hash : throw new InvalidDataException($"Script binding unavailable: 0x{legacyHash:X8}");
public int Suit(int oldOffset) => checked(oldOffset + SuitDelta);
public static ExperimentalAbi Resolve(BinaryImage image, string hash)
{
if (hash.Equals(ExperimentalAbilityCompatibility.ExecutableSha256, StringComparison.OrdinalIgnoreCase))
{
var legacy = new ExperimentalAbi { Legacy = true, AuditedBuild = true, TypeBase = 0x28A4800, EmptyReference = 0x272F3B0, SpecialItemMetadata = 0x2955360 };
foreach (var entry in ExperimentalAbilityCompatibility.Entries)
{
if (!image.Read(entry.Rva, entry.Bytes.Length / 2).AsSpan().SequenceEqual(Convert.FromHexString(entry.Bytes))) legacy.Problems.Add(entry.Name);
legacy.Bindings[entry.Name] = new(entry.Name, entry.Rva, entry.Bytes, "", true);
}
legacy.ResolveInterruptBudget(image);
legacy.ResolveCClosureCapture(image, 0x80DFE0);
legacy.ProfileVtables.Add(legacy.ProfileVtable);
return legacy;
}
using var manifest = JsonDocument.Parse(typeof(ExperimentalAbi).Assembly.GetManifestResourceStream("XFEWarframe.ExperimentalAbi.json")!);
var root = manifest.RootElement;
var result = new ExperimentalAbi { AuditedBuild = hash.Equals(root.GetProperty("sha256").GetString(), StringComparison.OrdinalIgnoreCase), ScriptState = 0 };
var candidates = root.GetProperty("bindings").EnumerateArray().ToDictionary(row => row.GetProperty("name").GetString()!, row => result.AuditedBuild ? [row.GetProperty("rva").GetInt32()] : image.Find(row.GetProperty("pattern").GetString()!).Where(r => !row.GetProperty("function").GetBoolean() || image.FunctionStart(r) == r).Distinct().ToArray(), StringComparer.Ordinal);
foreach (var row in root.GetProperty("bindings").EnumerateArray())
{
var name = row.GetProperty("name").GetString()!;
var baseline = row.GetProperty("rva").GetInt32();
var pattern = row.GetProperty("pattern").GetString()!;
var function = row.GetProperty("function").GetBoolean();
var required = row.GetProperty("required").GetBoolean();
int[] matches;
if (result.AuditedBuild) matches = [baseline];
else
{
matches = candidates[name];
if (row.TryGetProperty("inside", out var parent) && candidates[parent.GetString()!] is [var parentRva]) matches = matches.Where(r => image.FunctionStart(r) == parentRva).ToArray();
if (row.TryGetProperty("calls", out var callee) && candidates[callee.GetString()!] is [var calleeRva]) matches = matches.Where(r => HasCall(image, r, 105, calleeRva)).ToArray();
if (row.TryGetProperty("calledBy", out var caller) && candidates[caller.GetString()!] is [var callerRva])
{
var window = row.TryGetProperty("callWindow", out var callWindow) ? callWindow.GetInt32() : 64;
matches = matches.Where(r => HasCall(image, callerRva, window, r)).ToArray();
}
}
if (matches.Length != 1)
{
if (required) result.Problems.Add($"{name}: {matches.Length} candidates");
continue;
}
var rva = matches[0];
var expected = result.AuditedBuild ? row.GetProperty("bytes").GetString()! : Convert.ToHexString(image.Read(rva, 32));
if (result.AuditedBuild && !image.Read(rva, expected.Length / 2).AsSpan().SequenceEqual(Convert.FromHexString(expected)))
{ if (required) result.Problems.Add(name + ": signature changed"); continue; }
result.Bindings[name] = new(name, rva, expected, pattern, function);
if (row.TryGetProperty("legacy", out var old)) result.Relocations[old.GetInt32()] = rva;
if (row.TryGetProperty("alias", out var alias))
{
var descriptors = image.FindData(BitConverter.GetBytes(image.PreferredBase + (ulong)rva));
var identifiers = descriptors.Where(r => r >= 8 && image.ReadInt(r - 4) == 0).Select(r => unchecked((uint)image.ReadInt(r - 8))).Where(h => h != 0).Distinct().ToArray();
if (identifiers.Length == 1) result.Aliases[alias.GetUInt32()] = identifiers[0];
else if (required) result.Problems.Add(name + ": export identity is ambiguous");
}
}
result.ResolveInterruptBudget(image);
try { result.ValidateLuaRelationships(image); }
catch (InvalidDataException ex) { result.Problems.Add(ex.Message); }
try { result.ValidateRelationships(image); }
catch (InvalidDataException ex) { result.Problems.Add(ex.Message); }
return result;
}
private void ResolveInterruptBudget(BinaryImage image)
{
try
{
var interrupt = LuaInterruptAbi.Resolve(image);
LuaInterruptOffset = interrupt.Offset;
foreach (var (name, rva, length) in new[] { ("LuaInstructionGuard", interrupt.Guard, 32), ("LuaInterruptCounter", interrupt.Counter, 13) })
{
var bytes = Convert.ToHexString(image.Read(rva, length));
Bindings[name] = new(name, rva, bytes, bytes, true);
}
}
catch (InvalidDataException ex) { Problems.Add(ex.Message); }
}
private void ValidateRelationships(BinaryImage image)
{
// The offsets are derived from the resolved native operations, then checked in
// independent readers/writers. A matching prologue alone cannot authorize an ABI.
var setter = Address("OverrideSet");
var overrideOffset = Operand(image, setter, 48, "4C 8B 89 ?? ?? ?? ??", 3);
SuitDelta = overrideOffset - 0x36C0;
if (SuitDelta is < -0x100 or > 0x800 || (SuitDelta & 7) != 0) throw new InvalidDataException("Power suit layout changed.");
if (Operand(image, Address("OverrideApply"), 36, "48 81 C1 ?? ?? ?? ??", 3) != overrideOffset) throw new InvalidDataException("Override read/write layouts disagree.");
RequireBytes(image, Address("TryActivate"), 500, BitConverter.GetBytes(Suit(0x3448)));
RequireBytes(image, Address("TryActivate"), 500, BitConverter.GetBytes(Suit(0x3450)));
RequireBytes(image, Address("OverrideApply"), 425, BitConverter.GetBytes(Suit(0x3418)));
RequireBytes(image, Address("OverrideApply"), 425, BitConverter.GetBytes(Suit(0x3420)));
RequireCall(image, Address("OverrideApply"), 48, Address("AbilityValidate"));
RequireCall(image, Address("ConfigSerialize"), 1100, Address("TypeSerialize"));
RequireCall(image, Address("SpecialItemLua"), 105, Address("SpecialItem"));
RequireCall(image, Address("SpecialItemLua"), 105, Address("PushSpecialItem"));
if (image.FunctionStart(Address("SuitBeforeRanks")) != Address("SuitInitialize") ||
image.FunctionStart(Address("OverrideInheritScripts")) != Address("OverrideApply")) throw new InvalidDataException("Power suit call graph changed.");
TypeBase = RipBeforeCall(image, Address("ConfigSerialize"), 1100, Address("TypeSerialize"), "4C 8D 05", 24);
EmptyReference = OperandTarget(image, Address("OverrideApply"), 150, "4C 8D 3D ?? ?? ?? ??", 3);
if (OperandTarget(image, Address("StrongReferenceCopy"), 100, "48 8D 35 ?? ?? ?? ??", 3) != EmptyReference)
throw new InvalidDataException("Ability reference ownership contract changed.");
SpecialItemMetadata = OperandTarget(image, Address("SpecialItemLua"), 105, "48 8B 15 ?? ?? ?? ??", 3);
AnimationGetVirtual = Operand(image, Address("AnimationGetLua"), 48, "FF 92 ?? ?? ?? ??", 2);
AnimationSetVirtual = Operand(image, Address("AnimationSetLua"), 300, "FF 90 ?? ?? ?? ??", 2);
if (AnimationGetVirtual is < 0x100 or > 0x2000 || (AnimationGetVirtual & 7) != 0 || AnimationSetVirtual is < 0x100 or > 0x2000 || (AnimationSetVirtual & 7) != 0) throw new InvalidDataException("Animation interface changed.");
}
private void ValidateLuaRelationships(BinaryImage image)
{
foreach (var name in LuaContracts) _ = Address(name);
// C closures carry a debug/context pair before their captures in newer VMs.
// Read the 16-byte capture copy from lua_pushcclosure rather than treating
// a C wrapper as an L closure; their upvalue arrays need not start together.
ResolveCClosureCapture(image, Address("LuaPushFunction"));
HashSeed = unchecked((uint)Operand(image, Address("HashBytes"), 8, "B8 ?? ?? ?? ??", 1));
foreach (var name in new[] { "GetKubrowPets", "GetRadius", "SetRadius" })
{
var pattern = BitConverter.GetBytes(Hash(name, HashSeed)).Concat(new byte[4]).ToArray();
NamedMethods[name] = image.FindData(pattern).Where(r => (r & 7) == 0)
.Select(r => unchecked((int)(BitConverter.ToUInt64(image.Read(r + 8, 8)) - image.PreferredBase)))
.Where(image.IsExecutable).ToHashSet();
}
ValidateProfileTables(image);
// Avoid carrying literal script hashes into a newly salted VM.
foreach (var (old, name) in new (uint, string)[] { (0x1DD8A236, "HasVariable"), (0x433F610A, "GetLocalized"), (0x5D5FD020, "FlashMethod"), (0xBFBBF8CE, "GetAttachedUpgrades") }) Aliases[old] = Hash(name, HashSeed);
luaVerified = true;
}
private void ResolveCClosureCapture(BinaryImage image, int constructor)
{
var capture = new BytePattern("42 0F 11 44 02 ??").Find(image.Read(constructor, 256));
if (capture.Count != 1) throw new InvalidDataException("C closure capture layout is ambiguous.");
var captureRva = constructor + capture[0];
LuaCClosureUpvalueOffset = image.Read(captureRva + 5, 1)[0];
if (LuaCClosureUpvalueOffset is < 0x20 or > 0x80 || (LuaCClosureUpvalueOffset & 15) != 0)
throw new InvalidDataException("C closure capture alignment changed.");
var captureBytes = Convert.ToHexString(image.Read(captureRva, 6));
Bindings["LuaCClosureCapture"] = new("LuaCClosureCapture", captureRva, captureBytes, "42 0F 11 44 02 ??", false);
}
private void ValidateProfileTables(BinaryImage image)
{
// The VM main-thread field is independently used by pushthread and close.
RequireBytes(image, Address("LuaPushThread"), 100, BitConverter.GetBytes(0x2F8));
RequireBytes(image, Address("LuaClose"), 64, BitConverter.GetBytes(0x2F8));
var profileEntries = image.FindData(BitConverter.GetBytes(image.PreferredBase + (ulong)Address("ProfileUpdate")));
if (profileEntries.Count != 1) throw new InvalidDataException("Profile update table is ambiguous.");
ProfileVtable = profileEntries[0] - 0x140;
ProfileVtables.Add(ProfileVtable);
// Windows' derived manager uses a leaf tail-jump thunk in this slot.
// Its vtable is different from the base manager even though execution
// reaches the same verified update function with the original this.
foreach (var thunk in image.Find("E9 ?? ?? ?? ?? CC CC CC"))
{
if (image.RelativeTarget(thunk + 1) != Address("ProfileUpdate")) continue;
foreach (var entry in image.FindData(BitConverter.GetBytes(image.PreferredBase + (ulong)thunk)))
ProfileVtables.Add(entry - 0x140);
var name = "ProfileUpdateThunk" + thunk.ToString("X");
var bytes = Convert.ToHexString(image.Read(thunk, 8));
Bindings[name] = new(name, thunk, bytes, bytes, true);
}
}
public static uint Hash(string name, uint seed)
{
foreach (var value in Encoding.UTF8.GetBytes(name)) seed = unchecked((seed ^ value) * 0x1000193);
seed = ~seed; return seed << 17 | seed >> 15;
}
private static int Operand(BinaryImage image, int start, int length, string pattern, int offset)
{
var hits = new BytePattern(pattern).Find(image.Read(start, length));
return hits.Count == 1 ? image.ReadInt(start + hits[0] + offset) : throw new InvalidDataException("Native operand is ambiguous: " + pattern);
}
private static int OperandTarget(BinaryImage image, int start, int length, string pattern, int offset)
{
var hits = new BytePattern(pattern).Find(image.Read(start, length));
return hits.Count == 1 ? image.RelativeTarget(start + hits[0] + offset) : throw new InvalidDataException("Native resource reference is ambiguous.");
}
private static void RequireBytes(BinaryImage image, int start, int length, byte[] bytes)
{ if (image.Read(start, length).AsSpan().IndexOf(bytes) < 0) throw new InvalidDataException("Native field contract changed."); }
private static void RequireCall(BinaryImage image, int start, int length, int target)
{ if (!HasCall(image, start, length, target)) throw new InvalidDataException("Native call contract changed."); }
private static bool HasCall(BinaryImage image, int start, int length, int target)
{
var bytes = image.Read(start, length);
for (var i = 0; i < bytes.Length - 4; i++) if (bytes[i] == 0xE8 && image.RelativeTarget(start + i + 1) == target) return true;
return false;
}
private static int RipBeforeCall(BinaryImage image, int start, int length, int target, string opcode, int window)
{
var bytes = image.Read(start, length); var results = new HashSet<int>();
for (var i = window; i < bytes.Length - 4; i++)
if (bytes[i] == 0xE8 && image.RelativeTarget(start + i + 1) == target)
foreach (var hit in new BytePattern(opcode + " ?? ?? ?? ??").Find(bytes.AsSpan(i - window, window))) results.Add(image.RelativeTarget(start + i - window + hit + 3));
return results.Count == 1 ? results.Single() : throw new InvalidDataException("Native resource type is ambiguous.");
}
}
using System.Text;
using System.Text.Json;
namespace XFEWarframe.Client;
/// <summary>Resolved native contracts. An unknown build must satisfy the same independent contracts.</summary>
public sealed class ExperimentalAbi
{
public sealed record Binding(string Name, int Rva, string Bytes, string Pattern, bool Function);
public Dictionary<string, Binding> Bindings { get; } = new(StringComparer.Ordinal);
public Dictionary<uint, uint> Aliases { get; } = [];
public Dictionary<int, int> Relocations { get; } = [];
public Dictionary<string, HashSet<int>> NamedMethods { get; } = new(StringComparer.Ordinal);
public List<string> Problems { get; } = [];
public bool Legacy { get; private init; }
public bool AuditedBuild { get; private init; }
public int SuitDelta { get; private set; }
public int TypeBase { get; private set; }
public int EmptyReference { get; private set; }
public int SpecialItemMetadata { get; private set; }
public int AnimationGetVirtual { get; private set; } = 0x8C0;
public int AnimationSetVirtual { get; private set; } = 0x970;
public uint HashSeed { get; private set; } = 0x7E5AF8E9;
public int ScriptState { get; private set; } = 0x2734D40;
public int ProfileVtable { get; private set; } = 0x214BA70;
public HashSet<int> ProfileVtables { get; } = [];
public int LuaInterruptOffset { get; private set; }
public int LuaCClosureUpvalueOffset { get; private set; }
public bool MultiAbilities => Problems.Count == 0;
private bool luaVerified;
private static readonly string[] LuaContracts = ["LuaPCall", "LuaGetHash", "LuaSetTop", "LuaCreateTable", "LuaCopy", "LuaFindMethod", "LuaPushFunction", "LuaGetMetatable", "LuaGetString", "LuaPushString", "LuaEnsureStack", "LuaClose", "LuaPushThread", "HashBytes", "ProfileUpdate"];
public bool LuaAvailable => LuaInterruptOffset != 0 && Bindings.ContainsKey("LuaInstructionGuard") && Bindings.ContainsKey("LuaInterruptCounter") && (Legacy ? MultiAbilities : luaVerified && LuaContracts.All(Bindings.ContainsKey));
public bool FetchAvailable => LuaAvailable && (Legacy || Aliases.ContainsKey(0xB2A2BA51) && new[] { "GetKubrowPets", "GetRadius", "SetRadius" }.All(name => NamedMethods.TryGetValue(name, out var methods) && methods.Count > 0));
public bool CardRenderingAvailable => LuaAvailable && (Legacy || Bindings.ContainsKey("NativeMovieDraw") && Aliases.ContainsKey(0x297A9947));
public int Address(string name) => Bindings.TryGetValue(name, out var entry) ? entry.Rva : throw new InvalidDataException("Native binding unavailable: " + name);
public int Relocate(int legacyRva) => Legacy ? legacyRva : Relocations.TryGetValue(legacyRva, out var rva) ? rva : throw new InvalidDataException($"Native binding unavailable: 0x{legacyRva:X}");
public uint Alias(uint legacyHash) => Legacy ? legacyHash : Aliases.TryGetValue(legacyHash, out var hash) ? hash : throw new InvalidDataException($"Script binding unavailable: 0x{legacyHash:X8}");
public int Suit(int oldOffset) => checked(oldOffset + SuitDelta);
public static ExperimentalAbi Resolve(BinaryImage image, string hash)
{
if (hash.Equals(ExperimentalAbilityCompatibility.ExecutableSha256, StringComparison.OrdinalIgnoreCase))
{
var legacy = new ExperimentalAbi { Legacy = true, AuditedBuild = true, TypeBase = 0x28A4800, EmptyReference = 0x272F3B0, SpecialItemMetadata = 0x2955360 };
foreach (var entry in ExperimentalAbilityCompatibility.Entries)
{
if (!image.Read(entry.Rva, entry.Bytes.Length / 2).AsSpan().SequenceEqual(Convert.FromHexString(entry.Bytes))) legacy.Problems.Add(entry.Name);
legacy.Bindings[entry.Name] = new(entry.Name, entry.Rva, entry.Bytes, "", true);
}
legacy.ResolveInterruptBudget(image);
legacy.ResolveCClosureCapture(image, 0x80DFE0);
legacy.ProfileVtables.Add(legacy.ProfileVtable);
return legacy;
}
using var manifest = JsonDocument.Parse(typeof(ExperimentalAbi).Assembly.GetManifestResourceStream("XFEWarframe.ExperimentalAbi.json")!);
var root = manifest.RootElement;
var result = new ExperimentalAbi { AuditedBuild = hash.Equals(root.GetProperty("sha256").GetString(), StringComparison.OrdinalIgnoreCase), ScriptState = 0 };
var candidates = root.GetProperty("bindings").EnumerateArray().ToDictionary(row => row.GetProperty("name").GetString()!, row => result.AuditedBuild ? [row.GetProperty("rva").GetInt32()] : image.Find(row.GetProperty("pattern").GetString()!).Where(r => !row.GetProperty("function").GetBoolean() || image.FunctionStart(r) == r).Distinct().ToArray(), StringComparer.Ordinal);
foreach (var row in root.GetProperty("bindings").EnumerateArray())
{
var name = row.GetProperty("name").GetString()!;
var baseline = row.GetProperty("rva").GetInt32();
var pattern = row.GetProperty("pattern").GetString()!;
var function = row.GetProperty("function").GetBoolean();
var required = row.GetProperty("required").GetBoolean();
int[] matches;
if (result.AuditedBuild) matches = [baseline];
else
{
matches = candidates[name];
if (row.TryGetProperty("inside", out var parent) && candidates[parent.GetString()!] is [var parentRva]) matches = matches.Where(r => image.FunctionStart(r) == parentRva).ToArray();
if (row.TryGetProperty("calls", out var callee) && candidates[callee.GetString()!] is [var calleeRva]) matches = matches.Where(r => HasCall(image, r, 105, calleeRva)).ToArray();
if (row.TryGetProperty("calledBy", out var caller) && candidates[caller.GetString()!] is [var callerRva])
{
var window = row.TryGetProperty("callWindow", out var callWindow) ? callWindow.GetInt32() : 64;
matches = matches.Where(r => HasCall(image, callerRva, window, r)).ToArray();
}
}
if (matches.Length != 1)
{
if (required) result.Problems.Add($"{name}: {matches.Length} candidates");
continue;
}
var rva = matches[0];
var expected = result.AuditedBuild ? row.GetProperty("bytes").GetString()! : Convert.ToHexString(image.Read(rva, 32));
if (result.AuditedBuild && !image.Read(rva, expected.Length / 2).AsSpan().SequenceEqual(Convert.FromHexString(expected)))
{ if (required) result.Problems.Add(name + ": signature changed"); continue; }
result.Bindings[name] = new(name, rva, expected, pattern, function);
if (row.TryGetProperty("legacy", out var old)) result.Relocations[old.GetInt32()] = rva;
if (row.TryGetProperty("alias", out var alias))
{
var descriptors = image.FindData(BitConverter.GetBytes(image.PreferredBase + (ulong)rva));
var identifiers = descriptors.Where(r => r >= 8 && image.ReadInt(r - 4) == 0).Select(r => unchecked((uint)image.ReadInt(r - 8))).Where(h => h != 0).Distinct().ToArray();
if (identifiers.Length == 1) result.Aliases[alias.GetUInt32()] = identifiers[0];
else if (required) result.Problems.Add(name + ": export identity is ambiguous");
}
}
result.ResolveInterruptBudget(image);
try { result.ValidateLuaRelationships(image); }
catch (InvalidDataException ex) { result.Problems.Add(ex.Message); }
try { result.ValidateRelationships(image); }
catch (InvalidDataException ex) { result.Problems.Add(ex.Message); }
return result;
}
private void ResolveInterruptBudget(BinaryImage image)
{
try
{
var interrupt = LuaInterruptAbi.Resolve(image);
LuaInterruptOffset = interrupt.Offset;
foreach (var (name, rva, length) in new[] { ("LuaInstructionGuard", interrupt.Guard, 32), ("LuaInterruptCounter", interrupt.Counter, 13) })
{
var bytes = Convert.ToHexString(image.Read(rva, length));
Bindings[name] = new(name, rva, bytes, bytes, true);
}
}
catch (InvalidDataException ex) { Problems.Add(ex.Message); }
}
private void ValidateRelationships(BinaryImage image)
{
// The offsets are derived from the resolved native operations, then checked in
// independent readers/writers. A matching prologue alone cannot authorize an ABI.
var setter = Address("OverrideSet");
var overrideOffset = Operand(image, setter, 48, "4C 8B 89 ?? ?? ?? ??", 3);
SuitDelta = overrideOffset - 0x36C0;
if (SuitDelta is < -0x100 or > 0x800 || (SuitDelta & 7) != 0) throw new InvalidDataException("Power suit layout changed.");
if (Operand(image, Address("OverrideApply"), 36, "48 81 C1 ?? ?? ?? ??", 3) != overrideOffset) throw new InvalidDataException("Override read/write layouts disagree.");
RequireBytes(image, Address("TryActivate"), 500, BitConverter.GetBytes(Suit(0x3448)));
RequireBytes(image, Address("TryActivate"), 500, BitConverter.GetBytes(Suit(0x3450)));
RequireBytes(image, Address("OverrideApply"), 425, BitConverter.GetBytes(Suit(0x3418)));
RequireBytes(image, Address("OverrideApply"), 425, BitConverter.GetBytes(Suit(0x3420)));
RequireCall(image, Address("OverrideApply"), 48, Address("AbilityValidate"));
RequireCall(image, Address("ConfigSerialize"), 1100, Address("TypeSerialize"));
RequireCall(image, Address("SpecialItemLua"), 105, Address("SpecialItem"));
RequireCall(image, Address("SpecialItemLua"), 105, Address("PushSpecialItem"));
if (image.FunctionStart(Address("SuitBeforeRanks")) != Address("SuitInitialize") ||
image.FunctionStart(Address("OverrideInheritScripts")) != Address("OverrideApply")) throw new InvalidDataException("Power suit call graph changed.");
TypeBase = RipBeforeCall(image, Address("ConfigSerialize"), 1100, Address("TypeSerialize"), "4C 8D 05", 24);
EmptyReference = OperandTarget(image, Address("OverrideApply"), 150, "4C 8D 3D ?? ?? ?? ??", 3);
if (OperandTarget(image, Address("StrongReferenceCopy"), 100, "48 8D 35 ?? ?? ?? ??", 3) != EmptyReference)
throw new InvalidDataException("Ability reference ownership contract changed.");
SpecialItemMetadata = OperandTarget(image, Address("SpecialItemLua"), 105, "48 8B 15 ?? ?? ?? ??", 3);
AnimationGetVirtual = Operand(image, Address("AnimationGetLua"), 48, "FF 92 ?? ?? ?? ??", 2);
AnimationSetVirtual = Operand(image, Address("AnimationSetLua"), 300, "FF 90 ?? ?? ?? ??", 2);
if (AnimationGetVirtual is < 0x100 or > 0x2000 || (AnimationGetVirtual & 7) != 0 || AnimationSetVirtual is < 0x100 or > 0x2000 || (AnimationSetVirtual & 7) != 0) throw new InvalidDataException("Animation interface changed.");
}
private void ValidateLuaRelationships(BinaryImage image)
{
foreach (var name in LuaContracts) _ = Address(name);
// C closures carry a debug/context pair before their captures in newer VMs.
// Read the 16-byte capture copy from lua_pushcclosure rather than treating
// a C wrapper as an L closure; their upvalue arrays need not start together.
ResolveCClosureCapture(image, Address("LuaPushFunction"));
HashSeed = unchecked((uint)Operand(image, Address("HashBytes"), 8, "B8 ?? ?? ?? ??", 1));
foreach (var name in new[] { "GetKubrowPets", "GetRadius", "SetRadius" })
{
var pattern = BitConverter.GetBytes(Hash(name, HashSeed)).Concat(new byte[4]).ToArray();
NamedMethods[name] = image.FindData(pattern).Where(r => (r & 7) == 0)
.Select(r => unchecked((int)(BitConverter.ToUInt64(image.Read(r + 8, 8)) - image.PreferredBase)))
.Where(image.IsExecutable).ToHashSet();
}
ValidateProfileTables(image);
// Avoid carrying literal script hashes into a newly salted VM.
foreach (var (old, name) in new (uint, string)[] { (0x1DD8A236, "HasVariable"), (0x433F610A, "GetLocalized"), (0x5D5FD020, "FlashMethod"), (0xBFBBF8CE, "GetAttachedUpgrades") }) Aliases[old] = Hash(name, HashSeed);
luaVerified = true;
}
private void ResolveCClosureCapture(BinaryImage image, int constructor)
{
var capture = new BytePattern("42 0F 11 44 02 ??").Find(image.Read(constructor, 256));
if (capture.Count != 1) throw new InvalidDataException("C closure capture layout is ambiguous.");
var captureRva = constructor + capture[0];
LuaCClosureUpvalueOffset = image.Read(captureRva + 5, 1)[0];
if (LuaCClosureUpvalueOffset is < 0x20 or > 0x80 || (LuaCClosureUpvalueOffset & 15) != 0)
throw new InvalidDataException("C closure capture alignment changed.");
var captureBytes = Convert.ToHexString(image.Read(captureRva, 6));
Bindings["LuaCClosureCapture"] = new("LuaCClosureCapture", captureRva, captureBytes, "42 0F 11 44 02 ??", false);
}
private void ValidateProfileTables(BinaryImage image)
{
// The VM main-thread field is independently used by pushthread and close.
RequireBytes(image, Address("LuaPushThread"), 100, BitConverter.GetBytes(0x2F8));
RequireBytes(image, Address("LuaClose"), 64, BitConverter.GetBytes(0x2F8));
var profileEntries = image.FindData(BitConverter.GetBytes(image.PreferredBase + (ulong)Address("ProfileUpdate")));
if (profileEntries.Count != 1) throw new InvalidDataException("Profile update table is ambiguous.");
ProfileVtable = profileEntries[0] - 0x140;
ProfileVtables.Add(ProfileVtable);
// Windows' derived manager uses a leaf tail-jump thunk in this slot.
// Its vtable is different from the base manager even though execution
// reaches the same verified update function with the original this.
foreach (var thunk in image.Find("E9 ?? ?? ?? ?? CC CC CC"))
{
if (image.RelativeTarget(thunk + 1) != Address("ProfileUpdate")) continue;
foreach (var entry in image.FindData(BitConverter.GetBytes(image.PreferredBase + (ulong)thunk)))
ProfileVtables.Add(entry - 0x140);
var name = "ProfileUpdateThunk" + thunk.ToString("X");
var bytes = Convert.ToHexString(image.Read(thunk, 8));
Bindings[name] = new(name, thunk, bytes, bytes, true);
}
}
public static uint Hash(string name, uint seed)
{
foreach (var value in Encoding.UTF8.GetBytes(name)) seed = unchecked((seed ^ value) * 0x1000193);
seed = ~seed; return seed << 17 | seed >> 15;
}
private static int Operand(BinaryImage image, int start, int length, string pattern, int offset)
{
var hits = new BytePattern(pattern).Find(image.Read(start, length));
return hits.Count == 1 ? image.ReadInt(start + hits[0] + offset) : throw new InvalidDataException("Native operand is ambiguous: " + pattern);
}
private static int OperandTarget(BinaryImage image, int start, int length, string pattern, int offset)
{
var hits = new BytePattern(pattern).Find(image.Read(start, length));
return hits.Count == 1 ? image.RelativeTarget(start + hits[0] + offset) : throw new InvalidDataException("Native resource reference is ambiguous.");
}
private static void RequireBytes(BinaryImage image, int start, int length, byte[] bytes)
{ if (image.Read(start, length).AsSpan().IndexOf(bytes) < 0) throw new InvalidDataException("Native field contract changed."); }
private static void RequireCall(BinaryImage image, int start, int length, int target)
{ if (!HasCall(image, start, length, target)) throw new InvalidDataException("Native call contract changed."); }
private static bool HasCall(BinaryImage image, int start, int length, int target)
{
var bytes = image.Read(start, length);
for (var i = 0; i < bytes.Length - 4; i++) if (bytes[i] == 0xE8 && image.RelativeTarget(start + i + 1) == target) return true;
return false;
}
private static int RipBeforeCall(BinaryImage image, int start, int length, int target, string opcode, int window)
{
var bytes = image.Read(start, length); var results = new HashSet<int>();
for (var i = window; i < bytes.Length - 4; i++)
if (bytes[i] == 0xE8 && image.RelativeTarget(start + i + 1) == target)
foreach (var hit in new BytePattern(opcode + " ?? ?? ?? ??").Find(bytes.AsSpan(i - window, window))) results.Add(image.RelativeTarget(start + i - window + hit + 3));
return results.Count == 1 ? results.Single() : throw new InvalidDataException("Native resource type is ambiguous.");
}
}