Skip to content

Instantly share code, notes, and snippets.

@vcsjones
Created August 13, 2013 18:02
Show Gist options
  • Save vcsjones/6223885 to your computer and use it in GitHub Desktop.
Save vcsjones/6223885 to your computer and use it in GitHub Desktop.
Overwrite's a MethodInfo's JITed assembly code so that a method aways returns false.
private static void ChangeToReturnFalse(MethodInfo methodInfo)
{
var intPtrConstructor = typeof(IntPtr).GetConstructor(new[] { typeof(void*) });
var method = new DynamicMethod("ChangeToReturnFalse", typeof(IntPtr), Type.EmptyTypes, typeof(ServiceLocationModule));
var generator = method.GetILGenerator();
generator.Emit(OpCodes.Ldftn, methodInfo);
generator.Emit(OpCodes.Newobj, intPtrConstructor);
generator.Emit(OpCodes.Ret);
var addressFunctor = (Func<IntPtr>)method.CreateDelegate(typeof(Func<IntPtr>));
var address = addressFunctor();
var x64Asm = new byte[]
{
0x33, 0xc0, 0xf3, 0xc3
};
var x86Asm = new byte[]
{
0x55, 0x8b, 0xec, 0x33, 0xc0, 0x5d, 0xc3
};
var asm = IntPtr.Size == 8 ? x64Asm : x86Asm;
Marshal.Copy(asm, 0, address, asm.Length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment