Tuesday, May 08, 2012

Inline assembly

A mini-quest of mine is to (re-)learn x86 assembly language. Today I tried to get a 'Hello World!' thing going. My chosen platform is inline assembly in MSVC, basically because it seems like the easiest way. And it was pretty easy. Since strings in assembly are pretty complex, my program will add two integers together.

Inline assembly is just put in a '__asm' block. And it is really simple. Variable names can just be used inside the block. So my whole program looks like:

int add(int x, int y)
{
  __asm {
    mov eax, y
    add x, eax
  }

  return x;
}

int _tmain(int argc, _TCHAR* argv[])
{
  printf("sum: %d\n", add(4, 23));
    return 0;
}

Where add is a c function who's implementation is in assembly (well the prelude and epilogue are done by the C++ compiler, but that's one reason to use inline assembly, told you it made things easy). The main function supplies the arguments and prints the result.

The actual assembly is really simple, 'add' adds its second argument to the first, only one of the arguments can be a memory location, so we have to use a register for the second argument. The 'mov' instruction copies the value in y to eax, which then gets added to x, which holds the result.

1 comment:

  1. It's a different life for you now, isn't it!!

    ReplyDelete