FastNativeDetour.cs 4.7 KB

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