Tom Xue
Tom Xue

Reputation: 3355

What is the return value of the “inline assembly” code?

// 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!

Upvotes: 0

Views: 1211

Answers (3)

Vesper
Vesper

Reputation: 18747

IIRC the correct command should be "mov eax, esp" instead of "mov esp, eax".

unsigned long sp(void){ __asm__("mov %eax, %esp");} 

Upvotes: -1

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 long is thru %eax on 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 %esp register, SYSENTER instruction....).

Upvotes: 5

Ray Toal
Ray Toal

Reputation: 88378

This is the rules!

The calling convention used by GCC for 32-bit assembly is for the return value of a integer-returning function to be the value in %eax. GCC adopts this for inline assembly functions as well.

See Wikipedia for all the details.

Upvotes: 2

Related Questions