* 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
UnityLogCallback ignored its second parameter, so Unity exceptions and
errors logged only their message. Append the trace for Exception and Error
when Unity gives one. The Mono source already does this for Exception. Log
and Warning stay as they are, since in the game I tested Unity passed a
trace for most of those.
Fixes#660
Co-authored-by: mirfalltnixein <22786734+mirfalltnixein@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Cake's Zip creates each entry with ZipArchive.CreateEntry and copies the
bytes, so file modes on disk are never recorded and every file ends up as
0644. run_bepinex.sh therefore isn't executable after extracting, and users
have to chmod +x it before ./run_bepinex.sh %command% works. Set its mode
to 0755 after packing.
Co-authored-by: mirfalltnixein <22786734+mirfalltnixein@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Follow PE export jmp thunks before applying a native detour.
GetProcAddress of il2cpp_runtime_invoke can be a jmp rel32 stub. Dobby aborting on that stub is BepInEx#1188-class. Resolve E9 and FF 25 in INativeDetour.Create so Default/Dobby and Funchook all patch the prologue. No-op when the pointer is already a function body.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Use IntPtr.Size when following FF 25 thunks.
nint.Size does not exist on the net6.0 BepInEx IL2CPP target.
Co-authored-by: Cursor <cursoragent@cursor.com>
Two related failures on aggressively stripped Unity Mono builds:
1. InitializeLoggers reads Application.unityVersion, which the managed
code stripper can remove. The version is only used for an
informational log line, but a MissingMethodException there aborts the
rest of chainloader initialisation. Read it defensively instead.
2. UnityChainloader.Initialize caught every exception, logged it as
Fatal, and returned normally. StaticStart then called Execute() on a
chainloader that was never initialised, so BepInEx logged
"Chainloader startup complete" while every plugin silently never ran.
Rethrow so a failed init cannot be mistaken for a successful one.
Verified on Beacon Pines (Unity 2021.3.45f1, Mono, x64), which strips
both Application.unityVersion and the log-callback members.
Co-authored-by: ManlyMarco <39247311+ManlyMarco@users.noreply.github.com>
UnityLogSource's static constructor falls back to
Application.RegisterLogCallback when Application.logMessageReceived is
absent. Unity's managed code stripper can remove both, in which case
GetMethod returns null and the unguarded Invoke throws a
NullReferenceException out of the static constructor.
That exception propagates through chainloader initialisation, so the
chainloader never starts and no plugins load. The failure is close to
undiagnosable: LogOutput.log ends at "Preloader finished" with no error,
and the exception only appears on stdout.
Unity log forwarding is optional, so warn and continue instead of taking
the whole loader down.
Seen on Beacon Pines (Unity 2021.3.45f1, Mono), whose
UnityEngine.Application has neither member.
HashStrings passed str.Length (a char count) as the byte count to
MD5.TransformBlock, so for any non-ASCII string only a truncated prefix
of the UTF-8 bytes was hashed. Capture the byte array and use its Length.
ConfigFile documents its public methods as thread-safe, but GetEnumerator
returned the live Dictionary enumerator with no lock, so a concurrent
Bind/Reload could invalidate it mid-foreach. Snapshot under _ioLock instead.
typeof(byte) was registered twice in the TypeConverters initializer; the
second entry silently overwrote the first. Keep the one grouped with the
other integral types.
Patch-method discovery already reads both with the plural
MetadataHelper.GetAttributes<T>(), and the docs say additional target
attributes can be specified, but the attributes lacked
AllowMultiple = true, so the compiler rejected a second one (CS0579).
Set AllowMultiple = true on both.
* Don't abort startup when the config file can't be written
ConfigFile.Save opens the file for writing with no exception handling and is invoked automatically via SaveOnConfigSet while settings are bound during startup, before logging is initialized. A read-only or otherwise unwritable config file (a read-only install directory, a file locked by another process or antivirus) therefore throws UnauthorizedAccessException out of the early startup path and shows the Failed to start BepInEx dialog.
* Degrade instead of crashing when the interop assemblies are missing
OnInvokeMethod references interop types (UnityEngine.Application/LogType) in its body. The CLR JIT-compiles the whole method before running any of it, so when the interop assemblies cannot be resolved the method throws FileNotFoundException at JIT time -- before its own try is entered -- and the exception escapes into the native runtime-invoke detour and crashes the process with nothing logged.
Move the interop-referencing call into its own SetupUnityLogging method called inside the try. OnInvokeMethod then JITs without the interop assemblies present, the missing-interop failure is caught, and the loader degrades (logs and continues) so the game runs unmodded. Set unhook at the top of the try so the detour fires exactly once even on failure.
* Condense the interop-degrade comments and reword the fatal log
Per review: trim the JIT-bypass comments to one line each and change
the fatal message to "Unable to execute IL2CPP chainloader, no plugins
will be loaded".
BaseChainloader.Execute invoked the Finished event inside the same
try/catch that reports plugin-loading failures, so an exception thrown
by a Finished event listener was logged as "Error occurred loading
plugins:" even though it was unrelated to plugin loading.
Move Finished?.Invoke() into its own try/catch with an accurate
message. Control flow is otherwise unchanged: Finished still runs only
after LoadPlugins succeeds, a throwing listener is still caught, and
"Chainloader startup complete" is still logged afterwards.
Fixes#842
The chainloader collected both not-installed dependencies and
installed-but-incompatible-version dependencies into one list and
reported them all as "missing dependencies", which is confusing when
the plugin is present but on a version outside the requested range.
Separate the two cases and log distinct, actionable messages: one for
dependencies that are not installed, and one for dependencies present
with an incompatible version (showing the found version and the
required range).
Also expand the BepInDependency(string, string) xmldoc: the version is
a SemVer range, link the range syntax, and warn about the BepInEx 5 ->
6 behaviour change (a bare version was a minimum, now it is exact).
Fixes#779
When the Unity base-libraries download fails (commonly a 404 for a
Unity version not yet hosted on unity.bepinex.dev), the uncaught
HttpRequestException surfaced only as a cryptic "Failed to generate
Il2Cpp interop assemblies" and the game would not launch -- even
though a local fallback (the unity-libs directory) already exists.
Catch the download failure and throw a clear message naming the Unity
version, the URL and the two workarounds: place a matching
base-libraries .zip in the unity-libs directory, or point the
[IL2CPP] UnityBaseLibrariesSource config at a valid URL.
Refs #1295, #1084, #986, #941, #515
Change the behaviors of the default providers so if multiple assemblies with the same name exists, but in different directories, ignore any that are located deeper.