Don't kill the chainloader when Unity log callbacks are stripped (#1389)

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.
This commit is contained in:
Drew Mochak authored and GitHub committed 2026-09-01 06:56:05 +02:00
1 parent 6abdba47ee
commit 6d82b2e5fc
1 file changed
+18
@@ -2,6 +2,7 @@
using System.Reflection;
using BepInEx.Logging;
using UnityEngine;
using Logger = BepInEx.Logging.Logger;
namespace BepInEx.Unity.Mono.Logging;
@@ -61,6 +62,23 @@ public class UnityLogSource : ILogSource
{
var registerLogCallback =
typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Public | BindingFlags.Static);
// Unity's managed code stripper can remove both Application.logMessageReceived and the
// legacy Application.RegisterLogCallback. Invoking a null MethodInfo here throws a
// NullReferenceException out of this static constructor, which propagates through
// Chainloader.Initialize and silently prevents the chainloader (and therefore every
// plugin) from starting. Unity log forwarding is optional, so degrade instead of
// taking the whole loader down with us.
if (registerLogCallback == null)
{
Logger.Log(LogLevel.Warning,
"Unity log forwarding is unavailable: neither " +
"Application.logMessageReceived nor Application.RegisterLogCallback exist " +
"in this build (they were most likely stripped). Unity log messages will " +
"not appear in the BepInEx log.");
return;
}
registerLogCallback.Invoke(null, new object[] { callback });
//UnsubscribeAction = () => registerLogCallback.Invoke(null, new object[] { null });
}