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.

234 lines
8.8 KiB

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