nov
29
2009

Assembly inline

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

tags: , , ,
posted in programação by Tiago Maluta

Follow comments via the RSS Feed | Deixe um comentário | Trackback URL

1 Comment to "Assembly inline"

  1. Mauricio wrote:

    Hey Malutinha,
    Nice post!

    It seems Micro 2 is very made up on your mind. lol
    Good luck for the exam.

Leave Your Comment