TrampolineGenerator.cs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using Iced.Intel;
  5. namespace BepInEx.IL2CPP
  6. {
  7. public static class TrampolineGenerator
  8. {
  9. public static int Generate(IntPtr originalFunctionPtr, IntPtr patchedFunctionPtr, IntPtr trampolineFunctionPtr, int bitness)
  10. {
  11. byte[] instructionBuffer = new byte[80];
  12. Marshal.Copy(originalFunctionPtr, instructionBuffer, 0, 80);
  13. // Decode original function up until we go past the needed bytes to write the jump to patchedFunctionPtr
  14. var generatedJmp = GenerateAbsoluteJump(patchedFunctionPtr, originalFunctionPtr, bitness == 64);
  15. uint requiredBytes = (uint)generatedJmp.Length;
  16. var codeReader = new ByteArrayCodeReader(instructionBuffer);
  17. var decoder = Decoder.Create(bitness, codeReader);
  18. decoder.IP = (ulong)originalFunctionPtr.ToInt64();
  19. uint totalBytes = 0;
  20. var origInstructions = new InstructionList();
  21. while (codeReader.CanReadByte)
  22. {
  23. decoder.Decode(out var instr);
  24. origInstructions.Add(instr);
  25. totalBytes += (uint)instr.Length;
  26. if (instr.Code == Code.INVALID)
  27. throw new Exception("Found garbage");
  28. if (totalBytes >= requiredBytes)
  29. break;
  30. switch (instr.FlowControl)
  31. {
  32. case FlowControl.Next:
  33. break;
  34. case FlowControl.UnconditionalBranch:
  35. if (instr.Op0Kind == OpKind.NearBranch64)
  36. {
  37. var target = instr.NearBranchTarget;
  38. }
  39. goto default;
  40. case FlowControl.IndirectBranch:// eg. jmp reg/mem
  41. case FlowControl.ConditionalBranch:// eg. je, jno, etc
  42. case FlowControl.Return:// eg. ret
  43. case FlowControl.Call:// eg. call method
  44. case FlowControl.IndirectCall:// eg. call reg/mem
  45. case FlowControl.Interrupt:// eg. int n
  46. case FlowControl.XbeginXabortXend:
  47. case FlowControl.Exception:// eg. ud0
  48. default:
  49. throw new Exception("Not supported by this simple example - " + instr.FlowControl);
  50. }
  51. }
  52. if (totalBytes < requiredBytes)
  53. throw new Exception("Not enough bytes!");
  54. if (origInstructions.Count == 0)
  55. throw new Exception("Not enough instructions!");
  56. ref readonly var lastInstr = ref origInstructions[origInstructions.Count - 1];
  57. if (lastInstr.FlowControl != FlowControl.Return)
  58. {
  59. if (bitness == 64)
  60. {
  61. origInstructions.Add(Instruction.CreateBranch(Code.Jmp_rel32_64, lastInstr.NextIP));
  62. }
  63. else
  64. {
  65. origInstructions.Add(Instruction.CreateBranch(Code.Jmp_rel32_32, lastInstr.NextIP));
  66. }
  67. }
  68. // Generate trampoline from instruction list
  69. var codeWriter = new CodeWriterImpl();
  70. ulong relocatedBaseAddress = (ulong)trampolineFunctionPtr;
  71. var block = new InstructionBlock(codeWriter, origInstructions, relocatedBaseAddress);
  72. bool success = BlockEncoder.TryEncode(decoder.Bitness, block, out var errorMessage, out var result);
  73. if (!success)
  74. {
  75. throw new Exception(errorMessage);
  76. }
  77. // Write generated trampoline
  78. var newCode = codeWriter.ToArray();
  79. Marshal.Copy(newCode, 0, trampolineFunctionPtr, newCode.Length);
  80. // Overwrite the start of trampolineFunctionPtr with a jump to patchedFunctionPtr
  81. Marshal.Copy(generatedJmp, 0, originalFunctionPtr, (int)requiredBytes);
  82. return newCode.Length;
  83. }
  84. private static byte[] GenerateAbsoluteJump(IntPtr address, IntPtr currentAddress, bool x64)
  85. {
  86. byte[] jmpBytes;
  87. if (x64)
  88. {
  89. jmpBytes = new byte[]
  90. {
  91. 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, // FF25 00000000: JMP [RIP+6]
  92. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Absolute destination address
  93. };
  94. Array.Copy(BitConverter.GetBytes(address.ToInt64()), 0, jmpBytes, 6, 8);
  95. }
  96. else
  97. {
  98. jmpBytes = new byte[]
  99. {
  100. 0xE9, // E9: JMP rel destination
  101. 0x00, 0x00, 0x00, 0x00 // Relative destination address
  102. };
  103. Array.Copy(BitConverter.GetBytes(address.ToInt32() - (currentAddress.ToInt32() + 5)), 0, jmpBytes, 1, 4);
  104. }
  105. return jmpBytes;
  106. }
  107. private sealed class CodeWriterImpl : CodeWriter
  108. {
  109. readonly List<byte> allBytes = new List<byte>();
  110. public override void WriteByte(byte value) => allBytes.Add(value);
  111. public byte[] ToArray() => allBytes.ToArray();
  112. }
  113. }
  114. }