Parameter Passing Conventions in Assembly By Lord Lucifer September 2, 1998 Parameter Passing Conventions: ----------------------------------------------------------------------------- C calling convention: - Parameters are pushed in reverse order. - The function caller adjusts the stack. Stdcall calling convention: - Most 32-bit Windows programs use this form. - Parameters are pushed in reverse order. - The called function takes care of stack adjustment. Pascal calling convention: - The 16-bit Windows API uses this form. - Parameters are pushed in foward order. - The called function takes care of stack adjustment. Accessing Parameters and Local Variables: ----------------------------------------------------------------------------- The stack frame allows parameters and local variables to be easily accessed as offsets of register BP (or EBP). Take this example function (which uses the stdcall convention): void _stdcall Function(long var1, long var2) { int local1; int local2; local1 = var1; local2 = var2; } This is the memory map for the function call. ____ ____ ... |____|____| A104 |____|____| - ESP A108 |____|____| - local2 A10C |____|____| - local1 A110 |____|____| - EBP A114 |____|____| - Function return address A118 |____|____| - var1 A11C |____|____| - var2 ... |____|____| F000 |____|____| - Bottom of stack To access in assembly the parameters or the locals, all that is needed is the offset from EBP. Therefore: [ebp-4] would be the variable local1 [ebp-8] would be the variable local2 [ebp+08] would be the parameter var1 [ebp+0C] would be the parameter var2 The (unoptimized) disassembly of this simple function is: Function proc push ebp ; save ebp mov ebp,esp ; set ebp to current esp add esp,-8 ; adjust esp to point beyond ; the two local variables mov eax,dword ptr [ebp+08] ; copy var1 into temp eax mov dword ptr [ebp-4], eax ; copy temp eax into local1 mov ebx,dword ptr [ebp+0C] ; copy var2 into temp ebx mov dword ptr [ebp-8], ebx ; copy temp ebx into local2 add eax,ebx ; add local1 and local2 into eax ; eax is return value add esp,8 ; adjust esp to boint before the ; two local variables ; (point it to saved ebp) pop ebp ; restore ebp ret 8 ; return from function call and ; adjust stack past the 2 parameters Function endp ----------------------------------------------------------------------------- Copyright (C) 1998 Lord Lucifer (lord-lucifer@usa.net)