TrampolineGenerator.cs 7.0 KB

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