Entrypoint.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace BepInEx.Preloader
  6. {
  7. internal static class PreloaderRunner
  8. {
  9. public static void PreloaderMain(string[] args)
  10. {
  11. string bepinPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH)));
  12. Paths.SetExecutablePath(args[0], bepinPath, EnvVars.DOORSTOP_MANAGED_FOLDER_DIR);
  13. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  14. Preloader.Run();
  15. }
  16. private static Assembly LocalResolve(object sender, ResolveEventArgs args)
  17. {
  18. var assemblyName = new AssemblyName(args.Name);
  19. var foundAssembly = AppDomain.CurrentDomain.GetAssemblies()
  20. .FirstOrDefault(x => x.GetName().Name == assemblyName.Name);
  21. if (foundAssembly != null)
  22. return foundAssembly;
  23. if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly)
  24. || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly)
  25. || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly))
  26. return foundAssembly;
  27. return null;
  28. }
  29. }
  30. internal static class Entrypoint
  31. {
  32. private static string preloaderPath;
  33. /// <summary>
  34. /// The main entrypoint of BepInEx, called from Doorstop.
  35. /// </summary>
  36. /// <param name="args">
  37. /// The arguments passed in from Doorstop. First argument is the path of the currently executing
  38. /// process.
  39. /// </param>
  40. public static void Main(string[] args)
  41. {
  42. EnvVars.LoadVars();
  43. // Get the path of this DLL via Doorstop env var because Assembly.Location mangles non-ASCII characters on some versions of Mono for unknown reasons
  44. preloaderPath = Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH));
  45. AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
  46. // We have to use reflection and a separate startup class in order to not trigger premature assembly resolving
  47. typeof(Entrypoint).Assembly.GetType($"BepInEx.Preloader.{nameof(PreloaderRunner)}")
  48. ?.GetMethod(nameof(PreloaderRunner.PreloaderMain))
  49. ?.Invoke(null, new object[] { args });
  50. AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
  51. }
  52. private static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
  53. {
  54. var name = new AssemblyName(args.Name);
  55. try
  56. {
  57. return Assembly.LoadFile(Path.Combine(preloaderPath, $"{name.Name}.dll"));
  58. }
  59. catch (Exception)
  60. {
  61. return null;
  62. }
  63. }
  64. }
  65. }