The MASM Forum Archive 2004 to 2012

General Forums => The Workshop => Topic started by: brodeur235 on April 26, 2010, 02:14:04 AM

Title: asm return values
Post by: brodeur235 on April 26, 2010, 02:14:04 AM
What is the higher-language compatible way to return a value from a lower level asm function. I've been pushing arguments onto the stack, then subtracting 4 from esp to leave room for a return value or pointer, then calling the subroutine and setting up a stack frame. Then, after the function cleans up returns, the first thing I pop off the stack is the return value... This has just been my convention for the longest time, but it occurs to me that that is probably not the standard. What is? Help appreciated,

Brodeur235
Title: Re: asm return values
Post by: hutch-- on April 26, 2010, 02:25:21 AM
The convention is to return the function value in the EAX register. You should make sure your stack is balanced on procedure exit. With a MASM stack frame this is automatic, if you write your own proc without a stack frame with STDCALL, usually you use RET BYTECOUNT where BYTECOUNT = the number of bytes pushed by the caller. With C calling convention the caller adjusts the stack after the call has returned.
Title: Re: asm return values
Post by: MichaelW on April 26, 2010, 02:46:17 AM
For the return value under 32-bit Windows the standard is basically to return 32-bit integers in EAX, 64-bit integers in the EDX:EAX register pair, floating-point values at the top of the FPU stack in ST(0), and a pointer in EAX for anything else. See calling_conventions.pdf, available here:

http://www.agner.org/optimize/

Title: Re: asm return values
Post by: brodeur235 on April 26, 2010, 03:30:40 AM
EAX for 32 bit and EDX:EAX for 64 bit, thanks you guys are always awesome help.
Quote
With C calling convention the caller adjusts the stack after the call has returned.
I prefer this way to allow for a variable number of arguments, like printf. If you use the  ret command with some static integer that will always be added to the stack, you cannot adjust for a variable number of parameters.. I think, haha.
Thank you,

Brodeur235
Title: Re: asm return values
Post by: jj2007 on April 26, 2010, 06:38:02 AM
You might look at VARARG in STDCALL mode (http://www.masm32.com/board/index.php?topic=13727.0)
Title: Re: asm return values
Post by: joemc on April 28, 2010, 03:42:15 AM
brodeur235,
Your code also becomes larger if the function is called more than once.  The cleanup code has to be repeated over and over instead of just once. Probably not a big deal but it adds up if the function is called many times.
Title: Re: asm return values
Post by: dedndave on April 28, 2010, 04:30:24 AM
QuoteI prefer this way to allow for a variable number of arguments, like printf.
you could also pass a pointer to a structure
structures can have a variable number of arguments, as well as variable-length data types (like strings)