Sfoglia il codice sorgente

Fix logging not working in Unity 2018

denikson 6 anni fa
parent
commit
66c8a3b6c6

+ 9 - 0
BepInEx/BepInEx.csproj

@@ -36,6 +36,14 @@
     <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     <DebugSymbols>false</DebugSymbols>
   </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'v2018|AnyCPU'">
+    <OutputPath>..\bin\</OutputPath>
+    <DefineConstants>TRACE;UNITY_2018</DefineConstants>
+    <Optimize>true</Optimize>
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
+  </PropertyGroup>
   <ItemGroup>
     <Reference Include="0Harmony">
       <HintPath>..\lib\0Harmony.dll</HintPath>
@@ -51,6 +59,7 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Bootstrap\Entrypoint.cs" />
+    <Compile Include="Bootstrap\UnityPatches.cs" />
     <Compile Include="Contract\Attributes.cs" />
     <Compile Include="Bootstrap\AssemblyPatcher.cs" />
     <Compile Include="Bootstrap\Preloader.cs" />

+ 67 - 65
BepInEx/Bootstrap/Preloader.cs

@@ -42,23 +42,25 @@ namespace BepInEx.Bootstrap
 
 		public static void Run()
 		{
-			try
-			{
-				AllocateConsole();
+		    try
+		    {
+		        AllocateConsole();
 
-				PreloaderLog =
-					new PreloaderLogWriter(Utility.SafeParseBool(Config.GetEntry("preloader-logconsole", "false", "BepInEx")));
-				PreloaderLog.Enabled = true;
+		        UnityPatches.Apply();
 
-				string consoleTile =
-					$"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {Process.GetCurrentProcess().ProcessName}";
-				ConsoleWindow.Title = consoleTile;
+		        PreloaderLog = 
+		                new PreloaderLogWriter(Utility.SafeParseBool(Config.GetEntry("preloader-logconsole", "false", "BepInEx")));
+		        PreloaderLog.Enabled = true;
 
-				Logger.SetLogger(PreloaderLog);
+		        string consoleTile =
+		                $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {Process.GetCurrentProcess().ProcessName}";
+		        ConsoleWindow.Title = consoleTile;
 
-				PreloaderLog.WriteLine(consoleTile);
+		        Logger.SetLogger(PreloaderLog);
 
-				#if DEBUG
+		        PreloaderLog.WriteLine(consoleTile);
+
+#if DEBUG
 
 				object[] attributes = typeof(DebugInfoAttribute).Assembly.GetCustomAttributes(typeof(DebugInfoAttribute), false);
 				
@@ -69,59 +71,59 @@ namespace BepInEx.Bootstrap
 					PreloaderLog.WriteLine(attribute.Info);
 				}
 
-				#endif
-
-				Logger.Log(LogLevel.Message, "Preloader started");
-
-				string entrypointAssembly = Config.GetEntry("entrypoint-assembly", "UnityEngine.dll", "Preloader");
-
-				AddPatcher(new[] {entrypointAssembly}, PatchEntrypoint);
-
-				if (Directory.Exists(Paths.PatcherPluginPath))
-				{
-					var sortedPatchers = new SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
-
-					foreach (string assemblyPath in Directory.GetFiles(Paths.PatcherPluginPath, "*.dll"))
-						try
-						{
-							var assembly = Assembly.LoadFrom(assemblyPath);
-
-							foreach (KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>> kv in GetPatcherMethods(assembly))
-								sortedPatchers.Add(assembly.GetName().Name, kv);
-						}
-						catch (BadImageFormatException) { } //unmanaged DLL
-						catch (ReflectionTypeLoadException) { } //invalid references
-
-					foreach (KeyValuePair<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> kv in sortedPatchers)
-						AddPatcher(kv.Value.Value, kv.Value.Key);
-				}
-
-				AssemblyPatcher.PatchAll(Paths.ManagedPath, PatcherDictionary, Initializers, Finalizers);
-			}
-			catch (Exception ex)
-			{
-				Logger.Log(LogLevel.Fatal, "Could not run preloader!");
-				Logger.Log(LogLevel.Fatal, ex);
-
-				PreloaderLog.Enabled = false;
-
-				try
-				{
-					if (!ConsoleWindow.IsAttatched)
-					{
-						//if we've already attached the console, then the log will already be written to the console
-						AllocateConsole();
-						Console.Write(PreloaderLog);
-					}
-				}
-				finally
-				{
-					File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
-						PreloaderLog.ToString());
-
-					PreloaderLog.Dispose();
-				}
-			}
+#endif
+
+		        Logger.Log(LogLevel.Message, "Preloader started");
+
+		        string entrypointAssembly = Config.GetEntry("entrypoint-assembly", "UnityEngine.dll", "Preloader");
+
+		        AddPatcher(new[] {entrypointAssembly}, PatchEntrypoint);
+
+		        if (Directory.Exists(Paths.PatcherPluginPath))
+		        {
+		            var sortedPatchers = new SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
+
+		            foreach (string assemblyPath in Directory.GetFiles(Paths.PatcherPluginPath, "*.dll"))
+		                try
+		                {
+		                    var assembly = Assembly.LoadFrom(assemblyPath);
+
+		                    foreach (KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>> kv in GetPatcherMethods(assembly))
+		                        sortedPatchers.Add(assembly.GetName().Name, kv);
+		                }
+		                catch (BadImageFormatException) { } //unmanaged DLL
+		                catch (ReflectionTypeLoadException) { } //invalid references
+
+		            foreach (KeyValuePair<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> kv in sortedPatchers)
+		                AddPatcher(kv.Value.Value, kv.Value.Key);
+		        }
+
+		        AssemblyPatcher.PatchAll(Paths.ManagedPath, PatcherDictionary, Initializers, Finalizers);
+		    }
+		    catch (Exception ex)
+		    {
+		        Logger.Log(LogLevel.Fatal, "Could not run preloader!");
+		        Logger.Log(LogLevel.Fatal, ex);
+
+		        PreloaderLog.Enabled = false;
+
+		        try
+		        {
+		            if (!ConsoleWindow.IsAttatched)
+		            {
+		                //if we've already attached the console, then the log will already be written to the console
+		                AllocateConsole();
+		                Console.Write(PreloaderLog);
+		            }
+		        }
+		        finally
+		        {
+		            File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
+		                              PreloaderLog.ToString());
+
+		            PreloaderLog.Dispose();
+		        }
+		    }
 		}
 
 		/// <summary>

+ 28 - 0
BepInEx/Bootstrap/UnityPatches.cs

@@ -0,0 +1,28 @@
+using System;
+using Harmony;
+
+namespace BepInEx.Bootstrap
+{
+    internal static class UnityPatches
+    {
+        public static void Apply()
+        {
+            HarmonyInstance.Create("com.bepinex.unitypatches").PatchAll(typeof(UnityPatches));
+        }
+
+#if UNITY_2018
+        /*
+         * DESC: Workaround for Trace class not working because of missing .config file
+         * AFFECTS: Unity 2018+
+         */
+        [HarmonyPatch(typeof(AppDomain))]
+        [HarmonyPatch(nameof(AppDomain.SetupInformation), PropertyMethod.Getter)]
+        [HarmonyPostfix]
+        public static void GetExeConfigName(AppDomainSetup __result)
+        {
+            __result.ApplicationBase = $"file://{Paths.GameRootPath}";
+            __result.ConfigurationFile = "app.config";
+        }
+#endif
+    }
+}

+ 9 - 0
BepInEx/Logging/UnityLogWriter.cs

@@ -17,7 +17,11 @@ namespace BepInEx.Logging
 		/// <param name="value">The value to write.</param>
         public void WriteToLog(string value)
         {
+#if UNITY_2018
+            UnityEngine.UnityLogWriter.WriteStringToUnityLogImpl(value);
+#else
             UnityEngine.UnityLogWriter.WriteStringToUnityLog(value);
+#endif
         }
 
         protected void InternalWrite(string value)
@@ -94,6 +98,11 @@ namespace UnityEngine
 {
     internal sealed class UnityLogWriter
     {
+#if UNITY_2018
+        [MethodImpl(MethodImplOptions.InternalCall)]
+        public static extern void WriteStringToUnityLogImpl(string s);
+#endif
+
         [MethodImpl(MethodImplOptions.InternalCall)]
         public static extern void WriteStringToUnityLog(string s);
     }