TrampolineGenerator.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. // TODO: set this per arch, and implement x86 E9 jmp
  15. const uint requiredBytes = 10 + 2;
  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. origInstructions.Add(Instruction.CreateBranch(Code.Jmp_rel32_64, lastInstr.NextIP));
  58. // Generate trampoline from instruction list
  59. var codeWriter = new CodeWriterImpl();
  60. ulong relocatedBaseAddress = (ulong)trampolineFunctionPtr;
  61. var block = new InstructionBlock(codeWriter, origInstructions, relocatedBaseAddress);
  62. bool success = BlockEncoder.TryEncode(decoder.Bitness, block, out var errorMessage, out var result);
  63. if (!success)
  64. {
  65. throw new Exception(errorMessage);
  66. }
  67. // Write generated trampoline
  68. var newCode = codeWriter.ToArray();
  69. Marshal.Copy(newCode, 0, trampolineFunctionPtr, newCode.Length);
  70. // Overwrite the start of trampolineFunctionPtr with a jump to patchedFunctionPtr
  71. var jmpCode = new byte[requiredBytes];
  72. jmpCode[0] = 0x48;// \ 'MOV RAX,imm64'
  73. jmpCode[1] = 0xB8;// /
  74. ulong v = (ulong)patchedFunctionPtr.ToInt64();
  75. for (int i = 0; i < 8; i++, v >>= 8)
  76. jmpCode[2 + i] = (byte)v;
  77. jmpCode[10] = 0xFF;// \ JMP RAX
  78. jmpCode[11] = 0xE0;// /
  79. Marshal.Copy(jmpCode, 0, originalFunctionPtr, (int)requiredBytes);
  80. return newCode.Length;
  81. }
  82. private sealed class CodeWriterImpl : CodeWriter
  83. {
  84. readonly List<byte> allBytes = new List<byte>();
  85. public override void WriteByte(byte value) => allBytes.Add(value);
  86. public byte[] ToArray() => allBytes.ToArray();
  87. }
  88. }
  89. }