FastNativeDetour.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. private static ManualLogSource logger = Logger.CreateLogSource("FastNativeDetour");
  29. public void Apply()
  30. {
  31. Apply(null);
  32. }
  33. public void Apply(ManualLogSource debuggerLogSource)
  34. {
  35. if (IsApplied)
  36. return;
  37. DetourHelper.Native.MakeWritable(OriginalFunctionPtr, 32);
  38. if (debuggerLogSource != null)
  39. {
  40. debuggerLogSource.LogDebug($"Detouring 0x{OriginalFunctionPtr.ToString("X")} -> 0x{DetourFunctionPtr.ToString("X")}");
  41. debuggerLogSource.LogDebug("Original (32) asm");
  42. DetourGenerator.Disassemble(debuggerLogSource, OriginalFunctionPtr, 32);
  43. }
  44. var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
  45. GenerateTrampolineInner(out int trampolineLength, out int jmpLength);
  46. DetourGenerator.ApplyDetour(OriginalFunctionPtr, DetourFunctionPtr, arch, trampolineLength - jmpLength);
  47. if (debuggerLogSource != null)
  48. {
  49. debuggerLogSource.LogDebug($"Trampoline allocation: 0x{TrampolinePtr.ToString("X")}");
  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 = PageAllocator.Instance.Allocate(OriginalFunctionPtr);
  69. logger.LogDebug($"Original: {OriginalFunctionPtr.ToInt64():X}, Trampoline: {trampolineAlloc.ToInt64():X}, diff: {Math.Abs(OriginalFunctionPtr.ToInt64() - trampolineAlloc.ToInt64()):X}; is within +-1GB range: {PageAllocator.IsInRelJmpRange(OriginalFunctionPtr, trampolineAlloc)}");
  70. DetourHelper.Native.MakeWritable(trampolineAlloc, PageAllocator.PAGE_SIZE);
  71. var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
  72. DetourGenerator.CreateTrampolineFromFunction(instructionBuffer, OriginalFunctionPtr, trampolineAlloc,
  73. DetourGenerator.GetDetourLength(arch), arch, out trampolineLength, out jmpLength);
  74. DetourHelper.Native.MakeExecutable(trampolineAlloc, PageAllocator.PAGE_SIZE);
  75. TrampolinePtr = trampolineAlloc;
  76. TrampolineSize = trampolineLength;
  77. TrampolineJmpSize = jmpLength;
  78. }
  79. public void Undo()
  80. {
  81. if (!IsApplied)
  82. return;
  83. Marshal.Copy(BackupBytes, 0, OriginalFunctionPtr, BackupBytes.Length);
  84. PageAllocator.Instance.Free(TrampolinePtr);
  85. TrampolinePtr = IntPtr.Zero;
  86. TrampolineSize = 0;
  87. IsApplied = false;
  88. }
  89. public void Free()
  90. {
  91. IsValid = false;
  92. }
  93. public MethodBase GenerateTrampoline(MethodBase signature = null)
  94. {
  95. if (TrampolineMethod == null)
  96. {
  97. // Generate trampoline without applying the detour
  98. GenerateTrampolineInner(out _, out _);
  99. if (TrampolinePtr == IntPtr.Zero)
  100. throw new InvalidOperationException("Trampoline pointer is not available");
  101. TrampolineMethod = DetourHelper.GenerateNativeProxy(TrampolinePtr, signature);
  102. }
  103. return TrampolineMethod;
  104. }
  105. public T GenerateTrampoline<T>() where T : Delegate
  106. {
  107. if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
  108. throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
  109. return GenerateTrampoline(typeof(T).GetMethod("Invoke")).CreateDelegate(typeof(T)) as T;
  110. }
  111. public void Dispose()
  112. {
  113. if (!IsValid)
  114. return;
  115. Undo();
  116. Free();
  117. }
  118. }
  119. }