You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

239 lines
9.2 KiB

4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Linq;
  9. using IPA.Logging;
  10. using IPA.Utilities;
  11. using Mono.Cecil;
  12. #if NET3
  13. using Net3_Proxy;
  14. using Directory = Net3_Proxy.Directory;
  15. using Path = Net3_Proxy.Path;
  16. using File = Net3_Proxy.File;
  17. #endif
  18. namespace IPA.Loader
  19. {
  20. internal class CecilLibLoader : BaseAssemblyResolver
  21. {
  22. private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  23. private static readonly string CurrentAssemblyPath = Assembly.GetExecutingAssembly().Location;
  24. public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
  25. {
  26. LibLoader.SetupAssemblyFilenames();
  27. if (name.Name == CurrentAssemblyName)
  28. return AssemblyDefinition.ReadAssembly(CurrentAssemblyPath, parameters);
  29. if (LibLoader.FilenameLocations.TryGetValue($"{name.Name}.dll", out var path))
  30. {
  31. if (File.Exists(path))
  32. return AssemblyDefinition.ReadAssembly(path, parameters);
  33. }
  34. else if (LibLoader.FilenameLocations.TryGetValue($"{name.Name}.{name.Version}.dll", out path))
  35. {
  36. if (File.Exists(path))
  37. return AssemblyDefinition.ReadAssembly(path, parameters);
  38. }
  39. return base.Resolve(name, parameters);
  40. }
  41. }
  42. internal static class LibLoader
  43. {
  44. internal static string LibraryPath => Path.Combine(Environment.CurrentDirectory, "Libs");
  45. internal static string NativeLibraryPath => Path.Combine(LibraryPath, "Native");
  46. internal static Dictionary<string, string> FilenameLocations;
  47. internal static void Configure()
  48. {
  49. SetupAssemblyFilenames(true);
  50. AppDomain.CurrentDomain.AssemblyResolve -= AssemblyLibLoader;
  51. AppDomain.CurrentDomain.AssemblyResolve += AssemblyLibLoader;
  52. }
  53. internal static void SetupAssemblyFilenames(bool force = false)
  54. {
  55. if (FilenameLocations == null || force)
  56. {
  57. FilenameLocations = new Dictionary<string, string>();
  58. foreach (var fn in TraverseTree(LibraryPath, s => s != NativeLibraryPath))
  59. if (FilenameLocations.ContainsKey(fn.Name))
  60. Log(Logger.Level.Critical, $"Multiple instances of {fn.Name} exist in Libs! Ignoring {fn.FullName}");
  61. else FilenameLocations.Add(fn.Name, fn.FullName);
  62. if (!SetDefaultDllDirectories(LoadLibraryFlags.LOAD_LIBRARY_SEARCH_USER_DIRS | LoadLibraryFlags.LOAD_LIBRARY_SEARCH_SYSTEM32
  63. | LoadLibraryFlags.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LoadLibraryFlags.LOAD_LIBRARY_SEARCH_APPLICATION_DIR))
  64. {
  65. var err = new Win32Exception();
  66. Log(Logger.Level.Critical, $"Error configuring DLL search path");
  67. Log(Logger.Level.Critical, err);
  68. return;
  69. }
  70. static void AddDir(string path)
  71. {
  72. var retPtr = AddDllDirectory(path);
  73. if (retPtr == IntPtr.Zero)
  74. {
  75. var err = new Win32Exception();
  76. Log(Logger.Level.Warning, $"Could not add DLL directory {path}");
  77. Log(Logger.Level.Warning, err);
  78. }
  79. }
  80. if (Directory.Exists(NativeLibraryPath))
  81. {
  82. AddDir(NativeLibraryPath);
  83. TraverseTree(NativeLibraryPath, dir =>
  84. { // this is a terrible hack for iterating directories
  85. AddDir(dir); return true;
  86. }).All(f => true); // force it to iterate all
  87. }
  88. //var unityData = Directory.EnumerateDirectories(Environment.CurrentDirectory, "*_Data").First();
  89. //AddDir(Path.Combine(unityData, "Plugins"));
  90. foreach (var dir in Environment.GetEnvironmentVariable("path").Split(Path.PathSeparator))
  91. AddDir(dir);
  92. }
  93. }
  94. public static Assembly AssemblyLibLoader(object source, ResolveEventArgs e)
  95. {
  96. var asmName = new AssemblyName(e.Name);
  97. return LoadLibrary(asmName);
  98. }
  99. internal static Assembly LoadLibrary(AssemblyName asmName)
  100. {
  101. Log(Logger.Level.Debug, $"Resolving library {asmName}");
  102. SetupAssemblyFilenames();
  103. var testFile = $"{asmName.Name}.dll";
  104. Log(Logger.Level.Debug, $"Looking for file {asmName.Name}.dll");
  105. if (FilenameLocations.TryGetValue(testFile, out var path))
  106. {
  107. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  108. if (File.Exists(path))
  109. return Assembly.LoadFrom(path);
  110. Log(Logger.Level.Critical, $"but {path} no longer exists!");
  111. }
  112. else if (FilenameLocations.TryGetValue(testFile = $"{asmName.Name}.{asmName.Version}.dll", out path))
  113. {
  114. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  115. Log(Logger.Level.Warning, $"File {testFile} should be renamed to just {asmName.Name}.dll");
  116. if (File.Exists(path))
  117. return Assembly.LoadFrom(path);
  118. Log(Logger.Level.Critical, $"but {path} no longer exists!");
  119. }
  120. Log(Logger.Level.Critical, $"No library {asmName} found");
  121. return null;
  122. }
  123. internal static void Log(Logger.Level lvl, string message)
  124. { // multiple proxy methods to delay loading of assemblies until it's done
  125. if (Logger.LogCreated)
  126. AssemblyLibLoaderCallLogger(lvl, message);
  127. else
  128. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  129. Console.WriteLine($"[{lvl}] {message}");
  130. }
  131. internal static void Log(Logger.Level lvl, Exception message)
  132. { // multiple proxy methods to delay loading of assemblies until it's done
  133. if (Logger.LogCreated)
  134. AssemblyLibLoaderCallLogger(lvl, message);
  135. else
  136. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  137. Console.WriteLine($"[{lvl}] {message}");
  138. }
  139. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, string message) => Logger.libLoader.Log(lvl, message);
  140. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, Exception message) => Logger.libLoader.Log(lvl, message);
  141. // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-iterate-through-a-directory-tree
  142. private static IEnumerable<FileInfo> TraverseTree(string root, Func<string, bool> dirValidator = null)
  143. {
  144. if (dirValidator == null) dirValidator = s => true;
  145. Stack<string> dirs = new Stack<string>(32);
  146. if (!Directory.Exists(root))
  147. throw new ArgumentException();
  148. dirs.Push(root);
  149. while (dirs.Count > 0)
  150. {
  151. string currentDir = dirs.Pop();
  152. string[] subDirs;
  153. try
  154. {
  155. subDirs = Directory.GetDirectories(currentDir);
  156. }
  157. catch (UnauthorizedAccessException)
  158. { continue; }
  159. catch (DirectoryNotFoundException)
  160. { continue; }
  161. string[] files;
  162. try
  163. {
  164. files = Directory.GetFiles(currentDir);
  165. }
  166. catch (UnauthorizedAccessException)
  167. { continue; }
  168. catch (DirectoryNotFoundException)
  169. { continue; }
  170. foreach (string str in subDirs)
  171. if (dirValidator(str)) dirs.Push(str);
  172. foreach (string file in files)
  173. {
  174. FileInfo nextValue;
  175. try
  176. {
  177. nextValue = new FileInfo(file);
  178. }
  179. catch (FileNotFoundException)
  180. { continue; }
  181. yield return nextValue;
  182. }
  183. }
  184. }
  185. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  186. private static extern IntPtr AddDllDirectory(string lpPathName);
  187. [Flags]
  188. [SuppressMessage("ReSharper", "InconsistentNaming")]
  189. [SuppressMessage("ReSharper", "UnusedMember.Local")]
  190. private enum LoadLibraryFlags : uint
  191. {
  192. None = 0,
  193. LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200,
  194. LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000,
  195. LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800,
  196. LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400,
  197. }
  198. [DllImport("kernel32.dll", SetLastError = true)]
  199. private static extern bool SetDefaultDllDirectories(LoadLibraryFlags dwFlags);
  200. }
  201. }