Assembly inline

November 29, 2009

[Warning: This post is a backup recovery from my previous Wordpress blog. All content was automatically converted accessing a MySQL database using a Python script (details). Mostly are in Portuguese but if you are interest I can translate to English. If you found any problem dont’t hesitate to contact me in comments.]

I've made some code snippets about assembly inline with GCC. A quick search points to a lot of good documentation.

The syntax may be confusing, if you don't understand read the documentation available. Each example are an C function with the special construct "asm" for inline assembly code. Examples:

Increment an value:

void inc(int *value) {

    asm ( "incl %0"
         :"=a"(*value)
         :"0"(*value)
        );

}

Exchange to numbers:

void swap(int *x, int *y) {

    asm(""
        : "=a"(*y),"=b"(*x)
        : "a"(*x),"b"(*y)
       );

}

Copy an vector:

void vector_copy(int *v_src, int *v_dst, int *count) {

    asm("up: lodsl;"
	"    stosl;"
	"loop up;  "
	:
	: "S"(v_src), "D"(v_dst), "c"(*count)
	: "%eax"
	);

}

A simple copy:

void copy(int *from, int *to) {

     asm ("movl %1, %%eax;"
          "movl %%eax, %0;"
          :"=&r"(*to)
          :"r"(*from));

}

A very simple implementation for strncpy:

void _strncpy(char *src, char *dst, int *count) {

    asm("cld;"
        "rep movsb;"
        :
        : "S"(src), // 'S' == %esi
	  "D"(dst), // 'D' == %edi
	  "c"(*count)); // 'c' == %ecx
}

If you like to try check this example:

wget http://github.com/maluta/junk/raw/master/asm-inline.c
gcc -Wall -ggdb asm-inline.c -o asm-inline
./asm-inline