On entry to
_start, the top of the stack isargc, not a return address.
In C99, command-line arguments arrive in main(argc, argv), making it look as if the language runtime conjures them up. In reality, the kernel lays out the argument vector and environment on the stack, and main receives them via the CRT startup code. In this lesson, I inspect the process startup stack: what sits at rsp, where argv ends, how to locate envp, and why executing ret in _start crashes the program instead of returning cleanly.
Mental Model: Stack Layout Instead of a Call
| What it looks like in C99 | What happens in hardware |
|---|---|
main receives arguments from the language |
The kernel places argc, argv, and envp on the stack, then jumps to _start |
argv is a single string |
It’s a NULL-terminated array of pointers to strings |
envp is part of argv |
It’s a separate NULL-terminated array immediately following argv’s NULL |
_start can finish with ret |
argc sits at the top of the stack, not a return address |
argv[0] is always the short program name |
It’s whatever string execve received—which may be a full path |
The kernel neither calls main nor passes arguments to it in registers. Before jumping to _start for the first time, it populates the stack with the argument count, argv, and envp, and only then transfers control to the entry point.
Map of the Startup Stack
The args_inspect.asm testbed reads the first three stack items and prints argv[1] or a fallback message:
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; args_inspect.asm — argc, argv, and envp live on the initial process stack.
; GDB inspects envp_ready: r10 already points to envp.
default rel
%define SYS_WRITE 1
%define SYS_EXIT 60
%define STDOUT 1
section .rodata
msg_none: db "(no args)", 10
msg_none_len: equ $ - msg_none
section .text
global _start
; ------------------------------------------------------------------------------
; _start — prints argv[1] or "(no args)" and exits with argc.
; Input: rsp -> argc, argv, NULL, envp, NULL
; Output: does not return; exit code is argc
; Clobbers: rax, rcx, rdx, rsi, rdi, r8, r9, r10, r11, flags
; ------------------------------------------------------------------------------
_start:
mov r8, [rsp]
lea r9, [rsp + 8]
lea r10, [r9 + r8 * 8 + 8]
envp_ready:
cmp r8, 2
jl .no_arg
mov rsi, [r9 + 8]
xor edx, edx
.len_loop:
cmp byte [rsi + rdx], 0
je .print
inc rdx
jmp .len_loop
.no_arg:
lea rsi, [msg_none]
mov edx, msg_none_len
.print:
; syscall: write(STDOUT, rsi, rdx) — argv[1] or "(no args)"
mov eax, SYS_WRITE
mov edi, STDOUT
syscall
; syscall: exit(argc)
mov edi, r8d
mov eax, SYS_EXIT
syscall
section .note.GNU-stack noalloc noexec nowrite progbitsStack layout on entry to _start when running ./build/args_inspect alpha beta:
rsp + 0 -> argc = 3
rsp + 8 -> argv[0] --> "build/args_inspect"
rsp + 16 -> argv[1] --> "alpha"
rsp + 24 -> argv[2] --> "beta"
rsp + 32 -> NULL
rsp + 40 -> envp[0] --> "FOO=bar"
rsp + 48 -> envp[1] --> "BAZ=qux"
rsp + 56 -> ...rsp + 0—argc, the number of entries inargvincluding the program name.rsp + 8—argv[0], pointer to the program name string.rsp + 16andrsp + 24—argv[1]andargv[2].rsp + 32— null pointer terminatingargv.rsp + 40— first element ofenvp, followed by the rest of the environment variables.rsp + 56— continuation ofenvp, terminated by its own null pointer.
Disassembly shows how three instructions locate all three items:
401000: 4c 8b 04 24 mov r8,QWORD PTR [rsp]
401004: 4c 8d 4c 24 08 lea r9,[rsp+0x8]
401009: 4f 8d 54 c1 08 lea r10,[r9+r8*8+0x8]4c 8b 04 24—mov r8, [rsp]:r8receivesargc.4c 8d 4c 24 08—lea r9, [rsp+8]:r9receives the address ofargv[0].4f 8d 54 c1 08—lea r10, [r9 + r8*8 + 8]: computesenvpasargv + argc*8 + 8, where+8skips pastargv’s terminatingNULL.
GDB: Inspecting the Startup Stack Words
At the entry point, GDB shows both the stack words and the strings they point to. Below, x/s prints a null-terminated string, and *(char**) casts an 8-byte stack slot as a C pointer to a string pointer.
(gdb) break _start
Breakpoint 1 at 0x401000: file args_inspect.asm, line 26.
(gdb) run alpha beta
Starting program: .../build/args_inspect alpha beta
Breakpoint 1, _start () at args_inspect.asm:26
26 mov r8, [rsp]
(gdb) x/5gx $rsp
0x7fffffffec10: 0x0000000000000003 0x00007fffffffee10
0x7fffffffec20: 0x00007fffffffee69 0x00007fffffffee6f
0x7fffffffec30: 0x0000000000000000
(gdb) x/s *(char**)($rsp+8)
0x7fffffffee10: ".../build/args_inspect"
(gdb) x/s *(char**)($rsp+16)
0x7fffffffee69: "alpha"
(gdb) x/s *(char**)($rsp+24)
0x7fffffffee6f: "beta"- The first qword
0x0000000000000003isargc; hence the program exits with3. - The second qword is
argv[0], the path to the binary. - The third and fourth qwords point to
"alpha"and"beta". - The fifth qword is
0:argv’s null terminator. x/s *(char**)($rsp+16)treats the stack slot at$rsp+16as a pointer to a string pointer (char **), dereferences it once (*) to get thechar *, and prints the string itself rather than its address.
envp: The Vector After argv
At envp_ready, r10 already points to envp. In this GDB session, the environment was cleared with unset environment and populated via set environment FOO=bar, set environment BAZ=qux, and set environment HOME=/home/basted before run (otherwise envp would start with all inherited shell variables):
(gdb) break envp_ready
Breakpoint 2 at 0x40100e: file args_inspect.asm, line 31.
(gdb) continue
Breakpoint 2, envp_ready () at args_inspect.asm:31
31 cmp r8, 2
(gdb) print/x $r10
$1 = 0x7fffffffec38
(gdb) x/4gx $r10
0x7fffffffec38: 0x00007fffffffee74 0x00007fffffffee7c
0x7fffffffec48: 0x00007fffffffee84 0x00007fffffffee96
(gdb) x/s *(char**)$r10
0x7fffffffee74: "FOO=bar"
(gdb) x/s *(char**)($r10+8)
0x7fffffffee7c: "BAZ=qux"
(gdb) x/s *(char**)($r10+16)
0x7fffffffee84: "HOME=/home/basted"$1 = 0x7fffffffec38— address of the firstenvppointer.- The first two entries are
FOO=barandBAZ=quxset viaset environment. HOME=/home/bastedwas also set viaset environmentafter clearing (in a normal run withoutunset environment, the kernel copies the entire environment from the parent shell).x/4gxshows the pointer array continuing until its own trailing null pointer, just likeargv.
Running and Checking the Exit Status
The program prints the first argument and exits with argc:
$ ./build/args_inspect alpha beta
alpha
$ echo $?
3
$ ./build/args_inspect
(no args)
$ echo $?
1- With two arguments,
argv[1]points toalphaandecho $?prints3. - With no arguments,
.no_argprints(no args)and the exit code is1. - String length is computed in a loop until byte
0: there is no externalstrlenhere. args_inspectwritesargv[1]without a trailing\n: the line break before$ echo $?above is added for readability; in a real terminal the prompt appears right afteralpha.
Why Returning from _start with ret Crashes
The kernel does not invoke _start with call, so it never pushes a return address onto the stack. ret_bad.asm executes a single ret:
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; ret_bad.asm — ret from _start: argc sits on top of the stack, not a return address.
default rel
section .text
global _start
_start:
ret
section .note.GNU-stack noalloc noexec nowrite progbitsRunning it dies with a signal, and GDB shows the jump target:
$ ./build/ret_bad; echo $?
139
$ gdb -q --nx -batch -ex run -ex 'x/i $pc' ./build/ret_bad
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000001 in ?? ()
=> 0x1: Cannot access memory at address 0x1retpops the top qword from the stack—argc, which equals1.- The CPU jumps to address
0x1, where no memory is mapped, triggeringSIGSEGV. echo $?prints139 = 128 + 11: signal11isSIGSEGV.- In GDB,
$pcaliases$rip, sox/i $pctries to disassemble the instruction at the faulting jump target. - Always terminate
_startwith theexitsyscall, neverret.
Common Pitfalls
-
“Executing
retfrom_startreturns control to the kernel.”
Fact:./build/ret_bad; echo $?prints139, and GDB stops at0x0000000000000001.
Cause: the kernel never usedcalland never pushed a return address;retinterpretedargcas a return address.
Fix: exit the entry point via theexitsyscall (or hand off to CRT), never withret. -
"
[rsp]isargv[0]."
Fact:x/5gx $rspprints3as the first qword, whilex/s *(char**)($rsp+8)prints the program path.
Cause:argcsits atrsp, and the pointer array begins one qword higher.
Fix: readargcfrom[rsp]andargvstarting atrsp + 8. -
"
argv[argc]is another argument."
Fact: the stack dump afterbetacontains0x0000000000000000.
Cause:argvis null-terminated; that trailing pointer is not a valid string.
Fix: terminateargvtraversal on the null pointer rather than indexing pastargc. -
"
argv[0]is always the short filename without a path."
Fact: in GDB,x/s *(char**)($rsp+8)prints the full path.../build/args_inspect.
Cause: the kernel passes whatever string it received inexecve; the invoking shell may pass a full path.
Fix: never assumeargv[0]is a bare filename with no directory slashes.
Lab
Goal. Build args_echo.asm to print each argv entry on its own line and exit with argc.
Contract and requirements.
- Standalone binary: entry point
_start, no libc and no C99 harness. - Walk
argvuntil the null pointer rather than using a hardcoded bound. - Print each argument with
write, followed by a separatewriteof byte10(\n) from.rodata. - Exit with
argc; when launched with no extra arguments,argvstill containsargv[0]. - Do not copy or modify strings on the stack: print directly from the pointers in
argv.
Verification criteria.
./build/args_echo alpha beta; echo $?prints three lines and exits with3../build/args_echo; echo $?prints one line (the binary path) and exits with1.- In GDB at
_start, the first stack qword isargcandargv[1]followsargv[0]. strace -e write ./build/args_echo alpha betashows sixwritesyscalls to stdout (two per entry: the string itself and\n).- In GDB at the loop-termination checkpoint, the pointer register holds
NULLrather than a string address.
Hints, expected output, and walkthrough
Running ./build/args_echo alpha beta produces:
./build/args_echo
alpha
betaExit status is 3. The first line is argv[0], whose exact text depends on how the binary was invoked: ./build/args_echo from the lesson directory, or the full path under GDB.
argcsits at[rsp].argv[0]sits at[rsp+8].- The next array slot is
[rsp+16], not[rsp+9]: pointers are 8 bytes wide. - The array terminator is a null pointer, not an empty string.
If the output includes a stray blank line, the loop is printing argv’s null terminator as a string. If it crashes on the second argument, check for 32-bit pointer reads or the wrong stride across argv.
Testbed sources, Makefile, and automated tests for this lesson: lessons/13-command-line-args.
Summary
- The kernel enters
_startwithargc,argv,NULL,envp,NULLon the stack. argvis a null-pointer-terminated array of string pointers.envpstarts right afterargv’sNULLterminator and ends with its ownNULL.argcsits atrsp;argv[0]sits atrsp + 8.- Calling
retfrom_startpopsargcas a return address and triggersSIGSEGV. - CRT reads this startup stack and passes
argcandargvon tomain.
char, and signed division remainder with idiv.