Skip to content

Instantly share code, notes, and snippets.

@Unknown6656
Created June 30, 2020 11:34
Show Gist options
  • Save Unknown6656/a42a810d4283208c3c21c632fb16c3f9 to your computer and use it in GitHub Desktop.
Save Unknown6656/a42a810d4283208c3c21c632fb16c3f9 to your computer and use it in GitHub Desktop.
using System.Runtime.InteropServices;
using System;
public static unsafe class Program
{
[DllImport("kernel32.dll")]
private static extern void* VirtualAlloc(void* addr, int size, int type, int protect);
[DllImport("kernel32.dll")]
private static extern bool VirtualProtect(void* addr, int size, int new_protect, int* old_protect);
[DllImport("kernel32.dll")]
private static extern bool VirtualFree(void* addr, int size, int type);
public static int Main(string[] argv)
{
byte[] asm = {
0x8D, 0x04, 0x11, // lea eax, [rcx+rdx]
0xC3 // ret
};
void* buffer = VirtualAlloc(null, asm.Length, 0x1000, 4);
var func = (delegate*<int, int, int>)buffer;
int dummy;
Marshal.Copy(asm, 0, (nint)buffer, asm.Length);
VirtualProtect(buffer, asm.Length, 0x20, &dummy);
Console.WriteLine(func(42, 378)); // call 'func' with (42, 378), which computes '420'
VirtualFree(buffer, 0, 0x8000);
}
}
@Mshriver2
Copy link

Beautiful code. Thanks

@Unknown6656
Copy link
Author

@Mshriver2 thanks. You're welcome.

Please note though that it is only a proof-of-concept and that this code might not be applicable in many other contexts....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment