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

158 lines
5.6 KiB
C#

using System;
using System.IO;
using System.Linq;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Preloader.Core;
using BepInEx.Preloader.Core.Logging;
using BepInEx.Preloader.Core.Patching;
using BepInEx.Preloader.RuntimeFixes;
using BepInEx.Unity.Common;
using BepInEx.Unity.Mono.Preloader.RuntimeFixes;
using BepInEx.Unity.Mono.Preloader.Utils;
namespace BepInEx.Unity.Mono.Preloader;
/// <summary>
/// The main entrypoint of BepInEx, and initializes all patchers and the chainloader.
/// </summary>
internal static class UnityPreloader
{
#region Config
internal static readonly ConfigEntry<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Bind(
"Preloader", "ApplyRuntimePatches",
true,
"Enables or disables runtime patches.\nThis should always be true, unless you cannot start the game due to a Harmony related issue (such as running .NET Standard runtime) or you know what you're doing.");
#endregion
/// <summary>
/// The log writer that is specific to the preloader.
/// </summary>
private static PreloaderConsoleListener PreloaderLog { get; set; }
private static ManualLogSource Log => PreloaderLogger.Log;
public static void Run()
{
try
{
HarmonyBackendFix.Initialize();
UnityInfo.Initialize(Paths.ExecutablePath, Paths.GameDataPath);
ConsoleManager.Initialize(false, false);
AllocateConsole();
Utility.TryDo(() =>
{
if (ConfigApplyRuntimePatches.Value)
UnityPatches.Apply();
}, out var runtimePatchException);
Logger.Sources.Add(new HarmonyLogSource());
Logger.Sources.Add(TraceLogSource.CreateSource());
PreloaderLog = new PreloaderConsoleListener();
Logger.Listeners.Add(PreloaderLog);
ChainloaderLogHelper.PrintLogInfo(Log);
Log.Log(LogLevel.Info, $"Running under Unity {UnityInfo.Version}");
Log.Log(LogLevel.Info, $"CLR runtime version: {Environment.Version}");
Log.Log(LogLevel.Info, $"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}");
Log.Log(LogLevel.Debug, $"Game executable path: {Paths.ExecutablePath}");
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}");
Log.Log(LogLevel.Message, "Preloader started");
TypeLoader.SearchDirectories.UnionWith(Paths.DllSearchPaths);
using (var assemblyPatcher = new AssemblyPatcher(MonoAssemblyHelper.LoadFromMemory))
{
assemblyPatcher.AddPatchersFromDirectory(Paths.BepInExAssemblyDirectory);
assemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath);
Log.Log(LogLevel.Info,
$"{assemblyPatcher.PatcherContext.PatcherPlugins.Count} patcher plugin{(assemblyPatcher.PatcherContext.PatcherPlugins.Count == 1 ? "" : "s")} loaded");
assemblyPatcher.LoadAssemblyDirectories(Paths.DllSearchPaths);
Log.Log(LogLevel.Info,
$"{assemblyPatcher.PatcherContext.AvailableAssemblies.Count} assemblies discovered");
assemblyPatcher.PatchAndLoad();
}
Log.Log(LogLevel.Message, "Preloader finished");
Logger.Listeners.Remove(PreloaderLog);
PreloaderLog.Dispose();
}
catch (Exception ex)
{
try
{
Log.Log(LogLevel.Fatal, "Could not run preloader!");
Log.Log(LogLevel.Fatal, ex);
if (!ConsoleManager.ConsoleActive)
{
//if we've already attached the console, then the log will already be written to the console
AllocateConsole();
Console.Write(PreloaderLog);
}
}
catch { }
var log = string.Empty;
try
{
// We could use platform-dependent newlines, however the developers use Windows so this will be easier to read :)
log = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select(x => x.ToString()).ToArray());
log += "\r\n";
PreloaderLog?.Dispose();
PreloaderLog = null;
}
catch { }
File.WriteAllText(
Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
log + ex);
}
}
/// <summary>
/// Allocates a console window for use by BepInEx safely.
/// </summary>
public static void AllocateConsole()
{
if (!ConsoleManager.ConsoleEnabled)
return;
try
{
ConsoleManager.CreateConsole();
Logger.Listeners.Add(new ConsoleLogListener());
}
catch (Exception ex)
{
Log.LogError("Failed to allocate console!");
Log.LogError(ex);
}
}
}