Error in running byte array in C# using VirtualAlloc and GetDelegateForFunctionPointer

539 views Asked by At

I have a Windows form program created in c#, which is just a form and a single button. What I want to achieve here execute a hard-coded byte array, using VirtualAlloc and a delegate. This hard coded byte array pertains to the bytes of wrar.exe installer. I just wanted to try if it works. No special reason in choosing winrar installer. So in the button click event, I have this code:

private UInt32 MEM_COMMIT = 0x1000;
private UInt32 PAGE_EXECUTE_READWRITE = 0x40;
private UInt32 MEM_RELEASE = 0x8000;
private delegate void Runner();

[DllImport("kernel32")]
private static extern IntPtr VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);

byte[] body = new byte[1517376] { <actual bytes of the winrar installer EXE>};


private void btnExit_Click(object sender, EventArgs e)
{
        try
        {
            IntPtr buf = VirtualAlloc(0, (UInt32)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
            Marshal.Copy(body, 0, (IntPtr)buf, body.Length);
            Runner ptr = (Runner)Marshal.GetDelegateForFunctionPointer(buf, typeof(Runner));
            ptr();
            Application.Exit();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}

However, when I execute the program and click the button, I am having this error/exception: enter image description here

What am I doing wrong here? It seems it's related to the memory allocation. How do I fix this? Thanks a lot in advance!

1

There are 1 answers

2
Poppuff Arthem On

The code you wrote is for calling a function stored in memory.

What you stored is not a function but an executable. You need to find the offset of the entry point of the executable. Then call it.