diff --git a/BepInEx.Preloader.Core/RuntimeFixes/AppleSiliconDetourFix.cs b/BepInEx.Preloader.Core/RuntimeFixes/AppleSiliconDetourFix.cs
new file mode 100644
index 0000000..38e6d90
--- /dev/null
+++ b/BepInEx.Preloader.Core/RuntimeFixes/AppleSiliconDetourFix.cs
@@ -0,0 +1,115 @@
+using System;
+using System.Runtime.InteropServices;
+using MonoMod.RuntimeDetour;
+using MonoMod.RuntimeDetour.Platforms;
+using MonoMod.Utils;
+
+namespace BepInEx.Preloader.RuntimeFixes;
+
+///
+/// Lets MonoMod write detours when the game runs as a native arm64 process on Apple Silicon.
+///
+///
+/// Unity's code sits in a MAP_JIT region, which refuses mprotect with EACCES and
+/// mach_vm_write with KERN_INVALID_ADDRESS. Only pthread_jit_write_protect_np gets in, and
+/// managed code cannot call it: it drops execute permission for the calling thread, which is running
+/// JIT-compiled code. Doorstop's doorstop_jit_memcpy keeps the toggle and the write in one frame.
+///
+public static class AppleSiliconDetourFix
+{
+ /// Why the fix could not install. Logged once the preloader has a logger.
+ public static Exception Exception { get; private set; }
+
+ /// Whether this process is 64-bit arm64 macOS.
+ public static bool Applies =>
+ IntPtr.Size == 8 && PlatformHelper.Is(Platform.MacOS) && PlatformHelper.Is(Platform.ARM);
+
+ /// Installs the platform. Call before any read.
+ public static void Apply()
+ {
+ if (!Applies)
+ return;
+
+ try
+ {
+ DetourHelper.Native = new AppleSiliconNativePlatform(new DetourNativeARMPlatform());
+ }
+ catch (Exception e)
+ {
+ Exception = e;
+ }
+ }
+
+ /// Replaces the write operations only; the inner platform still encodes.
+ private sealed class AppleSiliconNativePlatform : IDetourNativePlatform
+ {
+ private const string LibSystem = "/usr/lib/libSystem.dylib";
+
+ /// RTLD_DEFAULT: every loaded image.
+ private static readonly IntPtr RtldDefault = new(-2);
+
+ /// Mirrors private DetourNativeARMPlatform.DetourSizes (MonoMod 22.7.31.1).
+ 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);
+ }
+}
diff --git a/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/RuntimeFixes/XTermFix.cs b/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/RuntimeFixes/XTermFix.cs
index ab33789..74bf13f 100644
--- a/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/RuntimeFixes/XTermFix.cs
+++ b/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/RuntimeFixes/XTermFix.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
+using BepInEx.Preloader.RuntimeFixes;
using HarmonyLib;
using MonoMod.RuntimeDetour;
using MonoMod.RuntimeDetour.Platforms;
@@ -29,9 +30,13 @@ internal static class XTermFix
// Apparently on older Unity versions (4.x), using Process.Start can run Console..cctor
// And since MonoMod's PlatformHelper (used by DetourHelper.Native) runs Process.Start to determine ARM/x86 platform,
// this causes a crash owing to TermInfoReader running before it can be patched and fixed
- // Because Doorstop does not support ARM at the moment, we can get away with just forcing x86 detour platform.
+ // so we can get away with just forcing the x86 detour platform.
// TODO: Figure out a way to detect ARM on Unix without running Process.Start
- DetourHelper.Native = new DetourNativeX86Platform();
+ // Apple Silicon really is ARM, so keep its platform.
+ var previousNative = DetourHelper.Native;
+
+ if (!AppleSiliconDetourFix.Applies)
+ DetourHelper.Native = new DetourNativeX86Platform();
var harmony = new Harmony("com.bepinex.xtermfix");
@@ -47,7 +52,7 @@ internal static class XTermFix
harmony.Patch(AccessTools.Method("System.TermInfoReader:GetStringBytes", new[] { AccessTools.TypeByName("System.TermInfoStrings") }),
transpiler: new HarmonyMethod(typeof(XTermFix), nameof(GetTermInfoStringsTranspiler)));
- DetourHelper.Native = null;
+ DetourHelper.Native = AppleSiliconDetourFix.Applies ? previousNative : null;
}
public static int GetInt32(byte[] buffer, int offset)
diff --git a/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/UnityPreloader.cs b/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/UnityPreloader.cs
index 6cc3b33..13a1191 100644
--- a/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/UnityPreloader.cs
+++ b/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/UnityPreloader.cs
@@ -66,6 +66,11 @@ internal static class UnityPreloader
Log.Log(LogLevel.Debug, $"Unity Managed directory: {Paths.ManagedPath}");
Log.Log(LogLevel.Debug, $"BepInEx root path: {Paths.BepInExRootPath}");
+ if (AppleSiliconDetourFix.Exception != null)
+ Log.Log(LogLevel.Warning,
+ "Failed to install the Apple Silicon detour platform, so no Harmony patch will apply. "
+ + $"Error message: {AppleSiliconDetourFix.Exception.Message}");
+
if (runtimePatchException != null)
Log.Log(LogLevel.Warning,
$"Failed to apply runtime patches for Mono. See more info in the output log. Error message: {runtimePatchException.Message}");
diff --git a/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/UnityPreloaderRunner.cs b/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/UnityPreloaderRunner.cs
index 0f063da..fca4fcb 100644
--- a/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/UnityPreloaderRunner.cs
+++ b/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/UnityPreloaderRunner.cs
@@ -46,6 +46,9 @@ internal static class UnityPreloaderRunner
{
PlatformUtils.SetPlatform();
+ // After SetPlatform, before any DetourHelper read.
+ AppleSiliconDetourFix.Apply();
+
var bepinPath = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2);
Paths.SetExecutablePath(EnvVars.DOORSTOP_PROCESS_PATH,