Tuesday, September 30, 2008

x86 assembler in .NET?

No, it's not possible - at least, not directly - to write inline ASM and call into it the way you can in C/C++. That was never a requirement for me, however - I just want something I can use to write ASM code and have it translated to a byte stream.

I'm one step closer today, thanks to Alex Lyman (whose blog is still under construction - I'll update later with a link) who answered my StackOverflow.com question with his X86Writer library.

Now I can write code like this:

    1 byte[] bytes;

    2 

    3 using (MemoryStream ms = new MemoryStream()) {

    4     X86Writer writer = new X86Writer(ms, new IntPtr(0x00400a00));

    5 

    6     var start = writer.CreateLabel();

    7     var func = writer.CreateLabel(new IntPtr(0x01000000));

    8 

    9     start.Mark();                                // start: 

   10 

   11     writer.Inc32(X86Register32.EAX);              // inc eax 

   12     writer.Cmp32(X86Register32.EAX, 5);           // cmp eax 05 

   13     writer.Jmp(X86ConditionCode.NotEqual, start); // jne start 

   14     writer.Call(func);                            // call 01000000 

   15 

   16     bytes = ms.ToArray();

   17 }


Really great stuff! I'd still like to be able to pass in a string, though - but this gives me a great platform on which to build!

Notice the support for labels - this really is the start of a powerful library, I think. Oh - and he open-sourced it under the New BSD License - which means everyone's free to contribute. If you have anything you want to add, please send me a patch!

No comments: