Tastybrownies
Tastybrownies

Reputation: 937

Calling Multiple Functions in x86

I am attempting to learn x86 AT&T syntax and am at a spot where I cam a little confused in general. I understand that there are frames on the stack and when a call is made the first thing that happens in that function is some sort of frame update, then getting parameters. So, if I have some sort of value like 5 in the register eax in my Main area of code and call Function, I still have access to the value 5 in eax correct? Or in order to get it as a parameter I have to do something like this. I saw somewhere else that you pushed your arguments to the stack before calling a function, is this true? I guess something has to be located at 8(ebp) for me to move it into eax, but what is the value of eax before I move something into it with movl? Is it 5? I know this is a lot of questions, I'm just confused at the moment of calling a function and returning something. Any help would be greatly appreciated. I'm sure this is like a piece of cake for some assembly gurus!

Function:
pushl %ebp
movl %esp, %ebp

movl 8(ebp), eax

Upvotes: 0

Views: 596

Answers (1)

Powerslave
Powerslave

Reputation: 1428

This page should basically wrap that up.

With cdecl you go like

; I'm not comfortable with AT&T syntax, but it's not relevant here

; void *processData(void *firstParam, void *secondParam)
proc processData
    push ebp
    mov ebp,esp

    mov eax,[dword ptr ss:ebp + 8]    ; firstParam
    mov edx,[dword ptr ss:ebp + 12]   ; secondParam

    ; do something with the data and put the result into EAX

    mov esp,ebp
    pop ebp
    ret
endp processData

You invoke it like

lea eax,[ds:bufferOfSecondParam]
push eax
lea eax,[ds:bufferOfFirstParam]
push eax
call processData
add esp,8

; Here you can do with the return value anything you want

First of all, you need to decide on the calling convention to use. Win32, for example, uses a variant of cdecl called stdcall where the callee is responsible for cleaning up the stack - this is not too convenient to implement and does not allow for varargs.

[SS:EBP + 8] points to the first argument, because

  • Arguments are passed onto the stack from right to left ([SS:EBP + 12] points to the second arg)
  • DWORDS are 4 bytes
  • [SS:EBP + 0] points to the previous EBP saved upon creation of the stack frame
  • [SS:EBP + 4] points to the return address reaad into EIP upon ret

Upvotes: 1

Related Questions