[Mono-list] Assembly code execution from C#

Markus Johnsson markus.johnsson.84 at gmail.com
Mon Oct 6 17:59:25 EDT 2008


Hi,

I've been experimenting with x86 assembly coding and execution from within
C#, and was happy to get some code (see below) to work. However, when I
tried it on Windows and .NET it failed with an AccessViolationException.
Should I expect it to fail on mono too in a future release? Is there a
better way to do this (i.e. executing x86 code without using a C
library)? Using mono the code below compiles and runs fine on both Windows
(mono 2.0) and Linux (mono svn).

cheers
Markus


using System;
using System.Text;
using System.Runtime.InteropServices;

class X86AssemblyExec {
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    private delegate int TheDelegate();

    public static void Main(string[] args) {
        // x86 assembly:
        // mov eax 8        B8 08 00 00 00
        // mov ebx 9        BB 09 00 00 00
        // add eax ebx      01 d8
        // ret              C3

        // opcode
        byte [] code = new byte[14];
        code[0] = (byte) 0xB8;
        code[1] = (byte) 0x08;
        code[2] = (byte) 0x00;
        code[3] = (byte) 0x00;
        code[4] = (byte) 0x00;

        code[5] = (byte) 0xBB;
        code[6] = (byte) 0x09;
        code[7] = (byte) 0x00;
        code[8] = (byte) 0x00;
        code[9] = (byte) 0x00;

        code[10] = (byte)0x01;
        code[11] = (byte)0xd8;

        code[12] = (byte)0xC3;

        code[13] = 0;

        unsafe {
            fixed (void *ptr = code) {

                // create the delegate
                TheDelegate del = (TheDelegate)
Marshal.GetDelegateForFunctionPointer(
                    new IntPtr(ptr), typeof(TheDelegate));

                // call the function
                int x = del();

                // outputs 17
                Console.WriteLine(x);
            }
        }
    }
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ximian.com/pipermail/mono-list/attachments/20081006/2e2ca3c0/attachment.html 


More information about the Mono-list mailing list