XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers.Binary;
using System.Reflection.PortableExecutable;

namespace XFEWarframe.Client;

public sealed class BytePattern
{
    private readonly byte?[] bytes;
    public BytePattern(string text) => bytes = text.Split(' ', StringSplitOptions.RemoveEmptyEntries)
        .Select(x => x is "?" or "??" ? (byte?)null : Convert.ToByte(x, 16)).ToArray();
    public List<int> Find(ReadOnlySpan<byte> data)
    {
        if (bytes.Length == 0) throw new InvalidOperationException("Empty signature.");
        var results = new List<int>();
        var anchor = Array.FindIndex(bytes, b => b.HasValue);
        if (anchor < 0) throw new InvalidOperationException("A signature needs a fixed byte.");
        for (var start = 0; start <= data.Length - bytes.Length;)
        {
            var found = data[(start + anchor)..(data.Length - bytes.Length + anchor + 1)].IndexOf(bytes[anchor]!.Value);
            if (found < 0) break;
            start += found;
            var match = true;
            for (var i = 0; i < bytes.Length; i++)
                if (bytes[i].HasValue && data[start + i] != bytes[i]) { match = false; break; }
            if (match) results.Add(start);
            start++;
        }
        return results;
    }
}

public sealed class BinaryImage : IDisposable
{
    private readonly PEReader reader;
    public byte[] Bytes { get; }
    public int ImageSize => reader.PEHeaders.PEHeader!.SizeOfImage;
    public ulong PreferredBase => reader.PEHeaders.PEHeader!.ImageBase;
    public bool IsExecutable(int rva) => reader.PEHeaders.SectionHeaders.Any(s => s.SectionCharacteristics.HasFlag(SectionCharacteristics.MemExecute) && rva >= s.VirtualAddress && (long)rva < (long)s.VirtualAddress + s.SizeOfRawData);
    public BinaryImage(string path) : this(File.ReadAllBytes(path)) { }
    public BinaryImage(byte[] bytes)
    {
        Bytes = bytes;
        reader = new PEReader(new MemoryStream(Bytes, false));
        if (reader.PEHeaders.CoffHeader.Machine != Machine.Amd64 || reader.PEHeaders.PEHeader?.Magic != PEMagic.PE32Plus)
            throw new InvalidDataException("需要 Windows x64 客户端。");
    }
    public int Offset(int rva, int length = 1)
    {
        foreach (var s in reader.PEHeaders.SectionHeaders)
            if (rva >= s.VirtualAddress && (long)rva + length <= (long)s.VirtualAddress + s.SizeOfRawData)
                return checked(s.PointerToRawData + rva - s.VirtualAddress);
        throw new InvalidDataException($"RVA 0x{rva:X} 不在文件映射范围内。");
    }
    public byte[] Read(int rva, int length) => Bytes.AsSpan(Offset(rva, length), length).ToArray();
    public int ReadInt(int rva) => BinaryPrimitives.ReadInt32LittleEndian(Read(rva, 4));
    public int RelativeTarget(int operandRva) => checked(operandRva + 4 + ReadInt(operandRva));
    public List<int> Find(string pattern)
    {
        var matcher = new BytePattern(pattern);
        return reader.PEHeaders.SectionHeaders
            .Where(s => s.SectionCharacteristics.HasFlag(SectionCharacteristics.MemExecute))
            .SelectMany(s => matcher.Find(Bytes.AsSpan(s.PointerToRawData, s.SizeOfRawData)).Select(o => s.VirtualAddress + o))
            .ToList();
    }
    public List<int> FindAscii(string text)
    {
        var needle = System.Text.Encoding.ASCII.GetBytes(text + '\0');
        var matches = new List<int>();
        foreach (var section in reader.PEHeaders.SectionHeaders.Where(s => !s.SectionCharacteristics.HasFlag(SectionCharacteristics.MemExecute)))
        {
            var data = Bytes.AsSpan(section.PointerToRawData, section.SizeOfRawData);
            for (var offset = 0; offset <= data.Length - needle.Length;)
            {
                var found = data[offset..].IndexOf(needle);
                if (found < 0) break;
                offset += found;
                matches.Add(section.VirtualAddress + offset++);
            }
        }
        return matches;
    }
    public List<int> FindData(byte[] needle)
    {
        if (needle.Length == 0) throw new ArgumentException("Empty data signature.");
        var matches = new List<int>();
        foreach (var section in reader.PEHeaders.SectionHeaders.Where(s => !s.SectionCharacteristics.HasFlag(SectionCharacteristics.MemExecute)))
        {
            var data = Bytes.AsSpan(section.PointerToRawData, section.SizeOfRawData);
            for (var offset = 0; offset <= data.Length - needle.Length;)
            {
                var found = data[offset..].IndexOf(needle);
                if (found < 0) break;
                offset += found;
                matches.Add(section.VirtualAddress + offset++);
            }
        }
        return matches;
    }
    public int FunctionStart(int rva) => TryFunctionStart(rva, out var entry) ? entry : rva;
    public bool TryFunctionStart(int rva, out int entry)
    {
        entry = rva;
        var table = reader.PEHeaders.PEHeader!.ExceptionTableDirectory;
        if (table.Size == 0) return false;
        var offset = Offset(table.RelativeVirtualAddress, table.Size);
        var low = 0; var high = table.Size / 12 - 1;
        while (low <= high)
        {
            var mid = (low + high) / 2;
            var span = Bytes.AsSpan(offset + mid * 12, 12);
            var begin = BinaryPrimitives.ReadInt32LittleEndian(span);
            var end = BinaryPrimitives.ReadInt32LittleEndian(span[4..]);
            if (rva < begin) high = mid - 1;
            else if (rva >= end) low = mid + 1;
            else
            {
                var unwind = BinaryPrimitives.ReadInt32LittleEndian(span[8..]);
                var visited = new HashSet<int>();
                while (true)
                {
                    if (begin <= 0 || end <= begin || end > ImageSize || !visited.Add(unwind) || visited.Count > 32)
                        throw new InvalidDataException("无效或循环的 x64 函数展开信息。");
                    var header = Read(unwind, 4);
                    if ((header[0] >> 3 & 4) == 0) { entry = begin; return true; }
                    if ((header[0] & 7) is not (1 or 2) || (header[0] >> 3 & 3) != 0)
                        throw new InvalidDataException("不支持的 x64 链式函数展开信息。");
                    // UNW_FLAG_CHAININFO ends with another RUNTIME_FUNCTION, after
                    // the unwind codes rounded up to an even number of slots.
                    var parent = Read(checked(unwind + 4 + (header[2] + 1) / 2 * 4), 12);
                    begin = BinaryPrimitives.ReadInt32LittleEndian(parent);
                    end = BinaryPrimitives.ReadInt32LittleEndian(parent.AsSpan(4));
                    unwind = BinaryPrimitives.ReadInt32LittleEndian(parent.AsSpan(8));
                }
            }
        }
        return false; // x64 leaf routines need not have an unwind entry.
    }
    public int ExportRva(string name)
    {
        var table = reader.PEHeaders.PEHeader!.ExportTableDirectory;
        if (table.Size == 0) throw new InvalidDataException("组件没有原生导出。");
        var count = ReadInt(table.RelativeVirtualAddress + 24);
        var functions = ReadInt(table.RelativeVirtualAddress + 28);
        var names = ReadInt(table.RelativeVirtualAddress + 32);
        var ordinals = ReadInt(table.RelativeVirtualAddress + 36);
        for (var i = 0; i < count; i++)
        {
            var n = Offset(ReadInt(names + i * 4));
            var end = Array.IndexOf(Bytes, (byte)0, n);
            if (end < n) throw new InvalidDataException("Invalid export name.");
            if (System.Text.Encoding.ASCII.GetString(Bytes, n, end - n) != name) continue;
            var ordinal = BinaryPrimitives.ReadUInt16LittleEndian(Read(ordinals + i * 2, 2));
            return ReadInt(functions + ordinal * 4);
        }
        throw new InvalidDataException($"组件缺少 {name} 导出。");
    }
    public void Dispose() => reader.Dispose();
}