I'm trying to write a program that prints the command-line arguments given to the executable. I've narrowed the problem down to this: When I call printf more than once, it prints the correct answer the first time and then the wrong answer on subsequent calls.
It is my understanding that 64-bit windows NASM passes parameters in the rcx, rdx, r8, and r9 registers. If this is the case, I don't know why I have to mess with the stack at the beginning and end of the function... I only know that a segfault occurs if I remove that code.
I've tried choosing different registers for storing the argc and argv params, including pushing them to the stack, but it always fails. Here's the simplest code I could write with the error:
global main
extern printf
section .data
fmt_num: db '%ld Params...', 10, 0
section .text
main:
; Reserve local space on stack.
push rbp
mov rbp, rsp
sub rsp, 8*4
mov r11, rcx ; argc
mov rcx, fmt_num
mov rdx, r11
call printf ; Prints the correct number of parameters
mov rcx, fmt_num
mov rdx, r11 ; If I remove this line, it prints a seemingly random number.
call printf ; Consistently prints 582.
; Return local stack space.
add rsp, 8*4
mov rax, 0
pop rbp
ret
Changing the format string from %ld to %d has no effect, and changing the one line in the second call from:
mov rdx, r11
to something like:
mov rdx, 23
works just fine, so it's like the r11 register's value gets modified, but the issue still occurs even if I save and restore the register.