FastNativeDetour.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 OriginalFunctionPtr { get; protected set; }
  15. public IntPtr DetourFunctionPtr { get; protected set; }
  16. public IntPtr TrampolinePtr { get; protected set; } = IntPtr.Zero;
  17. public int TrampolineSize { get; protected set; } = 0;
  18. protected int TrampolineJmpSize { get; set; } = 0;
  19. protected MethodInfo TrampolineMethod { get; set; }
  20. public FastNativeDetour(IntPtr originalFunctionPtr, IntPtr detourFunctionPtr)
  21. {
  22. OriginalFunctionPtr = originalFunctionPtr;
  23. DetourFunctionPtr = detourFunctionPtr;
  24. // TODO: This may not be safe during undo if the method is smaller than 20 bytes
  25. BackupBytes = new byte[20];
  26. Marshal.Copy(originalFunctionPtr, BackupBytes, 0, 20);
  27. }
  28. public void Apply()
  29. {
  30. Apply(null);
  31. }
  32. public void Apply(ManualLogSource debuggerLogSource)
  33. {
  34. if (IsApplied)
  35. return;
  36. DetourHelper.Native.MakeWritable(OriginalFunctionPtr, 32);
  37. if (debuggerLogSource != null)
  38. {
  39. debuggerLogSource.LogDebug($"Detouring 0x{OriginalFunctionPtr.ToString("X")} -> 0x{OriginalFunctionPtr.ToString("X")}");
  40. debuggerLogSource.LogDebug("Original (32) asm");
  41. DetourGenerator.Disassemble(debuggerLogSource, OriginalFunctionPtr, 32);
  42. }
  43. var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
  44. GenerateTrampolineInner(out int trampolineLength, out int jmpLength);
  45. debuggerLogSource?.LogDebug($"Cleared function length: {trampolineLength} - {jmpLength} = {trampolineLength - jmpLength}");
  46. debuggerLogSource?.LogDebug($"Trampoline allocation: 0x{TrampolinePtr.ToString("X")}");
  47. DetourGenerator.ApplyDetour(OriginalFunctionPtr, DetourFunctionPtr, arch, trampolineLength - jmpLength);
  48. if (debuggerLogSource != null)
  49. {
  50. debuggerLogSource.LogDebug("Modified (32) asm");
  51. DetourGenerator.Disassemble(debuggerLogSource, OriginalFunctionPtr, 32);
  52. debuggerLogSource.LogDebug($"Trampoline ({trampolineLength}) asm");
  53. DetourGenerator.Disassemble(debuggerLogSource, TrampolinePtr, trampolineLength);
  54. }
  55. DetourHelper.Native.MakeExecutable(OriginalFunctionPtr, 32);
  56. IsApplied = true;
  57. }
  58. private void GenerateTrampolineInner(out int trampolineLength, out int jmpLength)
  59. {
  60. if (TrampolinePtr != IntPtr.Zero)
  61. {
  62. trampolineLength = TrampolineSize;
  63. jmpLength = TrampolineJmpSize;
  64. return;
  65. }
  66. byte[] instructionBuffer = new byte[32];
  67. Marshal.Copy(OriginalFunctionPtr, instructionBuffer, 0, 32);
  68. var trampolineAlloc = DetourHelper.Native.MemAlloc(80);
  69. DetourHelper.Native.MakeWritable(trampolineAlloc, 80);
  70. var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
  71. DetourGenerator.CreateTrampolineFromFunction(instructionBuffer, OriginalFunctionPtr, trampolineAlloc,
  72. DetourGenerator.GetDetourLength(arch), arch, out trampolineLength, out jmpLength);
  73. DetourHelper.Native.MakeExecutable(trampolineAlloc, 80);
  74. TrampolinePtr = trampolineAlloc;
  75. TrampolineSize = trampolineLength;
  76. TrampolineJmpSize = jmpLength;
  77. }
  78. public void Undo()
  79. {
  80. if (!IsApplied)
  81. return;
  82. Marshal.Copy(BackupBytes, 0, OriginalFunctionPtr, BackupBytes.Length);
  83. DetourHelper.Native.MemFree(TrampolinePtr);
  84. TrampolinePtr = IntPtr.Zero;
  85. TrampolineSize = 0;
  86. IsApplied = false;
  87. }
  88. public void Free()
  89. {
  90. IsValid = false;
  91. }
  92. public MethodBase GenerateTrampoline(MethodBase signature = null)
  93. {
  94. if (TrampolineMethod == null)
  95. {
  96. // Generate trampoline without applying the detour
  97. GenerateTrampolineInner(out _, out _);
  98. if (TrampolinePtr == IntPtr.Zero)
  99. throw new InvalidOperationException("Trampoline pointer is not available");
  100. TrampolineMethod = DetourHelper.GenerateNativeProxy(TrampolinePtr, signature);
  101. }
  102. return TrampolineMethod;
  103. }
  104. public T GenerateTrampoline<T>() where T : Delegate
  105. {
  106. if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
  107. throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
  108. return GenerateTrampoline(typeof(T).GetMethod("Invoke")).CreateDelegate(typeof(T)) as T;
  109. }
  110. public void Dispose()
  111. {
  112. if (!IsValid)
  113. return;
  114. Undo();
  115. Free();
  116. }
  117. }
  118. }