using System.Buffers.Binary;
using System.Diagnostics;
using System.Text;
using XFEWorkflow.Plugins.WeCom.Native.Core;
using XFEWorkflow.Plugins.WeCom.Native.MemoryLab;
namespace XFEWorkflow.Plugins.WeCom.Native.Integrations;
internal sealed record NativeBinding(TypedMemorySnapshot Snapshot, uint ManagerControl, uint ManagerObject);
internal static class NativeDiscovery
{
internal static IReadOnlyList<WeComMember> ReadCachedContacts(int processId, uint imageBase, CancellationToken token)
{
using ProcessMemory memory = new(processId);
if (memory.GetMachine().ProcessMachine != 0x014c) throw new NotSupportedException("联系人读取要求 x86 企业微信。");
uint vtable = imageBase + 0x0AF98B84;
byte[] word = new byte[4], locator = new byte[20], rtti = new byte[256];
if (memory.Read(vtable - 4, word, 4) != 4 || memory.Read(Word(word, 0), locator, 20) != 20 ||
Word(locator, 0) != 0 || Word(locator, 4) != 0) throw new InvalidOperationException("联系人 RTTI 定位结构不匹配。");
int rttiLength = memory.Read(Word(locator, 12) + 8, rtti, rtti.Length);
int rttiEnd = rtti.AsSpan(0, rttiLength).IndexOf((byte)0);
if (rttiEnd < 0 || Encoding.ASCII.GetString(rtti, 0, rttiEnd) != ".?AV?$_Ref_count_obj2@VUser@model@wework@@@std@@")
throw new InvalidOperationException("联系人原生类型不匹配。");
byte[] signature = BitConverter.GetBytes(vtable), chunk = new byte[1024 * 1024 + 3];
Dictionary<string, HashSet<string>> contacts = new(StringComparer.Ordinal);
Stopwatch budget = Stopwatch.StartNew();
foreach (var region in memory.Regions(0x1_0000_0000))
{
if (!region.IsReadablePrivateData) continue;
for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
{
token.ThrowIfCancellationRequested();
if (budget.Elapsed > TimeSpan.FromSeconds(8)) throw new TimeoutException("联系人读取超时,请稍后重新读取。");
ulong start = (ulong)region.BaseAddress + offset;
int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
int position = 0;
while (position <= count - 4)
{
int relative = chunk.AsSpan(position, count - position).IndexOf(signature);
if (relative < 0) break;
int found = position + relative; position = found + 4;
ulong address = start + (uint)found;
if (address % 4 != 0) continue;
byte[] data = new byte[48];
if (memory.Read(address, data, data.Length) != data.Length || Word(data, 0) != vtable ||
Word(data, 4) is 0 or >= 1000000 || Word(data, 8) is 0 or >= 1000000) continue;
ulong id = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16));
if (id is 0 or ulong.MaxValue) continue;
string? name = ReadString(memory, data, 24);
if (string.IsNullOrWhiteSpace(name) || name.Any(char.IsControl)) continue;
string uid = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (!contacts.TryGetValue(uid, out HashSet<string>? names))
{
if (contacts.Count >= 20000) throw new InvalidOperationException("缓存联系人数量超出读取范围。");
contacts[uid] = names = new(StringComparer.Ordinal);
}
if (names.Count < 4) names.Add(name);
}
}
}
return contacts.Select(c => new WeComMember(c.Key, string.Join(" / ", c.Value.Order(StringComparer.Ordinal))))
.OrderBy(c => c.DisplayName, StringComparer.CurrentCulture).ThenBy(c => c.Id, StringComparer.Ordinal).ToArray();
}
internal static IReadOnlyList<WeComMessage> ReadReceivedMessages(NativeBinding binding, string selfId, CancellationToken token)
{
uint imageBase = Convert.ToUInt32(binding.Snapshot.ImageBase[2..], 16);
using ProcessMemory memory = new(binding.Snapshot.ProcessId);
byte[] signature = BitConverter.GetBytes(imageBase + 0x0AF984F0);
byte[] chunk = new byte[1024 * 1024 + 3];
Dictionary<string, WeComMessage> result = new(StringComparer.Ordinal);
Stopwatch budget = Stopwatch.StartNew();
foreach (var region in memory.Regions(0x1_0000_0000))
{
if (!region.IsReadablePrivateData) continue;
for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
{
token.ThrowIfCancellationRequested();
if (budget.Elapsed > TimeSpan.FromSeconds(5)) throw new TimeoutException("内存增量读取超时。");
ulong start = (ulong)region.BaseAddress + offset;
int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
int position = 0;
while (position <= count - 4)
{
int relative = chunk.AsSpan(position, count - position).IndexOf(signature);
if (relative < 0) break;
int found = position + relative; position = found + 4;
if ((start + (uint)found) % 4 != 0) continue;
byte[] data = new byte[0x78];
if (memory.Read(start + (uint)found, data, data.Length) != data.Length) continue;
if (Word(data, 0) != imageBase + 0x0AF984F0) continue;
if (Word(data, 4) is 0 or >= 1000000 || Word(data, 8) is 0 or >= 1000000) continue;
string? conversationId = ReadString(memory, data, 16 + 0x28);
if (!ReplySettings.ValidId(conversationId)) continue;
string sender = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16 + 0x48)).ToString(System.Globalization.CultureInfo.InvariantCulture);
if (sender == "0" || sender == ulong.MaxValue.ToString(System.Globalization.CultureInfo.InvariantCulture)) continue;
ulong localId = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16));
string? clientId = ReadString(memory, data, 16 + 0x10);
if (localId == 0 && string.IsNullOrEmpty(clientId)) continue;
string id = string.IsNullOrEmpty(clientId) ? "L:" + localId : clientId;
ulong unix = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16 + 0x58));
if (unix is < 1262304000 or > 4102444800) continue;
uint type = Word(data, 16 + 0x50);
result.TryAdd(conversationId + ":" + id, new(id, conversationId!, sender,
type == 4 ? MessageKind.MergedForward : type == 2 ? MessageKind.Text : MessageKind.Unknown, "",
DateTimeOffset.FromUnixTimeSeconds((long)unix), DateTimeOffset.UtcNow, false, sender == selfId,
localId.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
}
}
return result.Values.OrderBy(m => m.CreatedAtUtc).ToArray();
}
internal static NativeBinding Read(int processId, string groupName, string senderName, CancellationToken ct)
{
TypedMemorySnapshot snapshot = TypedSnapshot.Read(processId, groupName, senderName, ct);
uint imageBase = Convert.ToUInt32(snapshot.ImageBase[2..], 16);
using ProcessMemory memory = new(processId);
byte[] signature = BitConverter.GetBytes(imageBase + 0x0BA69DC0);
byte[] chunk = new byte[1024 * 1024 + 3];
HashSet<uint> managers = [];
foreach (var region in memory.Regions(0x1_0000_0000))
{
if (!region.IsReadablePrivateData) continue;
for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
{
ulong start = (ulong)region.BaseAddress + offset;
int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
int position = 0;
while (position <= count - 4)
{
int relative = chunk.AsSpan(position, count - position).IndexOf(signature);
if (relative < 0) break;
int found = position + relative;
position = found + 4;
ulong address = start + (uint)found;
if (address % 4 != 0) continue;
byte[] data = new byte[32];
if (memory.Read(address, data, data.Length) != data.Length) continue;
if (Word(data, 0) != imageBase + 0x0BA69DC0) continue;
uint strong = Word(data, 4), weak = Word(data, 8);
if (strong is 0 or >= 1000000 || weak is 0 or >= 1000000) continue;
if (Word(data, 12) != address + 12 || Word(data, 16) != address) continue;
uint environment = Word(data, 20), environmentControl = Word(data, 24);
byte[] environmentHeader = new byte[4];
if (environment != environmentControl + 12 ||
memory.Read(environmentControl, environmentHeader, 4) != 4 ||
Word(environmentHeader, 0) != imageBase + 0x0BA6A0CC) continue;
managers.Add((uint)address);
}
}
}
if (managers.Count != 1) throw new InvalidOperationException($"无法确定唯一发送会话:{managers.Count}。");
uint control = managers.Single();
return new(snapshot, control, control + 12);
}
internal static string? FindSelfTestServerId(int processId, uint imageBase, string localId, string selfId)
{
if (!ulong.TryParse(localId, out ulong expectedId) || expectedId == 0 || !ulong.TryParse(selfId, out ulong expectedSelf)) return null;
using ProcessMemory memory = new(processId);
byte[] signature = BitConverter.GetBytes(imageBase + 0x0AF984F0);
byte[] chunk = new byte[1024 * 1024 + 3];
foreach (var region in memory.Regions(0x1_0000_0000))
{
if (!region.IsReadablePrivateData) continue;
for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
{
ulong start = (ulong)region.BaseAddress + offset;
int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
int position = 0;
while (position <= count - 4)
{
int relative = chunk.AsSpan(position, count - position).IndexOf(signature);
if (relative < 0) break;
int found = position + relative; position = found + 4;
if ((start + (uint)found) % 4 != 0) continue;
byte[] data = new byte[0x78];
if (memory.Read(start + (uint)found, data, data.Length) != data.Length) continue;
if (Word(data, 0) != imageBase + 0x0AF984F0) continue;
if (Word(data, 4) is 0 or >= 1000000 || Word(data, 8) is 0 or >= 1000000) continue;
if (BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16)) != expectedId ||
BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16 + 0x48)) != expectedSelf) continue;
// FILEASSIST is an inline native string; do not read other conversations' content.
if (Word(data, 16 + 0x28 + 16) != 10 || Word(data, 16 + 0x28 + 20) != 15 ||
!data.AsSpan(16 + 0x28, 10).SequenceEqual("FILEASSIST"u8)) continue;
ulong serverId = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(24));
if (serverId != 0) return serverId.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
}
}
return null;
}
private static uint Word(byte[] data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(offset));
private static string? ReadString(ProcessMemory memory, byte[] data, int offset)
{
uint length = Word(data, offset + 16), capacity = Word(data, offset + 20);
if (length > 512 || capacity < length || capacity > 131072 || capacity < 15) return null;
byte[] bytes;
if (capacity == 15 && length <= 15) bytes = data.AsSpan(offset, (int)length).ToArray();
else
{
uint address = Word(data, offset);
if (address < 0x10000 || (ulong)address + length + 1 > 0x1_0000_0000) return null;
bytes = new byte[length + 1];
if (memory.Read(address, bytes, bytes.Length) != bytes.Length || bytes[^1] != 0) return null;
bytes = bytes[..^1];
}
try { return new UTF8Encoding(false, true).GetString(bytes); }
catch (DecoderFallbackException) { return null; }
}
}
using System.Buffers.Binary;
using System.Diagnostics;
using System.Text;
using XFEWorkflow.Plugins.WeCom.Native.Core;
using XFEWorkflow.Plugins.WeCom.Native.MemoryLab;
namespace XFEWorkflow.Plugins.WeCom.Native.Integrations;
internal sealed record NativeBinding(TypedMemorySnapshot Snapshot, uint ManagerControl, uint ManagerObject);
internal static class NativeDiscovery
{
internal static IReadOnlyList<WeComMember> ReadCachedContacts(int processId, uint imageBase, CancellationToken token)
{
using ProcessMemory memory = new(processId);
if (memory.GetMachine().ProcessMachine != 0x014c) throw new NotSupportedException("联系人读取要求 x86 企业微信。");
uint vtable = imageBase + 0x0AF98B84;
byte[] word = new byte[4], locator = new byte[20], rtti = new byte[256];
if (memory.Read(vtable - 4, word, 4) != 4 || memory.Read(Word(word, 0), locator, 20) != 20 ||
Word(locator, 0) != 0 || Word(locator, 4) != 0) throw new InvalidOperationException("联系人 RTTI 定位结构不匹配。");
int rttiLength = memory.Read(Word(locator, 12) + 8, rtti, rtti.Length);
int rttiEnd = rtti.AsSpan(0, rttiLength).IndexOf((byte)0);
if (rttiEnd < 0 || Encoding.ASCII.GetString(rtti, 0, rttiEnd) != ".?AV?$_Ref_count_obj2@VUser@model@wework@@@std@@")
throw new InvalidOperationException("联系人原生类型不匹配。");
byte[] signature = BitConverter.GetBytes(vtable), chunk = new byte[1024 * 1024 + 3];
Dictionary<string, HashSet<string>> contacts = new(StringComparer.Ordinal);
Stopwatch budget = Stopwatch.StartNew();
foreach (var region in memory.Regions(0x1_0000_0000))
{
if (!region.IsReadablePrivateData) continue;
for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
{
token.ThrowIfCancellationRequested();
if (budget.Elapsed > TimeSpan.FromSeconds(8)) throw new TimeoutException("联系人读取超时,请稍后重新读取。");
ulong start = (ulong)region.BaseAddress + offset;
int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
int position = 0;
while (position <= count - 4)
{
int relative = chunk.AsSpan(position, count - position).IndexOf(signature);
if (relative < 0) break;
int found = position + relative; position = found + 4;
ulong address = start + (uint)found;
if (address % 4 != 0) continue;
byte[] data = new byte[48];
if (memory.Read(address, data, data.Length) != data.Length || Word(data, 0) != vtable ||
Word(data, 4) is 0 or >= 1000000 || Word(data, 8) is 0 or >= 1000000) continue;
ulong id = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16));
if (id is 0 or ulong.MaxValue) continue;
string? name = ReadString(memory, data, 24);
if (string.IsNullOrWhiteSpace(name) || name.Any(char.IsControl)) continue;
string uid = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (!contacts.TryGetValue(uid, out HashSet<string>? names))
{
if (contacts.Count >= 20000) throw new InvalidOperationException("缓存联系人数量超出读取范围。");
contacts[uid] = names = new(StringComparer.Ordinal);
}
if (names.Count < 4) names.Add(name);
}
}
}
return contacts.Select(c => new WeComMember(c.Key, string.Join(" / ", c.Value.Order(StringComparer.Ordinal))))
.OrderBy(c => c.DisplayName, StringComparer.CurrentCulture).ThenBy(c => c.Id, StringComparer.Ordinal).ToArray();
}
internal static IReadOnlyList<WeComMessage> ReadReceivedMessages(NativeBinding binding, string selfId, CancellationToken token)
{
uint imageBase = Convert.ToUInt32(binding.Snapshot.ImageBase[2..], 16);
using ProcessMemory memory = new(binding.Snapshot.ProcessId);
byte[] signature = BitConverter.GetBytes(imageBase + 0x0AF984F0);
byte[] chunk = new byte[1024 * 1024 + 3];
Dictionary<string, WeComMessage> result = new(StringComparer.Ordinal);
Stopwatch budget = Stopwatch.StartNew();
foreach (var region in memory.Regions(0x1_0000_0000))
{
if (!region.IsReadablePrivateData) continue;
for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
{
token.ThrowIfCancellationRequested();
if (budget.Elapsed > TimeSpan.FromSeconds(5)) throw new TimeoutException("内存增量读取超时。");
ulong start = (ulong)region.BaseAddress + offset;
int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
int position = 0;
while (position <= count - 4)
{
int relative = chunk.AsSpan(position, count - position).IndexOf(signature);
if (relative < 0) break;
int found = position + relative; position = found + 4;
if ((start + (uint)found) % 4 != 0) continue;
byte[] data = new byte[0x78];
if (memory.Read(start + (uint)found, data, data.Length) != data.Length) continue;
if (Word(data, 0) != imageBase + 0x0AF984F0) continue;
if (Word(data, 4) is 0 or >= 1000000 || Word(data, 8) is 0 or >= 1000000) continue;
string? conversationId = ReadString(memory, data, 16 + 0x28);
if (!ReplySettings.ValidId(conversationId)) continue;
string sender = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16 + 0x48)).ToString(System.Globalization.CultureInfo.InvariantCulture);
if (sender == "0" || sender == ulong.MaxValue.ToString(System.Globalization.CultureInfo.InvariantCulture)) continue;
ulong localId = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16));
string? clientId = ReadString(memory, data, 16 + 0x10);
if (localId == 0 && string.IsNullOrEmpty(clientId)) continue;
string id = string.IsNullOrEmpty(clientId) ? "L:" + localId : clientId;
ulong unix = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16 + 0x58));
if (unix is < 1262304000 or > 4102444800) continue;
uint type = Word(data, 16 + 0x50);
result.TryAdd(conversationId + ":" + id, new(id, conversationId!, sender,
type == 4 ? MessageKind.MergedForward : type == 2 ? MessageKind.Text : MessageKind.Unknown, "",
DateTimeOffset.FromUnixTimeSeconds((long)unix), DateTimeOffset.UtcNow, false, sender == selfId,
localId.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
}
}
return result.Values.OrderBy(m => m.CreatedAtUtc).ToArray();
}
internal static NativeBinding Read(int processId, string groupName, string senderName, CancellationToken ct)
{
TypedMemorySnapshot snapshot = TypedSnapshot.Read(processId, groupName, senderName, ct);
uint imageBase = Convert.ToUInt32(snapshot.ImageBase[2..], 16);
using ProcessMemory memory = new(processId);
byte[] signature = BitConverter.GetBytes(imageBase + 0x0BA69DC0);
byte[] chunk = new byte[1024 * 1024 + 3];
HashSet<uint> managers = [];
foreach (var region in memory.Regions(0x1_0000_0000))
{
if (!region.IsReadablePrivateData) continue;
for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
{
ulong start = (ulong)region.BaseAddress + offset;
int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
int position = 0;
while (position <= count - 4)
{
int relative = chunk.AsSpan(position, count - position).IndexOf(signature);
if (relative < 0) break;
int found = position + relative;
position = found + 4;
ulong address = start + (uint)found;
if (address % 4 != 0) continue;
byte[] data = new byte[32];
if (memory.Read(address, data, data.Length) != data.Length) continue;
if (Word(data, 0) != imageBase + 0x0BA69DC0) continue;
uint strong = Word(data, 4), weak = Word(data, 8);
if (strong is 0 or >= 1000000 || weak is 0 or >= 1000000) continue;
if (Word(data, 12) != address + 12 || Word(data, 16) != address) continue;
uint environment = Word(data, 20), environmentControl = Word(data, 24);
byte[] environmentHeader = new byte[4];
if (environment != environmentControl + 12 ||
memory.Read(environmentControl, environmentHeader, 4) != 4 ||
Word(environmentHeader, 0) != imageBase + 0x0BA6A0CC) continue;
managers.Add((uint)address);
}
}
}
if (managers.Count != 1) throw new InvalidOperationException($"无法确定唯一发送会话:{managers.Count}。");
uint control = managers.Single();
return new(snapshot, control, control + 12);
}
internal static string? FindSelfTestServerId(int processId, uint imageBase, string localId, string selfId)
{
if (!ulong.TryParse(localId, out ulong expectedId) || expectedId == 0 || !ulong.TryParse(selfId, out ulong expectedSelf)) return null;
using ProcessMemory memory = new(processId);
byte[] signature = BitConverter.GetBytes(imageBase + 0x0AF984F0);
byte[] chunk = new byte[1024 * 1024 + 3];
foreach (var region in memory.Regions(0x1_0000_0000))
{
if (!region.IsReadablePrivateData) continue;
for (ulong offset = 0; offset < (ulong)region.RegionSize; offset += 1024 * 1024)
{
ulong start = (ulong)region.BaseAddress + offset;
int count = memory.Read(start, chunk, (int)Math.Min((ulong)chunk.Length, (ulong)region.RegionSize - offset));
int position = 0;
while (position <= count - 4)
{
int relative = chunk.AsSpan(position, count - position).IndexOf(signature);
if (relative < 0) break;
int found = position + relative; position = found + 4;
if ((start + (uint)found) % 4 != 0) continue;
byte[] data = new byte[0x78];
if (memory.Read(start + (uint)found, data, data.Length) != data.Length) continue;
if (Word(data, 0) != imageBase + 0x0AF984F0) continue;
if (Word(data, 4) is 0 or >= 1000000 || Word(data, 8) is 0 or >= 1000000) continue;
if (BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16)) != expectedId ||
BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16 + 0x48)) != expectedSelf) continue;
// FILEASSIST is an inline native string; do not read other conversations' content.
if (Word(data, 16 + 0x28 + 16) != 10 || Word(data, 16 + 0x28 + 20) != 15 ||
!data.AsSpan(16 + 0x28, 10).SequenceEqual("FILEASSIST"u8)) continue;
ulong serverId = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(24));
if (serverId != 0) return serverId.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
}
}
return null;
}
private static uint Word(byte[] data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(offset));
private static string? ReadString(ProcessMemory memory, byte[] data, int offset)
{
uint length = Word(data, offset + 16), capacity = Word(data, offset + 20);
if (length > 512 || capacity < length || capacity > 131072 || capacity < 15) return null;
byte[] bytes;
if (capacity == 15 && length <= 15) bytes = data.AsSpan(offset, (int)length).ToArray();
else
{
uint address = Word(data, offset);
if (address < 0x10000 || (ulong)address + length + 1 > 0x1_0000_0000) return null;
bytes = new byte[length + 1];
if (memory.Read(address, bytes, bytes.Length) != bytes.Length || bytes[^1] != 0) return null;
bytes = bytes[..^1];
}
try { return new UTF8Encoding(false, true).GetString(bytes); }
catch (DecoderFallbackException) { return null; }
}
}