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.

229 lines
8.8 KiB

  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. if (!pathEnvironmentVariable.Contains(path))
  69. {
  70. Environment.SetEnvironmentVariable("Path", pathEnvironmentVariable + Path.PathSeparator + path);
  71. }
  72. }
  73. if (Directory.Exists(NativeLibraryPath))
  74. {
  75. AddDir(NativeLibraryPath);
  76. _ = TraverseTree(NativeLibraryPath, dir =>
  77. { // this is a terrible hack for iterating directories
  78. AddDir(dir); return true;
  79. }).All(f => true); // force it to iterate all
  80. }
  81. //var unityData = Directory.EnumerateDirectories(Environment.CurrentDirectory, "*_Data").First();
  82. //AddDir(Path.Combine(unityData, "Plugins"));
  83. }
  84. }
  85. public static Assembly? AssemblyLibLoader(object source, ResolveEventArgs e)
  86. {
  87. var asmName = new AssemblyName(e.Name);
  88. return LoadLibrary(asmName);
  89. }
  90. internal static Assembly? LoadLibrary(AssemblyName asmName)
  91. {
  92. Log(Logger.Level.Debug, $"Resolving library {asmName}");
  93. SetupAssemblyFilenames();
  94. var testFile = $"{asmName.Name}.dll";
  95. Log(Logger.Level.Debug, $"Looking for file {asmName.Name}.dll");
  96. if (FilenameLocations.TryGetValue(testFile, out var path))
  97. {
  98. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  99. return LoadSafe(path);
  100. }
  101. else if (FilenameLocations.TryGetValue(testFile = $"{asmName.Name}.{asmName.Version}.dll", out path))
  102. {
  103. Log(Logger.Level.Debug, $"Found file {testFile} as {path}");
  104. Log(Logger.Level.Warning, $"File {testFile} should be renamed to just {asmName.Name}.dll");
  105. return LoadSafe(path);
  106. }
  107. Log(Logger.Level.Critical, $"No library {asmName} found");
  108. return null;
  109. }
  110. private static Assembly? LoadSafe(string path)
  111. {
  112. if (!File.Exists(path))
  113. {
  114. Log(Logger.Level.Critical, $"{path} no longer exists!");
  115. return null;
  116. }
  117. if (AntiMalwareEngine.IsInitialized)
  118. {
  119. var result = AntiMalwareEngine.Engine.ScanFile(new FileInfo(path));
  120. if (result is ScanResult.Detected)
  121. {
  122. Log(Logger.Level.Error, $"Scan of '{path}' found malware; not loading");
  123. return null;
  124. }
  125. if (!SelfConfig.AntiMalware_.RunPartialThreatCode_ && result is not ScanResult.KnownSafe and not ScanResult.NotDetected)
  126. {
  127. Log(Logger.Level.Error, $"Scan of '{path}' found partial threat; not loading. To load this, enable AntiMalware.RunPartialThreatCode in the config.");
  128. return null;
  129. }
  130. }
  131. return Assembly.LoadFrom(path);
  132. }
  133. internal static void Log(Logger.Level lvl, string message)
  134. { // multiple proxy methods to delay loading of assemblies until it's done
  135. if (Logger.LogCreated)
  136. AssemblyLibLoaderCallLogger(lvl, message);
  137. else
  138. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  139. Console.WriteLine($"[{lvl}] {message}");
  140. }
  141. internal static void Log(Logger.Level lvl, Exception message)
  142. { // multiple proxy methods to delay loading of assemblies until it's done
  143. if (Logger.LogCreated)
  144. AssemblyLibLoaderCallLogger(lvl, message);
  145. else
  146. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  147. Console.WriteLine($"[{lvl}] {message}");
  148. }
  149. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, string message) => Logger.libLoader.Log(lvl, message);
  150. private static void AssemblyLibLoaderCallLogger(Logger.Level lvl, Exception message) => Logger.libLoader.Log(lvl, message);
  151. // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-iterate-through-a-directory-tree
  152. private static IEnumerable<FileInfo> TraverseTree(string root, Func<string, bool>? dirValidator = null)
  153. {
  154. if (dirValidator == null) dirValidator = s => true;
  155. var dirs = new Stack<string>(32);
  156. if (!Directory.Exists(root))
  157. throw new ArgumentException("Directory does not exist", nameof(root));
  158. dirs.Push(root);
  159. while (dirs.Count > 0)
  160. {
  161. string currentDir = dirs.Pop();
  162. string[] subDirs;
  163. try
  164. {
  165. subDirs = Directory.GetDirectories(currentDir);
  166. }
  167. catch (UnauthorizedAccessException)
  168. { continue; }
  169. catch (DirectoryNotFoundException)
  170. { continue; }
  171. string[] files;
  172. try
  173. {
  174. files = Directory.GetFiles(currentDir);
  175. }
  176. catch (UnauthorizedAccessException)
  177. { continue; }
  178. catch (DirectoryNotFoundException)
  179. { continue; }
  180. foreach (string str in subDirs)
  181. if (dirValidator(str)) dirs.Push(str);
  182. foreach (string file in files)
  183. {
  184. FileInfo nextValue;
  185. try
  186. {
  187. nextValue = new FileInfo(file);
  188. }
  189. catch (FileNotFoundException)
  190. { continue; }
  191. yield return nextValue;
  192. }
  193. }
  194. }
  195. }
  196. }