I was reading assembly tutorials and got stuck on stack operations and function calls. As said here, when fuction A calls function B, it passes first 4 arguments in registers(by value or pointer) and next ones are passed via stack. Also, caller funcion has to allocate 32 bytes on stack for calle to store those 4 value in registers. But when I have this simple code:
void foo()
{
int a = 0;
a++;
}
int WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
foo();
return 0;
}
The disassembly:
WinMain:
mov dword ptr [rsp+20h],r9d
mov qword ptr [rsp+18h],r8
mov qword ptr [rsp+10h],rdx
mov qword ptr [rsp+8],rcx
sub rsp,28h
call foo (013F321000h)
xor eax,eax
add rsp,28h
ret
foo:
sub rsp,18h
mov dword ptr [rsp],0
mov eax,dword ptr [rsp]
inc eax
mov dword ptr [rsp],eax
add rsp,18h
ret
And the question is: why compiler allocates more memory than it actually needs for stack frames? For example, in WinMain
, when it's calling foo
, no parameters are passed via stack, so why it allocates 40 bytes instead of 32 shadow space? And the same is in foo
function: it needs only 4 bytes to store int variable, another 4 probably are used for alignment, but how another 16 bytes are used?
I use VS2017, code is build in Win64-Debug, optimisation, intrisicts and JMC are disabled.