From 9db07e534f68bb5889452f76d9c1f2d9ae32cbfa Mon Sep 17 00:00:00 2001 From: Kendall Loh Date: Thu, 19 Nov 2026 03:15:06 +0000 Subject: [PATCH] Add macOS platform layer (no change on Windows) Groundwork for running FMMatchLens on macOS (Apple Silicon) with the community macOS BepInEx IL2CPP package: - MacNative: macOS memory region queries (mach_vm_region) and finding the loaded game_plugin image, used by the hook in a follow-up PR. - VirtualMemory: region lookup moved into TryQueryRegion, which uses MacNative on macOS and VirtualQuery otherwise. The Windows logic is unchanged, only moved into the helper. - PluginOptions: default graphics path under ~/Library/Application Support on macOS; Windows default unchanged. --- src/FMMatchLens.Plugin/Memory/MacNative.cs | 422 ++++++++++++++++++ .../Memory/VirtualMemory.cs | 29 +- .../Services/PluginOptions.cs | 21 +- 3 files changed, 459 insertions(+), 13 deletions(-) create mode 100644 src/FMMatchLens.Plugin/Memory/MacNative.cs diff --git a/src/FMMatchLens.Plugin/Memory/MacNative.cs b/src/FMMatchLens.Plugin/Memory/MacNative.cs new file mode 100644 index 0000000..89b3c24 --- /dev/null +++ b/src/FMMatchLens.Plugin/Memory/MacNative.cs @@ -0,0 +1,422 @@ +using System.Runtime.InteropServices; + +namespace FMMatchLens.Plugin.Memory; + +/// +/// macOS replacements for the kernel32 calls the capture layer uses on Windows: +/// module lookup (dyld instead of GetModuleHandle/GetModuleFileName), region +/// queries (mach_vm_region instead of VirtualQuery), executable ranges (Mach-O +/// load commands instead of PE section headers) and function-entry checks +/// (LC_FUNCTION_STARTS instead of RtlLookupFunctionEntry). +/// +/// An "RVA" on macOS is an offset from the image's mach_header, which is where +/// dyld maps the start of __TEXT. That matches how Windows RVAs are measured +/// from the module base, so the rest of the plugin can treat both the same way. +/// +internal static class MacNative +{ + private const string LibSystem = "/usr/lib/libSystem.dylib"; + + private const uint MhMagic64 = 0xFEEDFACF; + private const uint LcSegment64 = 0x19; + private const uint LcFunctionStarts = 0x26; + private const uint SAttrPureInstructions = 0x80000000; + private const uint SAttrSomeInstructions = 0x00000400; + private const int VmProtRead = 0x1; + private const int VmProtExecute = 0x4; + private const int VmRegionBasicInfo64Flavor = 9; + private const int KernSuccess = 0; + + private static readonly object FunctionStartsLock = new(); + private static nint _functionStartsModule; + private static int[]? _functionStarts; + private static uint? _taskSelf; + + public static bool IsMacOS => OperatingSystem.IsMacOS(); + + /// One loaded image whose path contains the search text. + internal readonly record struct LoadedImage(nint Header, string Path); + + /// + /// Every loaded image whose path contains + /// (case-insensitive). The capture layer logs all of them, because the + /// exact name of FM's native match library on macOS is not yet confirmed. + /// + public static List FindImages(string nameFragment) + { + var result = new List(); + var count = _dyld_image_count(); + for (uint i = 0; i < count; i++) + { + var namePointer = _dyld_get_image_name(i); + if (namePointer == default) continue; + var path = Marshal.PtrToStringUTF8(namePointer); + if (string.IsNullOrEmpty(path)) continue; + if (path.IndexOf(nameFragment, StringComparison.OrdinalIgnoreCase) < 0) continue; + var header = _dyld_get_image_header(i); + if (header != default) result.Add(new LoadedImage(header, path)); + } + + return result; + } + + /// + /// The game's native match library. Prefers an image inside the app bundle + /// over any other match, and a file named exactly game_plugin over a longer name. + /// + public static nint FindGamePlugin(out string path, out List candidates) + { + candidates = FindImages("game_plugin"); + path = string.Empty; + if (candidates.Count == 0) return default; + + var best = candidates + .OrderByDescending(image => System.IO.Path.GetFileNameWithoutExtension(image.Path) + .Equals("game_plugin", StringComparison.OrdinalIgnoreCase)) + .ThenByDescending(image => image.Path.Contains(".app/", StringComparison.OrdinalIgnoreCase)) + .First(); + path = best.Path; + return best.Header; + } + + /// Path of the loaded image whose mach_header is at . + public static string GetImagePath(nint header) + { + var count = _dyld_image_count(); + for (uint i = 0; i < count; i++) + { + if (_dyld_get_image_header(i) != header) continue; + var namePointer = _dyld_get_image_name(i); + var path = namePointer == default ? null : Marshal.PtrToStringUTF8(namePointer); + if (!string.IsNullOrEmpty(path)) return path; + } + + throw new InvalidOperationException($"No loaded image has its header at 0x{(ulong)header:X}."); + } + + /// + /// The region that contains . mach_vm_region + /// returns the first region at or above the address, so a region that + /// starts above it means the address itself is unmapped. + /// + public static bool TryQueryRegion(nint address, out ulong start, out ulong end, out bool readable) + { + start = 0; + end = 0; + readable = false; + var regionAddress = (ulong)address; + ulong regionSize = 0; + var infoCount = (uint)(Marshal.SizeOf() / sizeof(int)); + var result = mach_vm_region( + TaskSelf(), ref regionAddress, ref regionSize, VmRegionBasicInfo64Flavor, + out var info, ref infoCount, out _); + if (result != KernSuccess) return false; + + start = regionAddress; + end = regionAddress + regionSize; + if (end < start || (ulong)address < start || (ulong)address >= end) return false; + readable = (info.Protection & VmProtRead) != 0; + return true; + } + + /// + /// Executable ranges of the mapped image, as (RVA, size) pairs, read from + /// its in-memory Mach-O load commands: sections that hold instructions, + /// inside segments mapped executable. + /// + public static bool TryGetExecutableRanges(nint header, out List<(int Rva, int Size)> ranges, out string failure) + { + ranges = []; + if (!TryReadHeader(header, out var commands, out var commandCount, out failure)) return false; + + ulong? textVmAddress = null; + var segments = new List<(ulong VmAddress, int InitProt, nint FirstSection, uint SectionCount)>(); + var cursor = commands; + for (var i = 0; i < commandCount; i++) + { + var command = (uint)Marshal.ReadInt32(cursor); + var size = (uint)Marshal.ReadInt32(cursor, 4); + if (size < 8) + { + failure = $"load command {i} has an invalid size {size}"; + return false; + } + + if (command == LcSegment64) + { + var name = ReadFixedString(cursor + 8, 16); + var vmAddress = (ulong)Marshal.ReadInt64(cursor, 24); + var initProt = Marshal.ReadInt32(cursor, 60); + var sectionCount = (uint)Marshal.ReadInt32(cursor, 64); + if (name == "__TEXT") textVmAddress = vmAddress; + segments.Add((vmAddress, initProt, cursor + 72, sectionCount)); + } + + cursor += (int)size; + } + + if (textVmAddress is not { } textBase) + { + failure = "image has no __TEXT segment"; + return false; + } + + foreach (var segment in segments) + { + if ((segment.InitProt & VmProtExecute) == 0) continue; + for (var s = 0; s < segment.SectionCount; s++) + { + var section = segment.FirstSection + s * 80; + var address = (ulong)Marshal.ReadInt64(section, 32); + var size = (ulong)Marshal.ReadInt64(section, 40); + var flags = (uint)Marshal.ReadInt32(section, 64); + if ((flags & (SAttrPureInstructions | SAttrSomeInstructions)) == 0 || size == 0) continue; + var rva = address - textBase; + if (rva > int.MaxValue || size > int.MaxValue || rva + size > int.MaxValue) + { + failure = $"section {ReadFixedString(section, 16)} lies outside the supported RVA range"; + return false; + } + + ranges.Add(((int)rva, (int)size)); + } + } + + failure = ranges.Count == 0 ? "image has no executable instruction sections" : string.Empty; + return ranges.Count > 0; + } + + /// + /// Adds the mapped segments of a loaded image to as absolute + /// [start, end) address ranges (__PAGEZERO excluded), so callers can tell pointers into + /// code and constant data apart from heap pointers. + /// + public static bool TryGetSegmentSpans(nint header, List<(ulong Start, ulong End)> spans) + { + if (!TryReadHeader(header, out var commands, out var commandCount, out _)) return false; + + ulong? textVmAddress = null; + var segments = new List<(ulong VmAddress, ulong VmSize)>(); + var cursor = commands; + for (var i = 0; i < commandCount; i++) + { + var command = (uint)Marshal.ReadInt32(cursor); + var size = (uint)Marshal.ReadInt32(cursor, 4); + if (size < 8) return false; + if (command == LcSegment64) + { + var name = ReadFixedString(cursor + 8, 16); + var vmAddress = (ulong)Marshal.ReadInt64(cursor, 24); + var vmSize = (ulong)Marshal.ReadInt64(cursor, 32); + if (name == "__TEXT") textVmAddress = vmAddress; + if (name != "__PAGEZERO" && vmSize > 0) segments.Add((vmAddress, vmSize)); + } + + cursor += (int)size; + } + + if (textVmAddress is not { } textBase) return false; + var slide = (ulong)header - textBase; + foreach (var (vmAddress, vmSize) in segments) spans.Add((vmAddress + slide, vmAddress + slide + vmSize)); + return true; + } + + /// + /// True when is listed in the image's LC_FUNCTION_STARTS + /// table. Detouring an address inside a function corrupts it, so this plays the + /// role the unwind-table check plays on Windows. + /// + public static bool IsFunctionEntry(nint header, int rva) + { + var starts = GetFunctionStarts(header); + return starts is not null && Array.BinarySearch(starts, rva) >= 0; + } + + /// Number of functions listed in LC_FUNCTION_STARTS, or -1 if the table is missing. + public static int CountFunctionStarts(nint header) => GetFunctionStarts(header)?.Length ?? -1; + + /// CPU type from the mach_header (0x0100000C is arm64, 0x01000007 is x86_64). + public static int ReadCpuType(nint header) => Marshal.ReadInt32(header, 4); + + private static int[]? GetFunctionStarts(nint header) + { + lock (FunctionStartsLock) + { + if (_functionStartsModule == header && _functionStarts is not null) return _functionStarts; + _functionStarts = ParseFunctionStarts(header); + _functionStartsModule = header; + return _functionStarts; + } + } + + private static int[]? ParseFunctionStarts(nint header) + { + if (!TryLocateFunctionStarts(header, out var data, out var dataSize)) return null; + if (!TryQueryRegion(data, out _, out var regionEnd, out var readable) || !readable || + (ulong)data + dataSize > regionEnd) + return null; + + var bytes = new byte[dataSize]; + Marshal.Copy(data, bytes, 0, (int)dataSize); + return DecodeFunctionStarts(bytes); + } + + /// + /// Where the mapped LC_FUNCTION_STARTS table sits in memory. The table lives in + /// __LINKEDIT, so its file offset maps to memory through that segment's own + /// vmaddr/fileoff pair plus the image slide. + /// + internal static bool TryLocateFunctionStarts(nint header, out nint data, out uint dataSize) + { + data = default; + dataSize = 0; + if (!TryReadHeader(header, out var commands, out var commandCount, out _)) return false; + + ulong? textVmAddress = null; + ulong linkEditVmAddress = 0, linkEditFileOffset = 0, linkEditFileSize = 0; + var haveLinkEdit = false; + uint dataOffset = 0; + var haveFunctionStarts = false; + var cursor = commands; + for (var i = 0; i < commandCount; i++) + { + var command = (uint)Marshal.ReadInt32(cursor); + var size = (uint)Marshal.ReadInt32(cursor, 4); + if (size < 8) return false; + if (command == LcSegment64) + { + var name = ReadFixedString(cursor + 8, 16); + if (name == "__TEXT") textVmAddress = (ulong)Marshal.ReadInt64(cursor, 24); + if (name == "__LINKEDIT") + { + linkEditVmAddress = (ulong)Marshal.ReadInt64(cursor, 24); + linkEditFileOffset = (ulong)Marshal.ReadInt64(cursor, 40); + linkEditFileSize = (ulong)Marshal.ReadInt64(cursor, 48); + haveLinkEdit = true; + } + } + else if (command == LcFunctionStarts) + { + dataOffset = (uint)Marshal.ReadInt32(cursor, 8); + dataSize = (uint)Marshal.ReadInt32(cursor, 12); + haveFunctionStarts = true; + } + + cursor += (int)size; + } + + if (textVmAddress is not { } textBase || !haveLinkEdit || !haveFunctionStarts || + dataOffset < linkEditFileOffset || dataOffset + (ulong)dataSize > linkEditFileOffset + linkEditFileSize) + return false; + + var slide = (ulong)header - textBase; + data = (nint)(long)(slide + linkEditVmAddress + (dataOffset - linkEditFileOffset)); + return true; + } + + /// + /// LC_FUNCTION_STARTS is a run of ULEB128 deltas. The first delta is measured + /// from the start of __TEXT, so cumulative values are RVAs. A zero delta ends it. + /// + internal static int[] DecodeFunctionStarts(ReadOnlySpan data) + { + var starts = new List(); + ulong address = 0; + var position = 0; + while (position < data.Length) + { + ulong delta = 0; + var shift = 0; + byte value; + do + { + if (position >= data.Length || shift > 63) return starts.ToArray(); + value = data[position++]; + delta |= (ulong)(value & 0x7F) << shift; + shift += 7; + } while ((value & 0x80) != 0); + + if (delta == 0) break; + address += delta; + if (address > int.MaxValue) break; + starts.Add((int)address); + } + + return starts.ToArray(); + } + + private static bool TryReadHeader(nint header, out nint commands, out int commandCount, out string failure) + { + commands = default; + commandCount = 0; + if (header == default) + { + failure = "image header is null"; + return false; + } + + var magic = (uint)Marshal.ReadInt32(header); + if (magic != MhMagic64) + { + failure = $"image is not a 64-bit Mach-O (magic 0x{magic:X8})"; + return false; + } + + commandCount = Marshal.ReadInt32(header, 16); + commands = header + 32; + failure = string.Empty; + return true; + } + + private static string ReadFixedString(nint address, int length) + { + var bytes = new byte[length]; + Marshal.Copy(address, bytes, 0, length); + var end = Array.IndexOf(bytes, (byte)0); + return System.Text.Encoding.ASCII.GetString(bytes, 0, end < 0 ? length : end); + } + + private static uint TaskSelf() + { + if (_taskSelf is { } task) return task; + // mach_task_self() is a macro over the exported mach_task_self_ variable. + var library = NativeLibrary.Load(LibSystem); + var symbol = NativeLibrary.GetExport(library, "mach_task_self_"); + task = (uint)Marshal.ReadInt32(symbol); + _taskSelf = task; + return task; + } + + // vm_region_basic_info_64 is declared under #pragma pack(4) in mach/vm_region.h. + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct VmRegionBasicInfo64 + { + public int Protection; + public int MaxProtection; + public uint Inheritance; + public int Shared; + public int Reserved; + public ulong Offset; + public int Behavior; + public ushort UserWiredCount; + } + + [DllImport(LibSystem)] + private static extern uint _dyld_image_count(); + + [DllImport(LibSystem)] + private static extern nint _dyld_get_image_header(uint imageIndex); + + [DllImport(LibSystem)] + private static extern nint _dyld_get_image_name(uint imageIndex); + + [DllImport(LibSystem)] + private static extern int mach_vm_region( + uint targetTask, + ref ulong address, + ref ulong size, + int flavor, + out VmRegionBasicInfo64 info, + ref uint infoCount, + out uint objectName); +} diff --git a/src/FMMatchLens.Plugin/Memory/VirtualMemory.cs b/src/FMMatchLens.Plugin/Memory/VirtualMemory.cs index b097c6d..2dc3e0b 100644 --- a/src/FMMatchLens.Plugin/Memory/VirtualMemory.cs +++ b/src/FMMatchLens.Plugin/Memory/VirtualMemory.cs @@ -53,20 +53,33 @@ public static bool IsReadable(nint address, int size) if (scope is not null && scope.TryFind(start, out var cached)) return cached.Readable && end <= cached.End; + if (!TryQueryRegion(address, out var regionStart, out var regionEnd, out var readable)) + return false; + if (regionEnd < regionStart || start < regionStart || start >= regionEnd) + return false; + scope?.Remember(new QueriedRegion(regionStart, regionEnd, readable)); + return readable && end <= regionEnd; + } + + private static bool TryQueryRegion(nint address, out ulong regionStart, out ulong regionEnd, out bool readable) + { + if (MacNative.IsMacOS) + return MacNative.TryQueryRegion(address, out regionStart, out regionEnd, out readable); + + regionStart = 0; + regionEnd = 0; + readable = false; var queryResult = VirtualQuery(address, out var info, (nuint)Marshal.SizeOf()); if (queryResult == 0) { return false; } - var regionStart = (ulong)info.BaseAddress; - var regionEnd = regionStart + (ulong)info.RegionSize; - var readable = info.State == MemCommit && - (info.Protect & (PageNoAccess | PageGuard)) == 0; - if (regionEnd < regionStart || start < regionStart || start >= regionEnd) - return false; - scope?.Remember(new QueriedRegion(regionStart, regionEnd, readable)); - return readable && end <= regionEnd; + regionStart = (ulong)info.BaseAddress; + regionEnd = regionStart + (ulong)info.RegionSize; + readable = info.State == MemCommit && + (info.Protect & (PageNoAccess | PageGuard)) == 0; + return true; } internal readonly record struct QueriedRegion(ulong Start, ulong End, bool Readable); diff --git a/src/FMMatchLens.Plugin/Services/PluginOptions.cs b/src/FMMatchLens.Plugin/Services/PluginOptions.cs index a58a09c..4f1e103 100644 --- a/src/FMMatchLens.Plugin/Services/PluginOptions.cs +++ b/src/FMMatchLens.Plugin/Services/PluginOptions.cs @@ -15,11 +15,7 @@ public PluginOptions(ConfigFile config) GraphicsPath = config.Bind( "Graphics", "GraphicsPath", - Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - "Sports Interactive", - "Football Manager 26", - "graphics"), + DefaultGraphicsPath(), "Root directory containing Football Manager graphics packs and their config.xml files."); ArchiveCompression = config.Bind( @@ -47,6 +43,21 @@ public PluginOptions(ConfigFile config) "Bounded archive writer queue capacity. A sustained overflow stops the current archive explicitly."); } + // macOS keeps FM user data under ~/Library/Application Support rather than Documents. + private static string DefaultGraphicsPath() => OperatingSystem.IsMacOS() + ? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + "Library", + "Application Support", + "Sports Interactive", + "Football Manager 27", + "graphics") + : Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + "Sports Interactive", + "Football Manager 26", + "graphics"); + public ConfigEntry LogMode { get; } public ConfigEntry GraphicsPath { get; }