DetourGenerator.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 = DetourHelper.Native.MemAlloc(80);
  58. DetourHelper.Native.MakeWritable(trampolinePtr, 80);
  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, (uint)trampolineLength);
  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. if (instr.IsIPRelativeMemoryOperand)
  88. {
  89. // TODO: AssemlberRegisters not needed, figure out what props to actually change
  90. // TODO: Check if it's better to use InternalOp0Kind (and other similar props) instead of normal ones
  91. // TODO: Probably need to check if the target is within the trampoline boundaries and thus shouldn't be fixed
  92. logger.LogDebug($"Got ptr with relative memory operand: {instr}");
  93. var addr = instr.IPRelativeMemoryAddress;
  94. logger.LogDebug($"Address: {addr:X}");
  95. instr.MemoryBase = Register.None;
  96. var op = AssemblerRegisters.__byte_ptr[addr].ToMemoryOperand(64);
  97. instr.Op0Kind = OpKind.Memory;
  98. instr.MemoryBase = op.Base;
  99. instr.MemoryIndex = op.Index;
  100. instr.MemoryIndexScale = op.Scale;
  101. instr.MemoryDisplSize = op.DisplSize;
  102. instr.MemoryDisplacement = (uint)op.Displacement;
  103. instr.IsBroadcast = op.IsBroadcast;
  104. instr.SegmentPrefix = op.SegmentPrefix;
  105. logger.LogDebug($"After edit: {instr}");
  106. }
  107. origInstructions.Add(instr);
  108. totalBytes += (uint)instr.Length;
  109. if (instr.Code == Code.INVALID)
  110. throw new Exception("Found garbage");
  111. if (totalBytes >= minimumTrampolineLength)
  112. break;
  113. switch (instr.FlowControl)
  114. {
  115. case FlowControl.Next:
  116. break;
  117. case FlowControl.UnconditionalBranch:
  118. if (instr.Op0Kind == OpKind.NearBranch64)
  119. {
  120. var target = instr.NearBranchTarget;
  121. }
  122. break;
  123. //goto default;
  124. case FlowControl.Interrupt:// eg. int n
  125. break;
  126. case FlowControl.IndirectBranch:// eg. jmp reg/mem
  127. case FlowControl.ConditionalBranch:// eg. je, jno, etc
  128. case FlowControl.Return:// eg. ret
  129. case FlowControl.Call:// eg. call method
  130. case FlowControl.IndirectCall:// eg. call reg/mem
  131. case FlowControl.XbeginXabortXend:
  132. case FlowControl.Exception:// eg. ud0
  133. default:
  134. throw new Exception("Not supported by this simple example - " + instr.FlowControl);
  135. }
  136. }
  137. if (totalBytes < minimumTrampolineLength)
  138. throw new Exception("Not enough bytes!");
  139. if (origInstructions.Count == 0)
  140. throw new Exception("Not enough instructions!");
  141. ref readonly var lastInstr = ref origInstructions[origInstructions.Count - 1];
  142. if (lastInstr.FlowControl != FlowControl.Return)
  143. {
  144. Instruction detourInstruction;
  145. if (arch == Architecture.X64)
  146. {
  147. detourInstruction = Instruction.CreateBranch(Code.Jmp_rel32_64, lastInstr.NextIP);
  148. }
  149. else
  150. {
  151. detourInstruction = Instruction.CreateBranch(Code.Jmp_rel32_32, lastInstr.NextIP);
  152. }
  153. origInstructions.Add(detourInstruction);
  154. }
  155. // Generate trampoline from instruction list
  156. var codeWriter = new CodeWriterImpl();
  157. ulong relocatedBaseAddress = (ulong)trampolinePtr;
  158. var block = new InstructionBlock(codeWriter, origInstructions, relocatedBaseAddress);
  159. bool success = BlockEncoder.TryEncode(decoder.Bitness, block, out var errorMessage, out var result);
  160. if (!success)
  161. {
  162. throw new Exception(errorMessage);
  163. }
  164. // Write generated trampoline
  165. var newCode = codeWriter.ToArray();
  166. Marshal.Copy(newCode, 0, trampolinePtr, newCode.Length);
  167. jmpLength = newCode.Length - (int)totalBytes;
  168. trampolineLength = newCode.Length;
  169. }
  170. public static byte[] GenerateAbsoluteJump(IntPtr targetAddress, IntPtr currentAddress, Architecture arch)
  171. {
  172. byte[] jmpBytes;
  173. if (arch == Architecture.X64)
  174. {
  175. jmpBytes = new byte[]
  176. {
  177. 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, // FF25 00000000: JMP [RIP+6]
  178. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Absolute destination address
  179. };
  180. Array.Copy(BitConverter.GetBytes(targetAddress.ToInt64()), 0, jmpBytes, 6, 8);
  181. }
  182. else
  183. {
  184. jmpBytes = new byte[]
  185. {
  186. 0xE9, // E9: JMP rel destination
  187. 0x00, 0x00, 0x00, 0x00 // Relative destination address
  188. };
  189. Array.Copy(BitConverter.GetBytes(targetAddress.ToInt32() - (currentAddress.ToInt32() + 5)), 0, jmpBytes, 1, 4);
  190. }
  191. return jmpBytes;
  192. }
  193. private sealed class CodeWriterImpl : CodeWriter
  194. {
  195. readonly List<byte> allBytes = new List<byte>();
  196. public override void WriteByte(byte value) => allBytes.Add(value);
  197. public byte[] ToArray() => allBytes.ToArray();
  198. }
  199. }
  200. }