Hello everyone,

I'm using the kipirvine library and am writing a few functions to showcase different ways of return values back to main.

How do you return a value by pushing it on the stack in the function, and then popping it back in main?

Thanks in advance...

-Mallard
Posted on 2011-10-29 19:25:57 by msmallard
You first need to make space on the stack where you will store the return value(s). Let's use a single 32-bit value to be returned as an example.

push eax  ;you can push any register you want, they're all the same for this purpose
push arg1
push arg2  ;push whichever number of arguments required by the proc
call myproc
;depending on the calling convention you use, you then either clean the stack yourself or let the system do it for you
;the proc would have to insert the return value on the stack in the reserved space in front of the arguments
;all you then have to do is to pop the return value directly to memory of into whichever register it can be used most effectively
pop ecx

myproc proc arg1:DWORD,arg2:DWORD
....
;assuming the return value is in ECX
mov arg1[4],ecx  ;store it in the stack slot immediately in front of the first argument that was pushed
ret
myproc endp


If your proc does not need any argument, you would then need to make sure that a stack frame is built and use the EBP register directly to locate the reserved stack slot which would be immediately next to the return address.
Posted on 2011-10-29 23:15:22 by Raymond