Aleksander Monk
Aleksander Monk

Reputation: 2907

Nasm return structure

Little homework question.

We have *.c file with some structure

typedef struct{
    int min;
    int max;
} M;
M mima( int N, ...);

int main(){
   M l = mima(5, 1, -2, 4 , 90, 4);
   printf("mi = %d, ma = %d \n", l.min, l.max);
   return 0;
}

and we have to write write "mima" in nasm. My only one problem is, after I find min and max I can't send them to my "c" program as a structure. Instead of -2 and 90 I get some random negative numbers.

We were told that it would be enough to send struct back.

 mov eax, (here is our min)
 mov edx, (here is our max)

But, unfortunately it doesn't work.

Here is how my asm file looks like

BITS 32
section .text

global mima

mima:                  
push ebp
mov ebp, esp


start:
    ; doing magic


leave 
ret             

Upvotes: 1

Views: 1300

Answers (1)

Jester
Jester

Reputation: 58762

There are two conventions in use for returning short structs. Either in edx/eax as you say, or like larger structs, in memory pointed to by a hidden first argument. Apparently you have been misinformed about the default convention used in your environment. Either the caller or the callee must be changed so their conventions match. If you are using gcc there is a -freg-struct-return command line switch that will enable the register return as you require. You may also change the assembly side, which should then look something like:

mima:                  
    push ebp
    mov ebp, esp
start:
    ; doing magic
    mov eax, [ebp+8]   ; hidden arg pointing to return space
    mov [eax], min     ; fill in return values
    mov [eax + 4], max
    ; must leave pointer in eax
    leave
    ret

Upvotes: 3

Related Questions