Skip to content

Instantly share code, notes, and snippets.

@josinSbazin
Created December 28, 2017 15:12
Show Gist options
  • Save josinSbazin/4ae58e2b67e6b01e8a548e06ad04d9ea to your computer and use it in GitHub Desktop.
Save josinSbazin/4ae58e2b67e6b01e8a548e06ad04d9ea to your computer and use it in GitHub Desktop.
HijackMethod
public static void HijackMethod(MethodInfo source, MethodInfo target)
{
RuntimeHelpers.PrepareMethod(source.MethodHandle);
RuntimeHelpers.PrepareMethod(target.MethodHandle);
var sourceAddress = source.MethodHandle.GetFunctionPointer();
var targetAddress = (long)target.MethodHandle.GetFunctionPointer();
int offset = (int)(targetAddress - (long)sourceAddress - 4 - 1); // four bytes for relative address and one byte for opcode
byte[] instruction = {
0xE9, // Long jump relative instruction
(byte)(offset & 0xFF),
(byte)((offset >> 8) & 0xFF),
(byte)((offset >> 16) & 0xFF),
(byte)((offset >> 24) & 0xFF)
};
Marshal.Copy(instruction, 0, sourceAddress, instruction.Length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment