DetourGenerator.cs 7.8 KB

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