DetourGenerator.cs 7.7 KB

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