DetourGenerator.cs 6.9 KB

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