Files
BepInEx/Runtimes/Unity/BepInEx.Unity.Mono.Preloader/RuntimeFixes/XTermFix.cs
T
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

139 lines
5.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using BepInEx.Preloader.RuntimeFixes;
using HarmonyLib;
using MonoMod.RuntimeDetour;
using MonoMod.RuntimeDetour.Platforms;
using MonoMod.Utils;
namespace BepInEx.Unity.Mono.Preloader.RuntimeFixes;
internal static class XTermFix
{
public static int intOffset;
public static void Apply()
{
if (PlatformHelper.Is(Platform.Windows))
return;
if (typeof(Console).Assembly.GetType("System.ConsoleDriver") == null)
// Mono version is too old, use our own TTY implementation instead
return;
if (AccessTools.Method("System.TermInfoReader:DetermineVersion") != null)
// Fix has been applied officially
return;
// 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
// 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
// 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");
harmony.Patch(AccessTools.Method("System.TermInfoReader:ReadHeader"),
new HarmonyMethod(typeof(XTermFix), nameof(ReadHeaderPrefix)));
harmony.Patch(AccessTools.Method("System.TermInfoReader:Get", new[] { AccessTools.TypeByName("System.TermInfoNumbers") }),
transpiler: new HarmonyMethod(typeof(XTermFix), nameof(GetTermInfoNumbersTranspiler)));
harmony.Patch(AccessTools.Method("System.TermInfoReader:Get", new[] { AccessTools.TypeByName("System.TermInfoStrings") }),
transpiler: new HarmonyMethod(typeof(XTermFix), nameof(GetTermInfoStringsTranspiler)));
harmony.Patch(AccessTools.Method("System.TermInfoReader:GetStringBytes", new[] { AccessTools.TypeByName("System.TermInfoStrings") }),
transpiler: new HarmonyMethod(typeof(XTermFix), nameof(GetTermInfoStringsTranspiler)));
DetourHelper.Native = AppleSiliconDetourFix.Applies ? previousNative : null;
}
public static int GetInt32(byte[] buffer, int offset)
{
int b1 = buffer[offset];
int b2 = buffer[offset + 1];
int b3 = buffer[offset + 2];
int b4 = buffer[offset + 3];
return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24);
}
public static short GetInt16(byte[] buffer, int offset)
{
int b1 = buffer[offset];
int b2 = buffer[offset + 1];
return (short) (b1 | (b2 << 8));
}
public static int GetInteger(byte[] buffer, int offset) =>
intOffset == 2
? GetInt16(buffer, offset)
: GetInt32(buffer, offset);
public static void DetermineVersion(short magic)
{
if (magic == 0x11a)
intOffset = 2;
else if (magic == 0x21e)
intOffset = 4;
else
throw new Exception($"Unknown xterm header format: {magic}");
}
public static bool ReadHeaderPrefix(byte[] buffer,
ref int position,
ref short ___boolSize,
ref short ___numSize,
ref short ___strOffsets)
{
var magic = GetInt16(buffer, position);
position += 2;
DetermineVersion(magic);
// nameSize = GetInt16(buffer, position);
position += 2;
___boolSize = GetInt16(buffer, position);
position += 2;
___numSize = GetInt16(buffer, position);
position += 2;
___strOffsets = GetInt16(buffer, position);
position += 2;
// strSize = GetInt16(buffer, position);
position += 2;
return false;
}
public static IEnumerable<CodeInstruction> GetTermInfoNumbersTranspiler(IEnumerable<CodeInstruction> instructions)
{
// This implementation does not seem to have changed so I will be using indexes like the lazy fuck I am
var list = instructions.ToList();
list[31] = new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(XTermFix), nameof(intOffset)));
list[36] = new CodeInstruction(OpCodes.Nop);
list[39] = new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(XTermFix), nameof(GetInteger)));
return list;
}
public static IEnumerable<CodeInstruction> GetTermInfoStringsTranspiler(IEnumerable<CodeInstruction> instructions)
{
// This implementation does not seem to have changed so I will be using indexes like the lazy fuck I am
var list = instructions.ToList();
list[32] = new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(XTermFix), nameof(intOffset)));
return list;
}
}