Sometimes the correct argc value is returned, sometimes 0, and sometimes (seemingly)random numbers… all from the same executable.
.section .text
.global _start
_start:
movq $1, %rax
popq %rdi
syscall
For example:
%as -o this.o this.s ; ld -o this this.o
%./this; echo $?
1
%./this 1; echo $?
0
%./this 1 2; echo $?
3
%./this 1 2 a; echo $?
4
%./this 1 2 a f; echo $?
0
%_
I’m kind of new to assembly, but I was pretty confident that getting the argument count was as easy as popping it off the stack like in Linux, where the System V ABI documents that RSP points at argc in a freshly execve‘d process.
Am I doing something wrong, or is this just really messed up?
I was confused in the same case on FreeBSD 9.0/amd64. What I did is (I used nasm for assembler):
I expected that argc was at rsp, but it was not.
I guessed that the kernel (the image activator) sets registers. I searched the source tree, I found the following code in /usr/src/sys/amd64/amd64/machdep.c (exec_setregs).
EDIT: machdep.c has been split up and this function can now be found in exec_machdep.c
These lines look saying that rsp is aligned, actual data are at rdi. I changed my code, and I got expected results.
Can you try rdi?