DetourGenerator.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. while (codeReader.CanReadByte)
  86. {
  87. decoder.Decode(out var instr);
  88. origInstructions.Add(instr);
  89. totalBytes += (uint)instr.Length;
  90. if (instr.Code == Code.INVALID)
  91. throw new Exception("Found garbage");
  92. if (totalBytes >= minimumTrampolineLength)
  93. break;
  94. switch (instr.FlowControl)
  95. {
  96. case FlowControl.Next:
  97. break;
  98. case FlowControl.Interrupt:// eg. int n
  99. break;
  100. // Handled by BlockEncoder in most cases
  101. case FlowControl.UnconditionalBranch:
  102. case FlowControl.IndirectBranch:// eg. jmp reg/mem
  103. case FlowControl.ConditionalBranch:// eg. je, jno, etc
  104. break;
  105. case FlowControl.Return:// eg. ret
  106. case FlowControl.Call:// eg. call method
  107. case FlowControl.IndirectCall:// eg. call reg/mem
  108. case FlowControl.XbeginXabortXend:
  109. case FlowControl.Exception:// eg. ud0
  110. default:
  111. throw new Exception("Not supported by this simple example - " + instr.FlowControl);
  112. }
  113. }
  114. if (totalBytes < minimumTrampolineLength)
  115. throw new Exception("Not enough bytes!");
  116. if (origInstructions.Count == 0)
  117. throw new Exception("Not enough instructions!");
  118. ref readonly var lastInstr = ref origInstructions[origInstructions.Count - 1];
  119. if (lastInstr.FlowControl != FlowControl.Return)
  120. {
  121. Instruction detourInstruction;
  122. if (arch == Architecture.X64)
  123. {
  124. detourInstruction = Instruction.CreateBranch(Code.Jmp_rel32_64, lastInstr.NextIP);
  125. }
  126. else
  127. {
  128. detourInstruction = Instruction.CreateBranch(Code.Jmp_rel32_32, lastInstr.NextIP);
  129. }
  130. origInstructions.Add(detourInstruction);
  131. }
  132. // Generate trampoline from instruction list
  133. var codeWriter = new CodeWriterImpl();
  134. ulong relocatedBaseAddress = (ulong)trampolinePtr;
  135. var block = new InstructionBlock(codeWriter, origInstructions, relocatedBaseAddress);
  136. bool success = BlockEncoder.TryEncode(decoder.Bitness, block, out var errorMessage, out var result);
  137. if (!success)
  138. {
  139. throw new Exception(errorMessage);
  140. }
  141. // Write generated trampoline
  142. var newCode = codeWriter.ToArray();
  143. Marshal.Copy(newCode, 0, trampolinePtr, newCode.Length);
  144. jmpLength = newCode.Length - (int)totalBytes;
  145. trampolineLength = newCode.Length;
  146. }
  147. public static byte[] GenerateAbsoluteJump(IntPtr targetAddress, IntPtr currentAddress, Architecture arch)
  148. {
  149. byte[] jmpBytes;
  150. if (arch == Architecture.X64)
  151. {
  152. jmpBytes = new byte[]
  153. {
  154. 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, // FF25 00000000: JMP [RIP+6]
  155. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Absolute destination address
  156. };
  157. Array.Copy(BitConverter.GetBytes(targetAddress.ToInt64()), 0, jmpBytes, 6, 8);
  158. }
  159. else
  160. {
  161. jmpBytes = new byte[]
  162. {
  163. 0xE9, // E9: JMP rel destination
  164. 0x00, 0x00, 0x00, 0x00 // Relative destination address
  165. };
  166. Array.Copy(BitConverter.GetBytes(targetAddress.ToInt32() - (currentAddress.ToInt32() + 5)), 0, jmpBytes, 1, 4);
  167. }
  168. return jmpBytes;
  169. }
  170. private sealed class CodeWriterImpl : CodeWriter
  171. {
  172. readonly List<byte> allBytes = new List<byte>();
  173. public override void WriteByte(byte value) => allBytes.Add(value);
  174. public byte[] ToArray() => allBytes.ToArray();
  175. }
  176. }
  177. }