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.

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