Entrypoint.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. Paths.SetExecutablePath(args[0]);
  12. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  13. Preloader.Run();
  14. }
  15. private static Assembly LocalResolve(object sender, ResolveEventArgs args)
  16. {
  17. var assemblyName = new AssemblyName(args.Name);
  18. var foundAssembly = AppDomain.CurrentDomain.GetAssemblies()
  19. .FirstOrDefault(x => x.GetName().Name == assemblyName.Name);
  20. if (foundAssembly != null)
  21. return foundAssembly;
  22. if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly)
  23. || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly)
  24. || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly))
  25. return foundAssembly;
  26. return null;
  27. }
  28. }
  29. internal static class Entrypoint
  30. {
  31. private static string preloaderPath;
  32. /// <summary>
  33. /// The main entrypoint of BepInEx, called from Doorstop.
  34. /// </summary>
  35. /// <param name="args">
  36. /// The arguments passed in from Doorstop. First argument is the path of the currently executing
  37. /// process.
  38. /// </param>
  39. public static void Main(string[] args)
  40. {
  41. // 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
  42. preloaderPath = Path.GetDirectoryName(Path.GetFullPath(Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH")));
  43. AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
  44. // We have to use reflection and a separate startup class in order to not trigger premature assembly resolving
  45. typeof(Entrypoint).Assembly.GetType($"BepInEx.Preloader.{nameof(PreloaderRunner)}")
  46. ?.GetMethod(nameof(PreloaderRunner.PreloaderMain))
  47. ?.Invoke(null, new object[] { args });
  48. AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
  49. }
  50. private static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
  51. {
  52. var name = new AssemblyName(args.Name);
  53. try
  54. {
  55. return Assembly.LoadFile(Path.Combine(preloaderPath, $"{name.Name}.dll"));
  56. }
  57. catch (Exception)
  58. {
  59. return null;
  60. }
  61. }
  62. }
  63. }