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

HaloPixelToolBox

【WinUI3】基于USB HID通讯的花再音响工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers.Binary;
using System.Security.Cryptography;
using HaloPixelToolBox.Core.Models.Bar;

namespace HaloPixelToolBox.Core.Utilities;

/// <summary>
/// 从网易云音乐模块的 PE 代码段中寻找歌词全局指针槽。
/// </summary>
public static class CloudMusicSignatureScanner
{
    private const uint ImageScnMemExecute = 0x20000000;

    // MSVC 为全局对象生成的析构路径:先取得全局槽、调用析构,再把同一槽清零。
    // 两条 RIP 相对指令必须解码到同一个 RVA,以避免把普通析构函数误认为歌词对象。
    private static readonly byte?[] Signature =
    [
        0x48, 0x8D, 0x0D, null, null, null, null,
        0xE8, null, null, null, null,
        0x48, 0x8B, 0xC8,
        0xE8, null, null, null, null,
        0x48, 0xC7, 0x05, null, null, null, null,
        0x00, 0x00, 0x00, 0x00
    ];

    public static long[] DefaultOffsets { get; } = [0x120, 0x8, 0x0];

    public static string ComputeModuleHash(string modulePath)
    {
        using var stream = File.OpenRead(modulePath);
        return Convert.ToHexString(SHA256.HashData(stream));
    }

    public static IReadOnlyList<AddressResolverModel> FindResolvers(string modulePath, string version)
    {
        var image = File.ReadAllBytes(modulePath);
        return FindBaseAddresses(image)
            .Select(baseAddress => new AddressResolverModel
            {
                Version = version,
                ModuleName = Path.GetFileName(modulePath),
                BaseAddress = baseAddress,
                Offsets = [.. DefaultOffsets]
            })
            .ToArray();
    }

    /// <summary>
    /// 在 PE 映像的可执行节中查找所有经过双重 RIP 目标校验的候选 RVA。
    /// </summary>
    public static IReadOnlyList<long> FindBaseAddresses(ReadOnlySpan<byte> image)
    {
        if (!TryReadPeLayout(image, out var sectionTableOffset, out var sectionCount, out var imageSize))
            return [];

        var candidates = new HashSet<long>();
        for (var sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++)
        {
            var sectionOffset = sectionTableOffset + sectionIndex * 40;
            if (sectionOffset < 0 || sectionOffset + 40 > image.Length)
                return [];

            var virtualAddress = BinaryPrimitives.ReadUInt32LittleEndian(image.Slice(sectionOffset + 12, 4));
            var rawSize = BinaryPrimitives.ReadUInt32LittleEndian(image.Slice(sectionOffset + 16, 4));
            var rawOffset = BinaryPrimitives.ReadUInt32LittleEndian(image.Slice(sectionOffset + 20, 4));
            var characteristics = BinaryPrimitives.ReadUInt32LittleEndian(image.Slice(sectionOffset + 36, 4));
            if ((characteristics & ImageScnMemExecute) == 0 || rawSize < Signature.Length || rawOffset >= image.Length)
                continue;

            var sectionEnd = Math.Min((long)image.Length, (long)rawOffset + rawSize);
            var lastStart = sectionEnd - Signature.Length;
            for (var fileOffset = (long)rawOffset; fileOffset <= lastStart; fileOffset++)
            {
                if (image[(int)fileOffset] != Signature[0] || !Matches(image, (int)fileOffset))
                    continue;

                var instructionRva = (long)virtualAddress + fileOffset - rawOffset;
                var firstDisplacement = BinaryPrimitives.ReadInt32LittleEndian(image.Slice((int)fileOffset + 3, 4));
                var secondDisplacement = BinaryPrimitives.ReadInt32LittleEndian(image.Slice((int)fileOffset + 23, 4));
                var firstTarget = instructionRva + 7 + firstDisplacement;
                var secondTarget = instructionRva + Signature.Length + secondDisplacement;
                if (firstTarget == secondTarget && firstTarget > 0 && firstTarget < imageSize)
                    candidates.Add(firstTarget);
            }
        }

        return candidates.Order().ToArray();
    }

    private static bool Matches(ReadOnlySpan<byte> image, int offset)
    {
        for (var index = 1; index < Signature.Length; index++)
        {
            if (Signature[index] is byte expected && image[offset + index] != expected)
                return false;
        }
        return true;
    }

    private static bool TryReadPeLayout(
        ReadOnlySpan<byte> image,
        out int sectionTableOffset,
        out int sectionCount,
        out uint imageSize)
    {
        sectionTableOffset = 0;
        sectionCount = 0;
        imageSize = 0;
        if (image.Length < 0x40 || image[0] != (byte)'M' || image[1] != (byte)'Z')
            return false;

        var peOffset = BinaryPrimitives.ReadInt32LittleEndian(image.Slice(0x3C, 4));
        if (peOffset < 0 || peOffset + 24 > image.Length ||
            image[peOffset] != (byte)'P' || image[peOffset + 1] != (byte)'E' ||
            image[peOffset + 2] != 0 || image[peOffset + 3] != 0)
            return false;

        sectionCount = BinaryPrimitives.ReadUInt16LittleEndian(image.Slice(peOffset + 6, 2));
        var optionalHeaderSize = BinaryPrimitives.ReadUInt16LittleEndian(image.Slice(peOffset + 20, 2));
        var optionalHeaderOffset = peOffset + 24;
        sectionTableOffset = optionalHeaderOffset + optionalHeaderSize;
        if (optionalHeaderSize < 60 || optionalHeaderOffset + optionalHeaderSize > image.Length ||
            sectionCount <= 0 || sectionTableOffset + sectionCount * 40 > image.Length)
            return false;

        imageSize = BinaryPrimitives.ReadUInt32LittleEndian(image.Slice(optionalHeaderOffset + 56, 4));
        return imageSize > 0;
    }
}