using System.Runtime.InteropServices; using System.Text; using System.Text.Json.Nodes; namespace XFEWarframe.Bridge; // Engine Lua ABI. General script execution is exposed only by the opt-in test adapter. // Production dependency resolution uses only fixed, audited donor resource paths. internal static unsafe partial class GameTestLua { private static nint image; // A returned item descriptor points into its resource template. Retain a bounded // set of donor templates for the module lifetime, just as the game's resource cache // does, so Lua userdata never observes a released template after a level change. private static readonly Dictionary RetainedResources = new(StringComparer.Ordinal); internal static void Prepare(nint module) { if (image == module) return; image = module; Check(0x13C58E0, "48895C24084889742410574883EC404533D2418BF0448BDA"); Check(0x13D5840, "48895C24185556574883EC40488B05EDA34B014833C44889"); Check(0x4BFCC0, "85D2783F4C8B41104C63CA488B51084D03C94B8D04C8483B"); Check(0xFADDA0, "48895C240848896C24104889742418574883EC204C8B4918"); } private static void Check(int rva, string bytes) { GameAbi.Check(image, rva, bytes); } private static int Top(nint state) => (int)((*(nint*)(state + 8) - *(nint*)(state + 0x10)) / 16); private static nint Value(nint state, int index) => *(nint*)(state + 0x10) + (index - 1) * 16; private static int Type(nint state, int index) => *(int*)(Value(state, index) + 12); private static void SetTop(nint state, int index) => ((delegate* unmanaged)(image + GameAbi.Rva(0x4BFCC0)))(state, index); private static void Copy(nint state, int index) => ((delegate* unmanaged)(image + GameAbi.Rva(0x1276310)))(state, index); private static void PushHash(nint state, uint hash) { var value = *(nint*)(state + 8); *(uint*)value = hash; *(int*)(value + 12) = 1; *(nint*)(state + 8) = value + 16; } private static uint Hash(string name) { if (name.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { var identifier = Convert.ToUInt32(name[2..], 16); if (identifier == 0x02D5AC03 && !GameAbi.Current.Legacy && !GameAbi.Current.Aliases.ContainsKey(identifier)) { using var lua = new Scope(); ResolveFingerprintSetter(lua, lua.Require("Lotus.Interface.CardUtilitiesRedux")); } return GameAbi.Current.Alias(identifier); } return XFEWarframe.Client.ExperimentalAbi.Hash(name, GameAbi.Current.HashSeed); } private static void Get(nint state, int index, string name, bool literal = false) { if (index > 0 && Type(state, index) == 9) { var metadata = ObjectMetadata(Value(state, index)); var function = ((delegate* unmanaged)(image + GameAbi.Rva(0x197C370)))(metadata, Hash(name)); if (function != 0) { ((delegate* unmanaged)(image + GameAbi.Rva(0x80DFE0)))(state, function, 0, 0, 0); return; } // Userdata access can throw a Lua error. Invoke its __index through pcall, // so longjmp never crosses a managed callback frame. var before = Top(state); if (((delegate* unmanaged)(image + GameAbi.Rva(0x16A5D40)))(state, index) == 0) throw new InvalidOperationException("The object has no script metatable."); Get(state, Top(state), "__index", true); if (Type(state, Top(state)) == 8) { Copy(state, index); if (literal) PushString(state, name); else PushHash(state, Hash(name)); Call(state, 2); } else if (Type(state, Top(state)) == 7) Get(state, Top(state), name, literal); else throw new InvalidOperationException("Unsupported script index handler."); new ReadOnlySpan((void*)Value(state, Top(state)), 16).CopyTo(new Span((void*)Value(state, before + 1), 16)); SetTop(state, before + 1); return; } if (index > 0 && Type(state, index) != 7) throw new InvalidOperationException("A table or engine object is required."); if (!literal) ((delegate* unmanaged)(image + GameAbi.Rva(0x13D5840)))(state, index, Hash(name)); else { var bytes = Encoding.UTF8.GetBytes(name + '\0'); fixed (byte* pointer = bytes) ((delegate* unmanaged)(image + GameAbi.Rva(0x18C6370)))(state, index, pointer); } } private static void PushString(nint state, string text, int maximumLength = 2048) { if (text.Length > maximumLength || text.Contains('\0')) throw new ArgumentException("Script string too long or contains NUL."); var bytes = Encoding.UTF8.GetBytes(text + '\0'); fixed (byte* pointer = bytes) ((delegate* unmanaged)(image + GameAbi.Rva(0xBFDC40)))(state, pointer); } private static void Call(nint state, int arguments) { var result = ((delegate* unmanaged)(image + GameAbi.Rva(0x13C58E0)))(state, arguments, 1, 0); if (result != 0) throw new InvalidOperationException("Game script error: " + Describe(Value(state, Top(state))).ToJsonString()); } internal static bool TrySuitAndSlot(nint state, out nint suit, out int slot) { suit = 0; slot = -1; if (Top(state) < 2 || Type(state, 1) != 9 || Type(state, 2) != 3) return false; var requested = *(float*)Value(state, 2); if (!float.IsFinite(requested) || requested != MathF.Truncate(requested) || requested is < 5 or > 7) return false; var reference = *(nint*)(*(nint*)Value(state, 1) + 0x18); suit = reference == 0 ? 0 : *(nint*)reference; slot = (int)requested; return suit != 0; } internal static nint RetainResource(nint state, string path) { if (RetainedResources.TryGetValue(path, out var retained)) return *(nint*)retained; if (RetainedResources.Count >= 32) throw new InvalidOperationException("Ability resource cache limit reached."); var saved = Top(state); ((delegate* unmanaged)(image + GameAbi.Rva(0x11E1C40)))(state, 16); try { Get(state, -10002, "Type"); PushString(state, path); Call(state, 1); if (Type(state, Top(state)) != 9) throw new InvalidOperationException("Donor resource did not load."); var reference = *(nint*)(*(nint*)Value(state, Top(state)) + 0x18); if (reference == 0 || *(nint*)reference == 0) throw new InvalidOperationException("Donor resource is empty."); // Resource userdata stores the native strong reference at +0x18; matching // retain operations are audited at the game's PushResource, RVA 0x6CE142. ++*(int*)(reference + 8); ++*(int*)(reference + 12); RetainedResources.Add(path, reference); return *(nint*)reference; } finally { SetTop(state, saved); } } internal static nint RetainResourceReference(nint state, string path) { RetainResource(state, path); return RetainedResources[path]; } internal static JsonObject WithLocalSuit(Func action) { var state = MainState(); if (state == 0) throw new InvalidOperationException("Game scripts are not initialized."); var saved = Top(state); ((delegate* unmanaged)(image + GameAbi.Rva(0x11E1C40)))(state, 32); try { Get(state, -10002, "gRegion"); foreach (var method in new[] { "GetLocalPlayerAvatar", "InventoryControl", "GetActivePowerSuit" }) { var self = Top(state); if (Type(state, self) != 9) throw new InvalidOperationException("Local player is not ready."); Get(state, self, method); Copy(state, self); Call(state, 1); } if (Type(state, Top(state)) != 9) throw new InvalidOperationException("Local suit is not ready."); // Same Entity userdata/ref layout as the audited engine binding at RVA 0x1644EE0. var userdata = *(nint*)Value(state, Top(state)); var reference = *(nint*)(userdata + 0x18); var suit = reference == 0 ? 0 : *(nint*)reference; if (suit == 0) throw new InvalidOperationException("Local suit has been destroyed."); return action(suit); } finally { SetTop(state, saved); } } internal static JsonObject Execute(JsonObject body) { var steps = body["steps"] as JsonArray ?? throw new ArgumentException("Script steps required."); if (steps.Count is < 1 or > 24) throw new ArgumentException("Use 1 to 24 script steps."); var state = MainState(); if (state == 0) throw new InvalidOperationException("Game scripts are not initialized."); var saved = Top(state); // Reserve stack space through the engine before any push. ((delegate* unmanaged)(image + GameAbi.Rva(0x11E1C40)))(state, 128); var indices = new List(); var output = new JsonArray(); int Reference(JsonNode? node) { var reference = node?.GetValue() ?? -1; return reference >= 0 && reference < indices.Count ? indices[reference] : throw new ArgumentException("Invalid script step reference."); } try { foreach (var node in steps) { var step = node as JsonObject ?? throw new ArgumentException("Script step object required."); if (step["global"] is { } global) Get(state, -10002, global.GetValue()); else if (step["field"] is { } field) Get(state, Reference(step["from"]), field.GetValue(), step["literal"]?.GetValue() == true); else if (step["meta"] is { } meta) { if (((delegate* unmanaged)(image + GameAbi.Rva(0x16A5D40)))(state, Reference(meta)) == 0) throw new InvalidOperationException("No script metatable."); } else if (step["call"] is { } function) { var index = Reference(function); if (Type(state, index) != 8) throw new InvalidOperationException("Script value is not callable."); var arguments = step["args"] as JsonArray ?? []; if (arguments.Count > 16) throw new ArgumentException("Too many script arguments."); Copy(state, index); foreach (var argument in arguments) { if (argument is JsonObject reference) Copy(state, Reference(reference["ref"])); else if (argument is JsonValue scalar && scalar.TryGetValue(out var text)) PushString(state, text); else { var value = *(nint*)(state + 8); new Span((void*)value, 16).Clear(); if (argument is JsonValue boolean && boolean.TryGetValue(out var flag)) { *(int*)value = flag ? 1 : 0; *(int*)(value + 12) = 1; } else if (argument is not null) { *(float*)value = argument.GetValue(); *(int*)(value + 12) = 3; } *(nint*)(state + 8) = value + 16; } } Call(state, arguments.Count); } else throw new ArgumentException("Unknown script step."); var current = Top(state); indices.Add(current); var description = Describe(Value(state, current)); if (step["inspect"]?.GetValue() == true && Type(state, current) == 7) description["fields"] = Table(*(nint*)Value(state, current)); if (step["inspect"]?.GetValue() == true && Type(state, current) == 9) description["methods"] = Methods(Value(state, current)); output.Add((JsonNode)description); } return new JsonObject { ["results"] = output }; } finally { SetTop(state, saved); } } private static JsonObject Describe(nint value) { var type = *(int*)(value + 12) & 15; var result = new JsonObject { ["type"] = type }; if (type == 1) result["hashOrBoolean"] = $"0x{*(uint*)value:X8}"; else if (type == 3) result["number"] = *(float*)value; else if (type == 6) { var text = *(nint*)value; var length = Math.Min(*(uint*)(text + 0x14), 2048u); result["text"] = Encoding.UTF8.GetString(new ReadOnlySpan((void*)(text + 0x18), (int)length)); } else if (type is 7 or 8 or 9) { result["object"] = $"0x{*(nint*)value:X}"; if (type == 8 && *(byte*)(*(nint*)value + 3) != 0) result["native"] = $"0x{*(nint*)(*(nint*)value + 0x18) - image:X}"; } return result; } private static JsonArray Table(nint table) { var result = new JsonArray(); var bits = *(byte*)(table + 6); if (bits > 16) throw new InvalidOperationException("Unexpected script table layout."); var nodes = *(nint*)(table + 0x20); for (var index = 0; index < (1 << bits) && result.Count < 256; index++) { var entry = nodes + index * 32; if (*(int*)(entry + 12) == 0) continue; result.Add((JsonNode)new JsonObject { ["key"] = Describe(entry + 16), ["value"] = Describe(entry) }); } return result; } private static nint ObjectMetadata(nint value) { var userData = *(nint*)(*(nint*)value + 0x10) & ~31; if (userData == 0) throw new InvalidOperationException("Script engine object is unavailable."); return *(nint*)(userData + 0x18); } private static JsonArray Methods(nint value) { var metadata = ObjectMetadata(value); var hashes = *(nint*)(metadata + 0x48); var methods = *(nint*)(metadata + 0x58); var count = *(uint*)(metadata + 0x50) / 4; if (count > 4096) throw new InvalidOperationException("Unexpected method metadata."); var result = new JsonArray(); for (var index = 0; index < count; index++) result.Add((JsonNode)new JsonObject { ["hash"] = $"0x{*(uint*)(hashes + index * 4):X8}", ["native"] = $"0x{*(nint*)(methods + index * 8) - image:X}" }); return result; } }