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.

81 lines
2.7 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. using IPA.Loader;
  2. using IPA.Logging;
  3. using System;
  4. using System.IO;
  5. using System.Reflection;
  6. using System.Runtime.InteropServices;
  7. using UnityEngine;
  8. using static IPA.Logging.Logger;
  9. namespace IPA.Injector
  10. {
  11. public static class Injector
  12. {
  13. private static bool injected = false;
  14. public static void Inject()
  15. {
  16. if (!injected)
  17. {
  18. injected = true;
  19. #region Add Library load locations
  20. AppDomain.CurrentDomain.AssemblyResolve += AssemblyLibLoader;
  21. try
  22. {
  23. if (!SetDllDirectory(Path.Combine(Environment.CurrentDirectory, "Libs", "Native")))
  24. {
  25. libLoader.Warn("Unable to add native library path to load path");
  26. }
  27. }
  28. catch (Exception) { }
  29. #endregion
  30. var bootstrapper = new GameObject("Bootstrapper").AddComponent<Bootstrapper>();
  31. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  32. }
  33. }
  34. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  35. [return: MarshalAs(UnmanagedType.Bool)]
  36. static extern bool SetDllDirectory(string lpPathName);
  37. #region Managed library loader
  38. private static string libsDir;
  39. private static Assembly AssemblyLibLoader(object source, ResolveEventArgs e)
  40. {
  41. if (libsDir == null)
  42. libsDir = Path.Combine(Environment.CurrentDirectory, "Libs");
  43. var asmName = new AssemblyName(e.Name);
  44. Log(Level.Debug, $"Resolving library {asmName}");
  45. var testFilen = Path.Combine(libsDir, $"{asmName.Name}.{asmName.Version}.dll");
  46. Log(Level.Debug, $"Looking for file {testFilen}");
  47. if (File.Exists(testFilen))
  48. return Assembly.LoadFile(testFilen);
  49. Log(Level.Critical, $"Could not load library {asmName}");
  50. return null;
  51. }
  52. private static void Log(Level lvl, string message)
  53. { // multiple proxy methods to delay loading of assemblies until it's done
  54. if (LogCreated)
  55. AssemblyLibLoaderCallLogger(lvl, message);
  56. else
  57. if (((byte)lvl & (byte)StandardLogger.PrintFilter) != 0)
  58. Console.WriteLine($"[{lvl}] {message}");
  59. }
  60. private static void AssemblyLibLoaderCallLogger(Level lvl, string message)
  61. {
  62. libLoader.Log(lvl, message);
  63. }
  64. #endregion
  65. private static void Bootstrapper_Destroyed()
  66. {
  67. PluginComponent.Create();
  68. }
  69. }
  70. }