Files
Chris Dobbyn dbc82f05b8 v6: Fix plugin loading on native arm64 macOS (#1405)
* fix(macos): load plugins when the game runs as native arm64

This is the v6 port of #1402, which fixed the same failure on v5-lts.

MonoMod picks DetourNativeMonoPosixPlatform on Mono, whose MakeWritable and
MakeExecutable call mprotect with PROT_READ|PROT_WRITE|PROT_EXEC. macOS on
Apple Silicon answers EACCES, because a process without the
com.apple.security.cs.allow-unsigned-executable-memory entitlement can never
hold a page that is writable and executable at once. Unity ships
com.apple.security.cs.allow-jit instead, so Mono's code lives in a MAP_JIT
region, which also rejects mach_vm_write with KERN_INVALID_ADDRESS.

The EACCES escapes DetourRuntimeILPlatform's constructor, which runs inside
DetourHelper.Runtime's initialiser after _RuntimeInit is already set, so every
later read of DetourHelper.Runtime returns null and every Harmony patch dies on
a NullReferenceException in DetourHelper.GetIdentifiable. On v6 the first
casualty is ConsoleSetOutFix.Apply, which is not wrapped in Utility.TryDo, so
the whole preloader dies before it opens LogOutput.log. The only trace is a
preloader_*.log beside the executable.

v6 reaches this more easily than v5 does: run_bepinex_mono.sh sets
ARCHPREFERENCE="arm64,x86_64" unconditionally on Apple Silicon, so a universal
game runs as native arm64 by default and no opt-in is needed to hit the bug.

AppleSiliconDetourFix installs a detour platform that keeps
DetourNativeARMPlatform's AArch64 encoding and routes every code write through
doorstop_jit_memcpy, which toggles pthread_jit_write_protect_np around its own
memcpy. The toggle cannot be done from managed code: it drops execute
permission for the calling thread, and the caller is itself running
JIT-compiled code.

XTermFix forced DetourNativeX86Platform on every non-Windows target. On Apple
Silicon that encoded x86 branches into arm64 method bodies and reinstated the
failing mprotect, so it is now skipped when the new fix applies. XTermFix also
cleared DetourHelper.Native back to null on the way out, which would discard
the platform installed here, so it now restores what it found.

doorstop_jit_memcpy landed in UnityDoorstop via NeighTools/UnityDoorstop#114
and is not in the pinned 4.5.0 release. Until DoorstopVersion is bumped, this
fix reports its absence as a warning through the preloader instead of failing
silently, which is what happens today.

Verified on an M4 Pro against Valheim 6000.0.75f1 (Unity Mono), with a probe
plugin that Harmony-patches an already-JIT-compiled method:

  arm64,   unpatched build: preloader dies, no LogOutput.log
  arm64,   this build:      plugin loads, Harmony patch applies
  x86_64,  this build:      plugin loads, Harmony patch applies

* Move AppleSiliconDetourFix to BepInEx.Preloader.Core

The IL2CPP preloader needs the same class, so keep one copy where both
preloaders already reference it rather than a copy per runtime.

* Cut the comments back to one line each
2026-11-05 19:50:19 +01:00

116 lines
4.5 KiB
C#

using System;
using System.Runtime.InteropServices;
using MonoMod.RuntimeDetour;
using MonoMod.RuntimeDetour.Platforms;
using MonoMod.Utils;
namespace BepInEx.Preloader.RuntimeFixes;
/// <summary>
/// Lets MonoMod write detours when the game runs as a native arm64 process on Apple Silicon.
/// </summary>
/// <remarks>
/// Unity's code sits in a MAP_JIT region, which refuses <c>mprotect</c> with EACCES and
/// <c>mach_vm_write</c> with KERN_INVALID_ADDRESS. Only <c>pthread_jit_write_protect_np</c> gets in, and
/// managed code cannot call it: it drops execute permission for the calling thread, which is running
/// JIT-compiled code. Doorstop's <c>doorstop_jit_memcpy</c> keeps the toggle and the write in one frame.
/// </remarks>
public static class AppleSiliconDetourFix
{
/// <summary>Why the fix could not install. Logged once the preloader has a logger.</summary>
public static Exception Exception { get; private set; }
/// <summary>Whether this process is 64-bit arm64 macOS.</summary>
public static bool Applies =>
IntPtr.Size == 8 && PlatformHelper.Is(Platform.MacOS) && PlatformHelper.Is(Platform.ARM);
/// <summary>Installs the platform. Call before any <see cref="DetourHelper" /> read.</summary>
public static void Apply()
{
if (!Applies)
return;
try
{
DetourHelper.Native = new AppleSiliconNativePlatform(new DetourNativeARMPlatform());
}
catch (Exception e)
{
Exception = e;
}
}
/// <summary>Replaces the write operations only; the inner platform still encodes.</summary>
private sealed class AppleSiliconNativePlatform : IDetourNativePlatform
{
private const string LibSystem = "/usr/lib/libSystem.dylib";
/// <summary>RTLD_DEFAULT: every loaded image.</summary>
private static readonly IntPtr RtldDefault = new(-2);
/// <summary>Mirrors private DetourNativeARMPlatform.DetourSizes (MonoMod 22.7.31.1).</summary>
private static readonly uint[] DetourSizes = { 4 + 4, 4 + 2 + 2 + 4, 4 + 4, 4 + 4 + 4, 4 + 4 + 8 };
private readonly IDetourNativePlatform inner;
private readonly JitMemCpy jitMemCpy;
public AppleSiliconNativePlatform(IDetourNativePlatform inner)
{
this.inner = inner;
var symbol = dlsym(RtldDefault, "doorstop_jit_memcpy");
if (symbol == IntPtr.Zero)
throw new NotSupportedException(
"doorstop_jit_memcpy is not exported by any loaded image. Detours cannot be written on " +
"arm64 macOS without it. Update UnityDoorstop, or run the game under Rosetta.");
jitMemCpy = (JitMemCpy) Marshal.GetDelegateForFunctionPointer(symbol, typeof(JitMemCpy));
}
// doorstop_jit_memcpy handles permissions and icache.
public void MakeWritable(IntPtr src, uint size) { }
public void MakeReadWriteExecutable(IntPtr src, uint size) { }
public void MakeExecutable(IntPtr src, uint size) { }
public void FlushICache(IntPtr src, uint size) { }
public void Apply(NativeDetourData detour)
{
// Position independent, so encode then copy whole.
var scratch = new byte[detour.Size];
var pin = GCHandle.Alloc(scratch, GCHandleType.Pinned);
try
{
var staging = detour;
staging.Method = pin.AddrOfPinnedObject();
inner.Apply(staging);
jitMemCpy(detour.Method, staging.Method, (UIntPtr) detour.Size);
}
finally
{
pin.Free();
}
}
public void Copy(IntPtr src, IntPtr dst, byte type)
{
if (type >= DetourSizes.Length)
throw new NotSupportedException($"Unknown detour type {type}");
jitMemCpy(dst, src, (UIntPtr) DetourSizes[type]);
}
public NativeDetourData Create(IntPtr from, IntPtr to, byte? type) => inner.Create(from, to, type);
public void Free(NativeDetourData detour) => inner.Free(detour);
public IntPtr MemAlloc(uint size) => inner.MemAlloc(size);
public void MemFree(IntPtr ptr) => inner.MemFree(ptr);
[DllImport(LibSystem)]
private static extern IntPtr dlsym(IntPtr handle, string symbol);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void JitMemCpy(IntPtr dst, IntPtr src, UIntPtr n);
}
}