Kaynağa Gözat

Merge branch 'master' into feature-unity-2018

Bepis 6 yıl önce
ebeveyn
işleme
0d72d29a3c

+ 104 - 71
BepInEx/Bootstrap/AssemblyPatcher.cs

@@ -2,24 +2,25 @@
 using System.Collections.Generic;
 using System.IO;
 using System.Reflection;
+using Harmony;
 using Mono.Cecil;
 
 namespace BepInEx.Bootstrap
 {
-	/// <summary>
-	/// Delegate used in patching assemblies.
-	/// </summary>
-	/// <param name="assembly">The assembly that is being patched.</param>
+    /// <summary>
+    /// Delegate used in patching assemblies.
+    /// </summary>
+    /// <param name="assembly">The assembly that is being patched.</param>
     public delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly);
 
-	/// <summary>
-	/// Worker class which is used for loading and patching entire folders of assemblies, or alternatively patching and loading assemblies one at a time.
-	/// </summary>
+    /// <summary>
+    /// Worker class which is used for loading and patching entire folders of assemblies, or alternatively patching and loading assemblies one at a time.
+    /// </summary>
     public static class AssemblyPatcher
     {
-		/// <summary>
-		/// Configuration value of whether assembly dumping is enabled or not.
-		/// </summary>
+        /// <summary>
+        /// Configuration value of whether assembly dumping is enabled or not.
+        /// </summary>
         private static bool DumpingEnabled => Utility.SafeParseBool(Config.GetEntry("dump-assemblies", "false", "Preloader"));
 
         /// <summary>
@@ -31,10 +32,10 @@ namespace BepInEx.Bootstrap
         /// <param name="finalizers">List of finalizers to run before returning</param>
         public static void PatchAll(string directory, IDictionary<AssemblyPatcherDelegate, IEnumerable<string>> patcherMethodDictionary, IEnumerable<Action> initializers = null, IEnumerable<Action> finalizers = null)
         {
-			//run all initializers
-			if (initializers != null)
-				foreach (Action init in initializers)
-					init.Invoke();
+            //run all initializers
+            if (initializers != null)
+                foreach (Action init in initializers)
+                    init.Invoke();
 
             //load all the requested assemblies
             Dictionary<string, AssemblyDefinition> assemblies = new Dictionary<string, AssemblyDefinition>();
@@ -42,7 +43,7 @@ namespace BepInEx.Bootstrap
             foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll"))
             {
                 var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
-                
+
                 //NOTE: this is special cased here because the dependency handling for System.dll is a bit wonky
                 //System has an assembly reference to itself, and it also has a reference to Mono.Security causing a circular dependency
                 //It's also generally dangerous to change system.dll since so many things rely on it, 
@@ -55,75 +56,107 @@ namespace BepInEx.Bootstrap
                 }
 
                 assemblies.Add(Path.GetFileName(assemblyPath), assembly);
+                PatchedAssemblyResolver.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
             }
 
             HashSet<string> patchedAssemblies = new HashSet<string>();
 
             //call the patchers on the assemblies
-	        foreach (var patcherMethod in patcherMethodDictionary)
-	        {
-		        foreach (string assemblyFilename in patcherMethod.Value)
-		        {
-		            if (assemblies.TryGetValue(assemblyFilename, out var assembly))
-		            {
-		                Patch(ref assembly, patcherMethod.Key);
-			            assemblies[assemblyFilename] = assembly;
-		                patchedAssemblies.Add(assemblyFilename);
+            foreach (var patcherMethod in patcherMethodDictionary)
+            {
+                foreach (string assemblyFilename in patcherMethod.Value)
+                {
+                    if (assemblies.TryGetValue(assemblyFilename, out var assembly))
+                    {
+                        Patch(ref assembly, patcherMethod.Key);
+                        assemblies[assemblyFilename] = assembly;
+                        patchedAssemblies.Add(assemblyFilename);
                     }
-		        }
-	        }
+                }
+            }
 
             // Finally, load all assemblies into memory
-			foreach (var kv in assemblies)
-			{
-				string filename = kv.Key;
-				var assembly = kv.Value;
-
-			    if (DumpingEnabled && patchedAssemblies.Contains(filename))
-			    {
-			        using (MemoryStream mem = new MemoryStream())
-			        {
-			            string dirPath = Path.Combine(Paths.PluginPath, "DumpedAssemblies");
-
-			            if (!Directory.Exists(dirPath))
-			                Directory.CreateDirectory(dirPath);
-                            
-			            assembly.Write(mem);
-			            File.WriteAllBytes(Path.Combine(dirPath, filename), mem.ToArray());
-			        }
-			    }
-
-			    Load(assembly);
-			    assembly.Dispose();
-			}
-			
-	        //run all finalizers
-	        if (finalizers != null)
-		        foreach (Action finalizer in finalizers)
-			        finalizer.Invoke();
+            foreach (var kv in assemblies)
+            {
+                string filename = kv.Key;
+                var assembly = kv.Value;
+
+                if (DumpingEnabled && patchedAssemblies.Contains(filename))
+                {
+                    using (MemoryStream mem = new MemoryStream())
+                    {
+                        string dirPath = Path.Combine(Paths.PluginPath, "DumpedAssemblies");
+
+                        if (!Directory.Exists(dirPath))
+                            Directory.CreateDirectory(dirPath);
+
+                        assembly.Write(mem);
+                        File.WriteAllBytes(Path.Combine(dirPath, filename), mem.ToArray());
+                    }
+                }
+
+                Load(assembly);
+                assembly.Dispose();
+            }
+
+            // Patch Assembly.Location and Assembly.CodeBase only if the assemblies were loaded from memory
+            PatchedAssemblyResolver.ApplyPatch();
+
+            //run all finalizers
+            if (finalizers != null)
+                foreach (Action finalizer in finalizers)
+                    finalizer.Invoke();
         }
 
-		/// <summary>
-		/// Patches an individual assembly, without loading it.
-		/// </summary>
-		/// <param name="assembly">The assembly definition to apply the patch to.</param>
-		/// <param name="patcherMethod">The patcher to use to patch the assembly definition.</param>
+        /// <summary>
+        /// Patches an individual assembly, without loading it.
+        /// </summary>
+        /// <param name="assembly">The assembly definition to apply the patch to.</param>
+        /// <param name="patcherMethod">The patcher to use to patch the assembly definition.</param>
         public static void Patch(ref AssemblyDefinition assembly, AssemblyPatcherDelegate patcherMethod)
         {
-	        patcherMethod.Invoke(ref assembly);
+            patcherMethod.Invoke(ref assembly);
+        }
+
+        /// <summary>
+        /// Loads an individual assembly defintion into the CLR.
+        /// </summary>
+        /// <param name="assembly">The assembly to load.</param>
+        public static void Load(AssemblyDefinition assembly)
+        {
+            using (MemoryStream assemblyStream = new MemoryStream())
+            {
+                assembly.Write(assemblyStream);
+                Assembly.Load(assemblyStream.ToArray());
+            }
         }
+    }
 
-		/// <summary>
-		/// Loads an individual assembly defintion into the CLR.
-		/// </summary>
-		/// <param name="assembly">The assembly to load.</param>
-	    public static void Load(AssemblyDefinition assembly)
-	    {
-		    using (MemoryStream assemblyStream = new MemoryStream())
-		    {
-			    assembly.Write(assemblyStream);
-			    Assembly.Load(assemblyStream.ToArray());
-		    }
-	    }
+    internal static class PatchedAssemblyResolver
+    {
+        public static Dictionary<string, string> AssemblyLocations { get; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
+
+        public static void ApplyPatch()
+        {
+            HarmonyInstance.Create("com.bepis.bepinex.asmlocationfix").PatchAll(typeof(PatchedAssemblyResolver));
+        }
+
+        [HarmonyPatch(typeof(Assembly))]
+        [HarmonyPatch(nameof(Assembly.Location), PropertyMethod.Getter)]
+        [HarmonyPostfix]
+        public static void GetLocation(ref string __result, Assembly __instance)
+        {
+            if (AssemblyLocations.TryGetValue(__instance.FullName, out string location))
+                __result = location;
+        }
+
+        [HarmonyPatch(typeof(Assembly))]
+        [HarmonyPatch(nameof(Assembly.CodeBase), PropertyMethod.Getter)]
+        [HarmonyPostfix]
+        public static void GetCodeBase(ref string __result, Assembly __instance)
+        {
+            if (AssemblyLocations.TryGetValue(__instance.FullName, out string location))
+                __result = $"file://{location.Replace('\\', '/')}";
+        }
     }
 }

+ 54 - 47
BepInEx/Bootstrap/Preloader.cs

@@ -73,57 +73,64 @@ namespace BepInEx.Bootstrap
 
 #endif
 
-		        Logger.Log(LogLevel.Message, "Preloader started");
+				Logger.Log(LogLevel.Message, "Preloader started");
 
-		        string entrypointAssembly = Config.GetEntry("entrypoint-assembly", "UnityEngine.dll", "Preloader");
+				string entrypointAssembly = Config.GetEntry("entrypoint-assembly", "UnityEngine.dll", "Preloader");
 
-		        AddPatcher(new[] {entrypointAssembly}, PatchEntrypoint);
+				AddPatcher(new[] {entrypointAssembly}, PatchEntrypoint);
 
-		        if (Directory.Exists(Paths.PatcherPluginPath))
-		        {
-		            var sortedPatchers = new SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
+				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<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> kv in GetPatcherMethods(assembly))
+							    try
+							    {
+							        sortedPatchers.Add(kv.Key, kv.Value);
+							    }
+							    catch (ArgumentException)
+							    {
+                                    Logger.Log(LogLevel.Warning, $"Found duplicate of patcher {kv.Key}!");
+							    }
+						}
+						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);
+				}
 
-		            foreach (string assemblyPath in Directory.GetFiles(Paths.PatcherPluginPath, "*.dll"))
-		                try
-		                {
-		                    var assembly = Assembly.LoadFrom(assemblyPath);
+				AssemblyPatcher.PatchAll(Paths.ManagedPath, PatcherDictionary, Initializers, Finalizers);
+			}
+			catch (Exception ex)
+			{
+				Logger.Log(LogLevel.Fatal, "Could not run preloader!");
+				Logger.Log(LogLevel.Fatal, ex);
 
-		                    foreach (KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>> kv in GetPatcherMethods(assembly))
-		                        sortedPatchers.Add(assembly.GetName().Name, kv);
-		                }
-		                catch (BadImageFormatException) { } //unmanaged DLL
-		                catch (ReflectionTypeLoadException) { } //invalid references
+				PreloaderLog.Enabled = false;
 
-		            foreach (KeyValuePair<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> kv in sortedPatchers)
-		                AddPatcher(kv.Value.Value, kv.Value.Key);
-		        }
+				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());
 
-		        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();
-		        }
-		    }
+					PreloaderLog.Dispose();
+				}
+			}
 		}
 
 		/// <summary>
@@ -131,9 +138,9 @@ namespace BepInEx.Bootstrap
 		/// </summary>
 		/// <param name="assembly">The assembly to scan.</param>
 		/// <returns>A dictionary of delegates which will be used to patch the targeted assemblies.</returns>
-		public static Dictionary<AssemblyPatcherDelegate, IEnumerable<string>> GetPatcherMethods(Assembly assembly)
+		public static Dictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> GetPatcherMethods(Assembly assembly)
 		{
-			var patcherMethods = new Dictionary<AssemblyPatcherDelegate, IEnumerable<string>>();
+			var patcherMethods = new Dictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
 
 			foreach (var type in assembly.GetExportedTypes())
 				try
@@ -179,7 +186,7 @@ namespace BepInEx.Bootstrap
 
 					var targets = (IEnumerable<string>) targetsProperty.GetValue(null, null);
 
-					patcherMethods[patchDelegate] = targets;
+					patcherMethods[$"{assembly.GetName().Name}{type.FullName}"] = new KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>(patchDelegate, targets);
 
 					var initMethod = type.GetMethod("Initialize",
 						BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,

+ 30 - 1
BepInEx/Bootstrap/TypeLoader.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.IO;
 using System.Reflection;
+using System.Text;
 using BepInEx.Logging;
 
 namespace BepInEx.Bootstrap
@@ -36,13 +37,41 @@ namespace BepInEx.Bootstrap
                     }
                 }
                 catch (BadImageFormatException) { } //unmanaged DLL
-                catch (ReflectionTypeLoadException)
+                catch (ReflectionTypeLoadException ex)
                 {
                     Logger.Log(LogLevel.Error, $"Could not load \"{Path.GetFileName(dll)}\" as a plugin!");
+                    Logger.Log(LogLevel.Debug, TypeLoadExceptionToString(ex));
                 }
             }
 
             return types;
         }
+
+        private static string TypeLoadExceptionToString(ReflectionTypeLoadException ex)
+        {
+            StringBuilder sb = new StringBuilder();
+            foreach (Exception exSub in ex.LoaderExceptions)
+            {
+                sb.AppendLine(exSub.Message);
+                if (exSub is FileNotFoundException exFileNotFound)
+                {
+                    if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
+                    {
+                        sb.AppendLine("Fusion Log:");
+                        sb.AppendLine(exFileNotFound.FusionLog);
+                    }
+                }
+                else if (exSub is FileLoadException exLoad)
+                {
+                    if (!string.IsNullOrEmpty(exLoad.FusionLog))
+                    {
+                        sb.AppendLine("Fusion Log:");
+                        sb.AppendLine(exLoad.FusionLog);
+                    }
+                }
+                sb.AppendLine();
+            }
+            return sb.ToString();
+        }
     }
 }

+ 5 - 1
BepInEx/Logging/UnityLogWriter.cs

@@ -61,6 +61,10 @@ namespace BepInEx.Logging
             Kon.ForegroundColor = level.GetConsoleColor();
             base.Log(level, entry);
             Kon.ForegroundColor = ConsoleColor.Gray;
+
+            // If the display level got ignored, still write it to the log
+            if ((DisplayedLevels & level) == LogLevel.None)
+                WriteToLog($"[{level.GetHighestLevel()}] {entry}\r\n");
         }
 
         public override void WriteLine(string value) => InternalWrite($"{value}\r\n");
@@ -102,7 +106,7 @@ namespace BepInEx.Logging
                     break;
                 case LogType.Log:
                 default:
-                    logLevel = LogLevel.Message;
+                    logLevel = LogLevel.Info;
                     break;
             }