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.

244 lines
9.4 KiB

5 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 string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  23. private static 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}.{name.Version}.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}.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. Console.WriteLine("Configuring up library loading");
  50. SetupAssemblyFilenames(true);
  51. AppDomain.CurrentDomain.AssemblyResolve -= AssemblyLibLoader;
  52. AppDomain.CurrentDomain.AssemblyResolve += AssemblyLibLoader;
  53. }
  54. internal static void SetupAssemblyFilenames(bool force = false)
  55. {
  56. if (FilenameLocations == null || force)
  57. {
  58. Console.WriteLine("Calculating assembly filenames");
  59. FilenameLocations = new Dictionary<string, string>();
  60. foreach (var fn in TraverseTree(LibraryPath, s => s != NativeLibraryPath))
  61. if (FilenameLocations.ContainsKey(fn.Name))
  62. Log(Logger.Level.Critical, $"Multiple instances of {fn.Name} exist in Libs! Ignoring {fn.FullName}");
  63. else FilenameLocations.Add(fn.Name, fn.FullName);
  64. foreach (var kvp in FilenameLocations) Console.WriteLine(kvp);
  65. if (!SetDefaultDllDirectories(LoadLibraryFlags.LOAD_LIBRARY_SEARCH_USER_DIRS | LoadLibraryFlags.LOAD_LIBRARY_SEARCH_SYSTEM32
  66. | LoadLibraryFlags.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LoadLibraryFlags.LOAD_LIBRARY_SEARCH_APPLICATION_DIR))
  67. {
  68. var err = new Win32Exception();
  69. Log(Logger.Level.Critical, $"Error configuring DLL search path");
  70. Log(Logger.Level.Critical, err);
  71. return;
  72. }
  73. void AddDir(string path)
  74. {
  75. var retPtr = AddDllDirectory(path);
  76. if (retPtr == IntPtr.Zero)
  77. {
  78. var err = new Win32Exception();
  79. Log(Logger.Level.Warning, $"Could not add DLL directory");
  80. Log(Logger.Level.Warning, err);
  81. }
  82. }
  83. if (Directory.Exists(NativeLibraryPath))
  84. {
  85. AddDir(NativeLibraryPath);
  86. TraverseTree(NativeLibraryPath, dir =>
  87. { // this is a terrible hack for iterating directories
  88. AddDir(dir); return true;
  89. }).All(f => true); // force it to iterate all
  90. }
  91. //var unityData = Directory.EnumerateDirectories(Environment.CurrentDirectory, "*_Data").First();
  92. //AddDir(Path.Combine(unityData, "Plugins"));
  93. foreach (var dir in Environment.GetEnvironmentVariable("path").Split(Path.PathSeparator))
  94. AddDir(dir);
  95. }
  96. }
  97. public static Assembly AssemblyLibLoader(object source, ResolveEventArgs e)
  98. {
  99. var asmName = new AssemblyName(e.Name);
  100. return LoadLibrary(asmName);
  101. }
  102. internal static Assembly LoadLibrary(AssemblyName asmName)
  103. {
  104. Log(Logger.Level.Debug, $"Resolving library {asmName}");
  105. SetupAssemblyFilenames();
  106. Console.WriteLine($"Looking for {asmName.Name} {asmName.Version} ({asmName.Name}.{asmName.Version}.dll)");
  107. var testFile = $"{asmName.Name}.{asmName.Version}.dll";
  108. Log(Logger.Level.Debug, $"Looking for file {testFile}");
  109. if (FilenameLocations.TryGetValue(testFile, out var path))
  110. {
  111. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  112. if (File.Exists(path))
  113. return Assembly.LoadFrom(path);
  114. Log(Logger.Level.Critical, $"but {path} no longer exists!");
  115. }
  116. else if (FilenameLocations.TryGetValue(testFile = $"{asmName.Name}.dll", out path))
  117. {
  118. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  119. if (File.Exists(path))
  120. return Assembly.LoadFrom(path);
  121. Log(Logger.Level.Critical, $"but {path} no longer exists!");
  122. }
  123. Log(Logger.Level.Critical, $"No library {asmName} found");
  124. return null;
  125. }
  126. internal static void Log(Logger.Level lvl, string message)
  127. { // multiple proxy methods to delay loading of assemblies until it's done
  128. if (Logger.LogCreated)
  129. AssemblyLibLoaderCallLogger(lvl, message);
  130. else
  131. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  132. Console.WriteLine($"[{lvl}] {message}");
  133. }
  134. internal static void Log(Logger.Level lvl, Exception message)
  135. { // multiple proxy methods to delay loading of assemblies until it's done
  136. if (Logger.LogCreated)
  137. AssemblyLibLoaderCallLogger(lvl, message);
  138. else
  139. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  140. Console.WriteLine($"[{lvl}] {message}");
  141. }
  142. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, string message) => Logger.libLoader.Log(lvl, message);
  143. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, Exception message) => Logger.libLoader.Log(lvl, message);
  144. // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-iterate-through-a-directory-tree
  145. private static IEnumerable<FileInfo> TraverseTree(string root, Func<string, bool> dirValidator = null)
  146. {
  147. if (dirValidator == null) dirValidator = s => true;
  148. Stack<string> dirs = new Stack<string>(32);
  149. if (!Directory.Exists(root))
  150. throw new ArgumentException();
  151. dirs.Push(root);
  152. while (dirs.Count > 0)
  153. {
  154. string currentDir = dirs.Pop();
  155. string[] subDirs;
  156. try
  157. {
  158. subDirs = Directory.GetDirectories(currentDir);
  159. }
  160. catch (UnauthorizedAccessException)
  161. { continue; }
  162. catch (DirectoryNotFoundException)
  163. { continue; }
  164. string[] files;
  165. try
  166. {
  167. files = Directory.GetFiles(currentDir);
  168. }
  169. catch (UnauthorizedAccessException)
  170. { continue; }
  171. catch (DirectoryNotFoundException)
  172. { continue; }
  173. foreach (string str in subDirs)
  174. if (dirValidator(str)) dirs.Push(str);
  175. foreach (string file in files)
  176. {
  177. FileInfo nextValue;
  178. try
  179. {
  180. nextValue = new FileInfo(file);
  181. }
  182. catch (FileNotFoundException)
  183. { continue; }
  184. yield return nextValue;
  185. }
  186. }
  187. }
  188. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  189. private static extern IntPtr AddDllDirectory(string lpPathName);
  190. [Flags]
  191. [SuppressMessage("ReSharper", "InconsistentNaming")]
  192. [SuppressMessage("ReSharper", "UnusedMember.Local")]
  193. private enum LoadLibraryFlags : uint
  194. {
  195. None = 0,
  196. LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200,
  197. LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000,
  198. LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800,
  199. LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400,
  200. }
  201. [DllImport("kernel32.dll", SetLastError = true)]
  202. private static extern bool SetDefaultDllDirectories(LoadLibraryFlags dwFlags);
  203. }
  204. }