DetourGenerator.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using BepInEx.IL2CPP.Allocator;
  5. using BepInEx.Logging;
  6. using Iced.Intel;
  7. using MonoMod.RuntimeDetour;
  8. namespace BepInEx.IL2CPP
  9. {
  10. public static class DetourGenerator
  11. {
  12. private static ManualLogSource logger = Logger.CreateLogSource("DetourGen");
  13. public static void Disassemble(ManualLogSource logSource, IntPtr memoryPtr, int size)
  14. {
  15. byte[] data = new byte[size];
  16. Marshal.Copy(memoryPtr, data, 0, size);
  17. var formatter = new NasmFormatter();
  18. var output = new StringOutput();
  19. var codeReader = new ByteArrayCodeReader(data);
  20. var decoder = Decoder.Create(64, codeReader);
  21. decoder.IP = (ulong)memoryPtr.ToInt64();
  22. while (codeReader.CanReadByte)
  23. {
  24. decoder.Decode(out var instr);
  25. formatter.Format(instr, output);
  26. logSource.LogDebug($"{instr.IP:X16} {output.ToStringAndReset()}");
  27. if (instr.Code == Code.Jmp_rm64 && instr.Immediate32 == 0) // && instr.IsIPRelativeMemoryOperand && instr.IPRelativeMemoryAddress = 6
  28. {
  29. byte[] address = new byte[8];
  30. for (int i = 0; i < 8; i++)
  31. address[i] = (byte)codeReader.ReadByte();
  32. logSource.LogDebug($"{(instr.IP + (ulong)instr.Length):X16} db 0x{BitConverter.ToUInt64(address, 0):X16}");
  33. decoder.IP += 8;
  34. }
  35. }
  36. }
  37. public static int GetDetourLength(Architecture arch)
  38. => arch == Architecture.X64 ? 14 : 5;
  39. /// <summary>
  40. /// Writes a detour on <see cref="functionPtr"/> to redirect to <see cref="detourPtr"/>.
  41. /// </summary>
  42. /// <param name="functionPtr">The pointer to the function to apply the detour to.</param>
  43. /// <param name="detourPtr">The pointer to the function to redirect to.</param>
  44. /// <param name="architecture">The architecture of the current platform.</param>
  45. /// <param name="minimumLength">The minimum amount of length that the detour should consume. If the generated redirect is smaller than this, the remaining space is padded with NOPs.</param>
  46. public static void ApplyDetour(IntPtr functionPtr, IntPtr detourPtr, Architecture architecture, int minimumLength = 0)
  47. {
  48. byte[] jmp = GenerateAbsoluteJump(detourPtr, functionPtr, architecture);
  49. Marshal.Copy(jmp, 0, functionPtr, jmp.Length);
  50. // Fill remaining space with NOP instructions
  51. for (int i = jmp.Length; i < minimumLength; i++)
  52. Marshal.WriteByte(functionPtr + i, 0x90);
  53. }
  54. public static IntPtr CreateTrampolineFromFunction(IntPtr originalFuncPointer, out int trampolineLength, out int jmpLength)
  55. {
  56. byte[] instructionBuffer = new byte[32];
  57. Marshal.Copy(originalFuncPointer, instructionBuffer, 0, 32);
  58. var trampolinePtr = PageAllocator.Instance.Allocate(originalFuncPointer);
  59. DetourHelper.Native.MakeWritable(trampolinePtr, PageAllocator.PAGE_SIZE);
  60. var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
  61. int minimumTrampolineLength = GetDetourLength(arch);
  62. CreateTrampolineFromFunction(instructionBuffer, originalFuncPointer, trampolinePtr, minimumTrampolineLength, arch, out trampolineLength, out jmpLength);
  63. DetourHelper.Native.MakeExecutable(originalFuncPointer, 32);
  64. DetourHelper.Native.MakeExecutable(trampolinePtr, PageAllocator.PAGE_SIZE);
  65. return trampolinePtr;
  66. }
  67. /// <summary>
  68. /// Reads assembly from <see cref="functionPtr"/> (at least <see cref="minimumTrampolineLength"/> bytes), and writes it to <see cref="trampolinePtr"/> plus a jmp to continue execution.
  69. /// </summary>
  70. /// <param name="instructionBuffer">The buffer to copy assembly from.</param>
  71. /// <param name="functionPtr">The pointer to the function to copy assembly from.</param>
  72. /// <param name="trampolinePtr">The pointer to write the trampoline assembly to.</param>
  73. /// <param name="arch">The architecture of the current platform.</param>
  74. /// <param name="minimumTrampolineLength">Copies at least this many bytes of assembly from <see cref="functionPtr"/>.</param>
  75. /// <param name="trampolineLength">Returns the total length of the trampoline, in bytes.</param>
  76. /// <param name="jmpLength">Returns the length of the jmp at the end of the trampoline, in bytes.</param>
  77. public static void CreateTrampolineFromFunction(byte[] instructionBuffer, IntPtr functionPtr, IntPtr trampolinePtr, int minimumTrampolineLength, Architecture arch, out int trampolineLength, out int jmpLength)
  78. {
  79. // Decode original function up until we go past the needed bytes to write the jump to patchedFunctionPtr
  80. var codeReader = new ByteArrayCodeReader(instructionBuffer);
  81. var decoder = Decoder.Create(arch == Architecture.X64 ? 64 : 32, codeReader);
  82. decoder.IP = (ulong)functionPtr.ToInt64();
  83. uint totalBytes = 0;
  84. var origInstructions = new InstructionList();
  85. var readOverflowArea = false;
  86. while (codeReader.CanReadByte)
  87. {
  88. decoder.Decode(out var instr);
  89. origInstructions.Add(instr);
  90. totalBytes += (uint)instr.Length;
  91. if (instr.Code == Code.INVALID)
  92. throw new Exception("Found garbage");
  93. if (totalBytes >= minimumTrampolineLength)
  94. break;
  95. if (readOverflowArea)
  96. {
  97. if (instr.Mnemonic != Mnemonic.Int && instr.Mnemonic != Mnemonic.Nop)
  98. throw new Exception("Function is too short to hook");
  99. continue;
  100. }
  101. switch (instr.FlowControl)
  102. {
  103. case FlowControl.Next:
  104. break;
  105. // Interrupts are usually used for aligning
  106. case FlowControl.Interrupt:// eg. int n
  107. break;
  108. // Handled by BlockEncoder in most cases
  109. case FlowControl.UnconditionalBranch:
  110. case FlowControl.IndirectBranch: // eg. jmp reg/mem
  111. case FlowControl.ConditionalBranch: // eg. je, jno, etc
  112. break;
  113. case FlowControl.Return: // eg. ret
  114. // There is a possibility of an overflow area, attempt to allocate trampoline onto it
  115. readOverflowArea = true;
  116. break;
  117. case FlowControl.Call:// eg. call method
  118. case FlowControl.IndirectCall:// eg. call reg/mem
  119. case FlowControl.XbeginXabortXend:
  120. case FlowControl.Exception:// eg. ud0
  121. default:
  122. throw new Exception("Not supported yet - " + instr.FlowControl);
  123. }
  124. }
  125. if (totalBytes < minimumTrampolineLength)
  126. throw new Exception("Not enough bytes!");
  127. if (origInstructions.Count == 0)
  128. throw new Exception("Not enough instructions!");
  129. ref readonly var lastInstr = ref origInstructions[origInstructions.Count - 1];
  130. if (lastInstr.FlowControl != FlowControl.Return)
  131. {
  132. Instruction detourInstruction;
  133. if (arch == Architecture.X64)
  134. {
  135. detourInstruction = Instruction.CreateBranch(Code.Jmp_rel32_64, lastInstr.NextIP);
  136. }
  137. else
  138. {
  139. detourInstruction = Instruction.CreateBranch(Code.Jmp_rel32_32, lastInstr.NextIP);
  140. }
  141. origInstructions.Add(detourInstruction);
  142. }
  143. // Generate trampoline from instruction list
  144. var codeWriter = new CodeWriterImpl();
  145. ulong relocatedBaseAddress = (ulong)trampolinePtr;
  146. var block = new InstructionBlock(codeWriter, origInstructions, relocatedBaseAddress);
  147. bool success = BlockEncoder.TryEncode(decoder.Bitness, block, out var errorMessage, out var result);
  148. if (!success)
  149. {
  150. throw new Exception(errorMessage);
  151. }
  152. // Write generated trampoline
  153. var newCode = codeWriter.ToArray();
  154. Marshal.Copy(newCode, 0, trampolinePtr, newCode.Length);
  155. jmpLength = newCode.Length - (int)totalBytes;
  156. trampolineLength = newCode.Length;
  157. }
  158. public static byte[] GenerateAbsoluteJump(IntPtr targetAddress, IntPtr currentAddress, Architecture arch)
  159. {
  160. byte[] jmpBytes;
  161. if (arch == Architecture.X64)
  162. {
  163. jmpBytes = new byte[]
  164. {
  165. 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, // FF25 00000000: JMP [RIP+6]
  166. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Absolute destination address
  167. };
  168. Array.Copy(BitConverter.GetBytes(targetAddress.ToInt64()), 0, jmpBytes, 6, 8);
  169. }
  170. else
  171. {
  172. jmpBytes = new byte[]
  173. {
  174. 0xE9, // E9: JMP rel destination
  175. 0x00, 0x00, 0x00, 0x00 // Relative destination address
  176. };
  177. Array.Copy(BitConverter.GetBytes(targetAddress.ToInt32() - (currentAddress.ToInt32() + 5)), 0, jmpBytes, 1, 4);
  178. }
  179. return jmpBytes;
  180. }
  181. private sealed class CodeWriterImpl : CodeWriter
  182. {
  183. readonly List<byte> allBytes = new List<byte>();
  184. public override void WriteByte(byte value) => allBytes.Add(value);
  185. public byte[] ToArray() => allBytes.ToArray();
  186. }
  187. }
  188. }