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.

237 lines
9.1 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. 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. 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");
  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}.{asmName.Version}.dll";
  104. Log(Logger.Level.Debug, $"Looking for file {testFile}");
  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}.dll", out path))
  113. {
  114. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  115. if (File.Exists(path))
  116. return Assembly.LoadFrom(path);
  117. Log(Logger.Level.Critical, $"but {path} no longer exists!");
  118. }
  119. Log(Logger.Level.Critical, $"No library {asmName} found");
  120. return null;
  121. }
  122. internal static void Log(Logger.Level lvl, string message)
  123. { // multiple proxy methods to delay loading of assemblies until it's done
  124. if (Logger.LogCreated)
  125. AssemblyLibLoaderCallLogger(lvl, message);
  126. else
  127. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  128. Console.WriteLine($"[{lvl}] {message}");
  129. }
  130. internal static void Log(Logger.Level lvl, Exception message)
  131. { // multiple proxy methods to delay loading of assemblies until it's done
  132. if (Logger.LogCreated)
  133. AssemblyLibLoaderCallLogger(lvl, message);
  134. else
  135. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  136. Console.WriteLine($"[{lvl}] {message}");
  137. }
  138. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, string message) => Logger.libLoader.Log(lvl, message);
  139. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, Exception message) => Logger.libLoader.Log(lvl, message);
  140. // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-iterate-through-a-directory-tree
  141. private static IEnumerable<FileInfo> TraverseTree(string root, Func<string, bool> dirValidator = null)
  142. {
  143. if (dirValidator == null) dirValidator = s => true;
  144. Stack<string> dirs = new Stack<string>(32);
  145. if (!Directory.Exists(root))
  146. throw new ArgumentException();
  147. dirs.Push(root);
  148. while (dirs.Count > 0)
  149. {
  150. string currentDir = dirs.Pop();
  151. string[] subDirs;
  152. try
  153. {
  154. subDirs = Directory.GetDirectories(currentDir);
  155. }
  156. catch (UnauthorizedAccessException)
  157. { continue; }
  158. catch (DirectoryNotFoundException)
  159. { continue; }
  160. string[] files;
  161. try
  162. {
  163. files = Directory.GetFiles(currentDir);
  164. }
  165. catch (UnauthorizedAccessException)
  166. { continue; }
  167. catch (DirectoryNotFoundException)
  168. { continue; }
  169. foreach (string str in subDirs)
  170. if (dirValidator(str)) dirs.Push(str);
  171. foreach (string file in files)
  172. {
  173. FileInfo nextValue;
  174. try
  175. {
  176. nextValue = new FileInfo(file);
  177. }
  178. catch (FileNotFoundException)
  179. { continue; }
  180. yield return nextValue;
  181. }
  182. }
  183. }
  184. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  185. private static extern IntPtr AddDllDirectory(string lpPathName);
  186. [Flags]
  187. [SuppressMessage("ReSharper", "InconsistentNaming")]
  188. [SuppressMessage("ReSharper", "UnusedMember.Local")]
  189. private enum LoadLibraryFlags : uint
  190. {
  191. None = 0,
  192. LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200,
  193. LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000,
  194. LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800,
  195. LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400,
  196. }
  197. [DllImport("kernel32.dll", SetLastError = true)]
  198. private static extern bool SetDefaultDllDirectories(LoadLibraryFlags dwFlags);
  199. }
  200. }