// gcc -g stack.c -o stack
//
unsigned long sp(void){ __asm__("mov %esp, %eax");}
int main(int argc, char **argv)
{
unsigned long esp = sp();
printf("Stack pointer (ESP : 0x%lx)\n",esp);
return 0;
}
Please check the above code. And in fact, the sp() will return the esp register value via esp->eax, I guess. But why? The default return value of sp() is eax?
Who could tell me more about it? Thanks!
The way a processor architecture organizes arguments, calls, and returns, (and syscalls to kernel) i.e. calling conventions, is specificed in the ABI (application binary interface). For Linux on x86-64 you should read the x86-64 ABI document. And yes, the returned value for a function returning a
longis thru%eaxon x86-64. (There is also the X32 ABI)Notice that it is mostly conventional, but if the convention changes, you’ll need to change the compiler, perhaps the linker, the kernel, and all the libraries. Actually, it is so important that processor makers are designing the silicon with existing ABIs in mind (e.g. importance of the
%espregister,SYSENTERinstruction….).