FastNativeDetour.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Reflection;
  3. using System.Runtime.InteropServices;
  4. using BepInEx.Logging;
  5. using MonoMod.RuntimeDetour;
  6. using MonoMod.Utils;
  7. namespace BepInEx.IL2CPP.Hook
  8. {
  9. public class FastNativeDetour : IDetour
  10. {
  11. protected byte[] BackupBytes { get; set; }
  12. public bool IsValid { get; protected set; } = true;
  13. public bool IsApplied { get; protected set; }
  14. public IntPtr OriginalFuncPtr { get; protected set; }
  15. public IntPtr DetourFuncPtr { get; protected set; }
  16. public IntPtr TrampolinePtr { get; protected set; } = IntPtr.Zero;
  17. public int TrampolineSize { get; protected set; } = 0;
  18. protected MethodInfo TrampolineMethod { get; set; }
  19. public FastNativeDetour(IntPtr originalFuncPtr, IntPtr detourFuncPtr)
  20. {
  21. OriginalFuncPtr = originalFuncPtr;
  22. DetourFuncPtr = detourFuncPtr;
  23. // TODO: This may not be safe during undo if the method is smaller than 20 bytes
  24. BackupBytes = new byte[20];
  25. Marshal.Copy(originalFuncPtr, BackupBytes, 0, 20);
  26. }
  27. public void Apply()
  28. {
  29. Apply(null);
  30. }
  31. public void Apply(ManualLogSource debuggerLogSource)
  32. {
  33. if (IsApplied)
  34. return;
  35. int trampolineLength;
  36. if (debuggerLogSource == null)
  37. TrampolinePtr = TrampolineGenerator.Generate(OriginalFuncPtr, DetourFuncPtr, out trampolineLength);
  38. else
  39. TrampolinePtr = TrampolineGenerator.Generate(debuggerLogSource, OriginalFuncPtr, DetourFuncPtr, out trampolineLength);
  40. TrampolineSize = trampolineLength;
  41. IsApplied = true;
  42. }
  43. public void Undo()
  44. {
  45. Marshal.Copy(BackupBytes, 0, OriginalFuncPtr, BackupBytes.Length);
  46. DetourHelper.Native.MemFree(TrampolinePtr);
  47. TrampolinePtr = IntPtr.Zero;
  48. TrampolineSize = 0;
  49. IsApplied = false;
  50. }
  51. public void Free()
  52. {
  53. IsValid = false;
  54. }
  55. public MethodBase GenerateTrampoline(MethodBase signature = null)
  56. {
  57. if (TrampolineMethod == null)
  58. {
  59. TrampolineMethod = DetourHelper.GenerateNativeProxy(TrampolinePtr, signature);
  60. }
  61. return TrampolineMethod;
  62. }
  63. public T GenerateTrampoline<T>() where T : Delegate
  64. {
  65. if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
  66. throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
  67. return GenerateTrampoline(typeof(T).GetMethod("Invoke")).CreateDelegate(typeof(T)) as T;
  68. }
  69. public void Dispose()
  70. {
  71. if (!IsValid)
  72. return;
  73. Undo();
  74. Free();
  75. }
  76. }
  77. }