using System.ComponentModel; using System.Security.Cryptography; namespace XFEEDToolBox.Plugin; internal sealed class NativeAccessException : Exception { internal uint Status { get; } internal NativeAccessException(string message, uint status = 0xc0000005) : base(message) { Status = status; HResult = unchecked((int)status); } } internal static unsafe class Platform { internal const string GameHash = "ed5a8f8cd10f9a80d3bda5badd7ba1d4fcfc15996c8c7e018852cb170e264b63"; internal const string PluginVersion = "0.5.29-dev"; internal static int ProcessId => Environment.ProcessId; internal static nuint ImageBase => (nuint)GetModuleHandleW(null); internal static nuint ImageEnd { get { var start = ImageBase; return start + Read(start + (nuint)Read(start + 0x3c) + 0x50); } } internal static T Read(nuint address) where T : unmanaged { T value = default; if (XfeCopy(&value, (void*)address, (nuint)sizeof(T)) == 0) throw new NativeAccessException("Native memory is no longer readable"); return value; } internal static void Write(nuint address, T value) where T : unmanaged { if (XfeCopy((void*)address, &value, (nuint)sizeof(T)) == 0) throw new NativeAccessException("Native memory is no longer writable"); } internal static nuint Pointer(nuint address) => Read(address); internal static byte[] ReadBytes(nuint address, int count) { var bytes = new byte[count]; fixed (byte* destination = bytes) if (XfeCopy(destination, (void*)address, (nuint)count) == 0) throw new NativeAccessException("Native memory is no longer readable"); return bytes; } internal static void WriteBytes(nuint address, ReadOnlySpan bytes) { fixed (byte* source = bytes) if (XfeCopy((void*)address, source, (nuint)bytes.Length) == 0) throw new NativeAccessException("Native memory is no longer writable"); } internal static ulong F32(float value) => BitConverter.SingleToUInt32Bits(value); internal static ulong F64(double value) => BitConverter.DoubleToUInt64Bits(value); internal static ulong Call(nuint function, params ulong[] arguments) => Invoke(function, arguments, false); internal static float CallFloat(nuint function, params ulong[] arguments) => BitConverter.UInt32BitsToSingle((uint)Invoke(function, arguments, true)); internal static double CallDouble(nuint function, params ulong[] arguments) => BitConverter.UInt64BitsToDouble(Invoke(function, arguments, true)); private static ulong Invoke(nuint function, ulong[] arguments, bool floating) { ulong* result = stackalloc ulong[2]; fixed (ulong* input = arguments) { var status = XfeCall(function, input, (uint)arguments.Length, result); if (status != 0) throw new NativeAccessException($"Native call failed (0x{status:x8})", status); } return result[floating ? 1 : 0]; } internal static ulong Utc() => (ulong)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); private static readonly Lazy atomicDecrementEntry = new(() => { // Keep a potentially faulting atomic instruction outside the AOT code-manager range. // mov eax,-1; lock xadd [rcx],eax; dec eax; ret. The caller's SEH boundary // catches a concurrently invalidated address before re-entering managed code. var code = new byte[] { 0xb8,0xff,0xff,0xff,0xff,0xf0,0x0f,0xc1,0x01,0xff,0xc8,0xc3 }; var memory = Allocate(4096); if (memory == 0) throw new NativeAccessException("Could not allocate native atomic entry"); try { WriteBytes(memory, code); if (!Protect(memory, 4096, 0x20, out _) || !FlushCode(memory, (nuint)code.Length)) throw new NativeAccessException("Could not protect native atomic entry"); return memory; } catch { Free(memory); throw; } }); internal static int AtomicDecrement(nuint address) { return unchecked((int)Call(atomicDecrementEntry.Value, (ulong)address)); } internal static string ModulePath(nuint module = 0) { var buffer = new char[32768]; fixed (char* value = buffer) { var length = GetModuleFileNameW((nint)module, value, buffer.Length); if (length == 0 || length >= buffer.Length) throw new Win32Exception(Marshal.GetLastWin32Error()); return new string(value, 0, (int)length); } } internal static string ImageHash(string path) { try { using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); return Convert.ToHexStringLower(SHA256.HashData(file)); } catch (IOException) { return ""; } catch (UnauthorizedAccessException) { return ""; } } internal static bool Pin(nuint address) => GetModuleHandleExW(0x5, address, out _); internal static nuint Allocate(nuint bytes, uint protection = 4) => (nuint)VirtualAlloc(0, bytes, 0x3000, protection); internal static void Free(nuint address) { if (address != 0) VirtualFree((nint)address, 0, 0x8000); } internal static bool Protect(nuint address, nuint size, uint protection, out uint previous) => VirtualProtect((nint)address, size, protection, out previous); internal static bool FlushCode(nuint address, nuint length) => FlushInstructionCache(new nint(-1), (nint)address, length); [DllImport("XfePlatform", EntryPoint = "XfeCopy")] private static extern int XfeCopy(void* destination, void* source, nuint count); [DllImport("XfePlatform", EntryPoint = "XfeCall")] private static extern uint XfeCall(nuint function, ulong* arguments, uint count, ulong* results); [DllImport("XfePlatform", EntryPoint = "XfeHookInitialize")] internal static extern int HookInitialize(); [DllImport("XfePlatform", EntryPoint = "XfeHookCreate")] internal static extern int HookCreate(nuint target, nuint callback, out nuint original); [DllImport("XfePlatform", EntryPoint = "XfeHookEnable")] internal static extern int HookEnable(nuint target); [DllImport("XfePlatform", EntryPoint = "XfeHookDisable")] internal static extern int HookDisable(nuint target); [DllImport("XfePlatform", EntryPoint = "XfeHookRemove")] internal static extern int HookRemove(nuint target); [DllImport("XfePlatform", EntryPoint = "XfeHookQueueEnable")] internal static extern int HookQueueEnable(nuint target); [DllImport("XfePlatform", EntryPoint = "XfeHookApplyQueued")] internal static extern int HookApplyQueued(); [DllImport("XfePlatform", EntryPoint = "XfeObserver")] internal static extern nuint Observer(nuint callback, out nuint original, nuint target); [DllImport("XfePlatform", EntryPoint = "XfeFreeObserver")] internal static extern void FreeObserver(nuint address); [DllImport("kernel32.dll")] internal static extern ulong GetTickCount64(); [DllImport("kernel32.dll")] internal static extern uint GetCurrentThreadId(); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern nint GetModuleHandleW(string? name); [DllImport("kernel32.dll", SetLastError = true)] private static extern uint GetModuleFileNameW(nint module, char* buffer, int size); [DllImport("kernel32.dll", EntryPoint = "GetModuleHandleExW", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetModuleHandleExW(uint flags, nuint address, out nint module); [DllImport("kernel32.dll", SetLastError = true)] internal static extern nint VirtualAlloc(nint address, nuint size, uint allocation, uint protection); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool VirtualFree(nint address, nuint size, uint type); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool VirtualProtect(nint address, nuint size, uint protection, out uint previous); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool FlushInstructionCache(nint process, nint address, nuint size); [DllImport("kernel32.dll")] internal static extern uint GetLastError(); [DllImport("kernel32.dll")] internal static extern void SetLastError(uint error); }