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.

218 lines
8.3 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. }
  78. }
  79. public static Assembly AssemblyLibLoader(object source, ResolveEventArgs e)
  80. {
  81. var asmName = new AssemblyName(e.Name);
  82. return LoadLibrary(asmName);
  83. }
  84. internal static Assembly LoadLibrary(AssemblyName asmName)
  85. {
  86. Log(Logger.Level.Debug, $"Resolving library {asmName}");
  87. SetupAssemblyFilenames();
  88. var testFile = $"{asmName.Name}.{asmName.Version}.dll";
  89. Log(Logger.Level.Debug, $"Looking for file {testFile}");
  90. if (FilenameLocations.TryGetValue(testFile, out var path))
  91. {
  92. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  93. if (File.Exists(path))
  94. return Assembly.LoadFrom(path);
  95. Log(Logger.Level.Critical, $"but {path} no longer exists!");
  96. }
  97. else if (FilenameLocations.TryGetValue(testFile = $"{asmName.Name}.dll", out path))
  98. {
  99. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  100. if (File.Exists(path))
  101. return Assembly.LoadFrom(path);
  102. Log(Logger.Level.Critical, $"but {path} no longer exists!");
  103. }
  104. Log(Logger.Level.Critical, $"No library {asmName} found");
  105. return null;
  106. }
  107. internal static void Log(Logger.Level lvl, string message)
  108. { // multiple proxy methods to delay loading of assemblies until it's done
  109. if (Logger.LogCreated)
  110. AssemblyLibLoaderCallLogger(lvl, message);
  111. else
  112. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  113. Console.WriteLine($"[{lvl}] {message}");
  114. }
  115. internal static void Log(Logger.Level lvl, Exception message)
  116. { // multiple proxy methods to delay loading of assemblies until it's done
  117. if (Logger.LogCreated)
  118. AssemblyLibLoaderCallLogger(lvl, message);
  119. else
  120. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  121. Console.WriteLine($"[{lvl}] {message}");
  122. }
  123. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, string message) => Logger.libLoader.Log(lvl, message);
  124. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, Exception message) => Logger.libLoader.Log(lvl, message);
  125. // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-iterate-through-a-directory-tree
  126. private static IEnumerable<FileInfo> TraverseTree(string root, Func<string, bool> dirValidator = null)
  127. {
  128. if (dirValidator == null) dirValidator = s => true;
  129. Stack<string> dirs = new Stack<string>(32);
  130. if (!Directory.Exists(root))
  131. throw new ArgumentException();
  132. dirs.Push(root);
  133. while (dirs.Count > 0)
  134. {
  135. string currentDir = dirs.Pop();
  136. string[] subDirs;
  137. try
  138. {
  139. subDirs = Directory.GetDirectories(currentDir);
  140. }
  141. catch (UnauthorizedAccessException)
  142. { continue; }
  143. catch (DirectoryNotFoundException)
  144. { continue; }
  145. string[] files;
  146. try
  147. {
  148. files = Directory.GetFiles(currentDir);
  149. }
  150. catch (UnauthorizedAccessException)
  151. { continue; }
  152. catch (DirectoryNotFoundException)
  153. { continue; }
  154. foreach (string str in subDirs)
  155. if (dirValidator(str)) dirs.Push(str);
  156. foreach (string file in files)
  157. {
  158. FileInfo nextValue;
  159. try
  160. {
  161. nextValue = new FileInfo(file);
  162. }
  163. catch (FileNotFoundException)
  164. { continue; }
  165. yield return nextValue;
  166. }
  167. }
  168. }
  169. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  170. private static extern IntPtr AddDllDirectory(string lpPathName);
  171. [Flags]
  172. [SuppressMessage("ReSharper", "InconsistentNaming")]
  173. [SuppressMessage("ReSharper", "UnusedMember.Local")]
  174. private enum LoadLibraryFlags : uint
  175. {
  176. None = 0,
  177. LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200,
  178. LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000,
  179. LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800,
  180. LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400,
  181. }
  182. [DllImport("kernel32.dll", SetLastError = true)]
  183. private static extern bool SetDefaultDllDirectories(LoadLibraryFlags dwFlags);
  184. }
  185. }