X86-assembly/High-level-logic/functions

From aldeid
Jump to navigation Jump to search
You are here:
functions

Function anatomy

A function can be divided into 3 parts:

push  ebp               ; Save EBP
mov   ebp, esp          ; Save ESP in EBP
push  ecx               ; Allocate space for local variables
-------------------------------------------------------------
mov   eax, [ebp+8]      ;
add   eax, [ebp+0Ch]    ; Parameters passed to the function 
add   eax, [ebp+10h]    ;
mov   [ebp-4], eax      ; Save result in local variable
mov   eax, [ebp-4]      ; Copy the result to EAX
-------------------------------------------------------------
mov   esp, ebp          ; Restore ESP
pop   ebp               ; Restore EBP
retn                    ; Return
Function prolog
allocates local variable (EBP-value) and save registers
arguments (EBP+value) are placed on the stack with the push instruction
EIP is set to the address of the start of the function
EBP is pushed onto the stack so that the calling function knows where to go back once the function is executed
Function body
the function executes
Function epilog
stack and registers are restored
ESP is adjusted to free the local variables and EBP is restored so that the calling function can address its variables properly. The leave instrcution can be called
the function returns by calling the ret instruction

Calling conventions

cdecl

  • Arguments on stack, right to left
  • Return value in EAX
  • Caller cleans up stack
  • Most common

Example:

push    offset aSet_me_0   ; "set_me"
push    offset byte_40E024 ; Dest
call    strcpy
add     esp, 8             ; stack cleanup

stdcall

  • Similar to cdecl, callee cleans up stack
  • Used in WIN32 API

Example:

push    offset LibFileName ; "kernel32.dll"
call    LoadLibraryA
mov     [ebp+hLibModule], eax

fastcall

  • Parameters in registers
  • Extra parameters on stack
  • Caller cleans up

Example:

push    esi
push    ebx
call    sub_401020
add     esp, 8

thiscall

  • Used in C++ code (member functions)
  • Similar to cdecl, caller cleans up stack
  • ECX typically holds "this" pointer (Microsoft)
  • "this" pointer pushed onto stack last (GNU)

Example:

mov     ecx, [ebp+var_8] ; ecx holds address of 'self'
call    sub_41100A