I finished writing this swap function earlier today, first in c, then in assembly, and I understand everything except lines 9 and 10 which access the parameters to the function. I figured out the offsets 32 and 28 by using the -S option with gcc and examining the .s file. This is solely for my own learning purpose, so I really want to take the time to understand why the offsets are what they are. I understand that parameters are passed in backwards in cdecl, and that they are ints, which is why the difference between them is 4. I am guessing they are in a new stack frame, which is why it is so high, but I am not sure.
#include <stdio.h>
char msg[] = "asm print test<-->\0";
char msg2[] = "ebx value is: %d\n\0";
//asm version
void asm_swap(int* a, int* b ){
__asm__("\n\
enter $0,$0\n\
movl 32(%ebp), %ebx\n\
movl 28(%ebp), %esi\n\
xorl %ebx, %esi\n\
xorl %esi, %ebx\n\
xorl %ebx, %esi\n\
movl %ebx, 32(%ebp)\n\
movl %esi, 28(%ebp)\n\
leave\n\
");
}
void asm_loop(){
__asm__("\n\
xorl %ebx, %ebx\n\
begin:\n\
addl $1, %ebx\n\
cmpl $3, %ebx\n\
jg end\n\
push $msg\n\
call printf\n\
addl $4, %esp\n\
pushl %ebx\n\
pushl $msg2\n\
call printf\n\
addl $8, %esp\n\
jmp begin\n\
end:\n\
");
}
int main(){
//testing asm_swap
int a = 3232; int b = 7575;
int* x = &a; int* y = &b;
printf("\n::testing asm_swap::\nx: %d, y:%d\n",*x,*y);
asm_swap(x,y);
printf("x: %d, y:%d\n\n",*x,*y);
return 0;
}
Edited:
Just for clarity's sake, the C function basically was:
void swap(int* x, int* y){
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
This post has been edited by raspinudo: 15 May 2012 - 01:18 AM

New Topic/Question
Reply


MultiQuote







|