c - Printf in inline Assembly -
i trying write inline assebly function exchanges 2 values.( , i'm using extended asm format)
this code works:
#include <stdio.h> void exchange(int *x, int *y) { printf("in exchange function: before exchange x is: %d\n",*x); printf("in exchange function: before exchange y is: %d\n",*y); asm("xchg %%eax,%%edx\n\t" \ :"+a"(*x),"+d"(*y)); printf("in exchange function: after exchange x is: %d\n",*x); printf("in exchange function: after exchange y is: %d\n",*y); } int main() { int x=20; int y=30; printf("in main: before exchange x is: %d\n",x); printf("in main: before exchange y is: %d\n",y); exchange(&x,&y); printf("in main: after exchange x is: %d\n",x); printf("in main: after exchange y is: %d\n",y); return 0; }
but when try wirte in full assembly below segmentation fault (core dumped) error.
void exchange(int *x, int *y) { asm("subl $8,%%esp\n\t" \ "movl %%eax,4(%%esp)\n\t" \ "movl %%edx,(%%esp)\n\t" \ "call printf\n\t" \ "addl $8,%%esp\n\t" \ "xchg %%eax,%%edx\n\t" \ "subl $8,%%esp\n\t" \ "movl %%eax,4(%%esp)\n\t" \ "movl %%edx,(%%esp)\n\t" \ "call printf\n\t" \ "addl $8,%%esp\n\t" \ :"+a"(*x),"+d"(*y)); } int main() { int x=20; int y=30; printf("in main: before exchange x is: %d\n",x); printf("in main: before exchange y is: %d\n",y); exchange(&x,&y); printf("in main: after exchange x is: %d\n",x); printf("in main: after exchange y is: %d\n",y); return 0; }
aren't allowed use printf function in assembly section?
your asm code calls printf 2 integer arguments -- no format string. tries dereference first integer pointer format string , crashes.
also, calling printf clobber values in %eax , %edx, not preserved across calls in standard x86 calling conventions.
Comments
Post a Comment