Reserve shadow space with sub rsp, 40 before Windows x64 calls
Reserve shadow space with sub rsp, 40 before Windows x64 calls: 32 bytes of home space plus 8 to re-align the stack.
The Windows x64 calling convention makes the caller reserve 32 bytes of shadow space above the return address for the callee to spill its four register arguments, even when the callee takes none. The stack must also be 16-byte aligned at the call, and on entry to your function it is off by 8. So the standard prologue is sub rsp, 40: 32 for the shadow space and 8 to restore the alignment.
bits 64
default rel
extern ExitProcess
global main
section .text
main: ; entered by the loader: rsp is 8 mod 16
sub rsp, 40 ; 32 shadow + 8 alignment
mov ecx, 7 ; first argument in rcx
call ExitProcess
add rsp, 40 ; not reachednasm -f win64 exit.asm
link exit.obj kernel32.lib /entry:main /subsystem:console
exit.exe
echo %ERRORLEVEL%
7Without the shadow space the callee's spill writes land in your own frame and corrupt it, which shows up as a crash somewhere later. Microsoft's documentation of the x64 calling convention gives the rules, including that the first four integer arguments go in rcx, rdx, r8 and r9. System V on Linux has no shadow space and passes six in registers, so this prologue does not carry over.