Assembly Language for Beginners

(nextflipdebug2) #1

1.10. ACCESSING PASSED ARGUMENTS


retn
f endp


public main
main proc near


var_10 = dword ptr -10h
var_C = dword ptr -0Ch
var_8 = dword ptr -8


push ebp
mov ebp, esp
and esp, 0FFFFFFF0h
sub esp, 10h
mov [esp+10h+var_8], 3 ; 3rd argument
mov [esp+10h+var_C], 2 ; 2nd argument
mov [esp+10h+var_10], 1 ; 1st argument
call f
mov edx, offset aD ; "%d\n"
mov [esp+10h+var_C], eax
mov [esp+10h+var_10], edx
call _printf
mov eax, 0
leave
retn
main endp


The result is almost the same with some minor differences discussed earlier.


Thestack pointeris not set back after the two function calls(f and printf), because the penultimateLEAVE
(.1.6 on page 1028) instruction takes care of this at the end.


1.10.2 x64


The story is a bit different in x86-64. Function arguments (first 4 or first 6 of them) are passed in registers
i.e. thecalleereads them from registers instead of reading them from the stack.


MSVC


Optimizing MSVC:


Listing 1.89: Optimizing MSVC 2012 x64

$SG2997 DB '%d', 0aH, 00H


main PROC
sub rsp, 40
mov edx, 2
lea r8d, QWORD PTR [rdx+1] ; R8D=3
lea ecx, QWORD PTR [rdx-1] ; ECX=1
call f
lea rcx, OFFSET FLAT:$SG2997 ; '%d'
mov edx, eax
call printf
xor eax, eax
add rsp, 40
ret 0
main ENDP


f PROC
; ECX - 1st argument
; EDX - 2nd argument
; R8D - 3rd argument
imul ecx, edx
lea eax, DWORD PTR [r8+rcx]
ret 0
f ENDP

Free download pdf