TExcelTAD
Home › x86-64 Assembly › The Stack

The Stack

The stack is a region of memory that every program gets for free, used for temporary storage, saved registers, local variables and the return addresses of function calls. The register rsp always points to its top. On x86 the stack grows downwards: pushing makes rsp smaller.

push and pop

Instruction Effect
push src rsp = rsp - 8, then store the 8-byte src at [rsp]
pop dest load [rsp] into dest, then rsp = rsp + 8
text
              before            push 10            push 20            pop rax (= 20)
             +-------+         +-------+          +-------+          +-------+
  higher     |  ...  |         |  ...  |          |  ...  |          |  ...  |
             +-------+         +-------+          +-------+          +-------+
   rsp ----> |       |         |  10   | <- rsp   |  10   |          |  10   | <- rsp
             +-------+         +-------+          +-------+          +-------+
  lower                                           |  20   | <- rsp   |  (20) |  stale, free
                                                  +-------+          +-------+

The stack is last in, first out (LIFO): values come back in the reverse order.

nasm · try it yourself
section .text
global _start
_start:
    push 10
    push 20
    push 30

    pop rbx                     ; 30, the last one pushed
    mov rdi, rbx
    call print_uint
    pop rbx                     ; 20
    mov rdi, rbx
    call print_uint
    pop rbx                     ; 10
    mov rdi, rbx
    call print_uint

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
30
20
10

Note: In 64-bit mode push and pop always move 8 bytes (16-bit forms exist but are almost never useful). push accepts a 32-bit immediate that is sign-extended to 64 bits.

Reversing with the stack

LIFO order makes the stack a natural tool for reversing things. Push each character of a word, then pop them back into the buffer:

nasm · try it yourself
section .data
word_text:  db "stressed"
word_len    equ $ - word_text
newline:    db 10

section .text
global _start
_start:
    xor ecx, ecx
.push_loop:
    movzx eax, byte [word_text + rcx]
    push rax                    ; one character per 8-byte slot
    inc ecx
    cmp ecx, word_len
    jb .push_loop

    xor ecx, ecx
.pop_loop:
    pop rax                     ; comes back in reverse order
    mov [word_text + rcx], al
    inc ecx
    cmp ecx, word_len
    jb .pop_loop

    mov eax, 1
    mov edi, 1
    mov rsi, word_text
    mov edx, word_len + 1       ; the word and its newline
    syscall

    mov eax, 60
    xor edi, edi
    syscall
desserts

Every push must be matched by a pop (or by adding to rsp). If they don't balance, everything that relies on rsp — especially ret — goes wrong.

Reading the stack without popping

The stack is ordinary memory, so you can address it relative to rsp. [rsp] is the top item, [rsp + 8] the one below it, and so on:

nasm · try it yourself
section .text
global _start
_start:
    push 111
    push 222
    push 333

    mov rdi, [rsp]              ; top: 333
    call print_uint
    mov rdi, [rsp + 16]         ; two slots down: 111
    call print_uint

    add rsp, 24                 ; discard all three at once
    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
333
111

Wait — print_uint itself uses the stack (its call pushes a return address and it reserves 32 bytes). Why are our values still intact? Because everything a function puts on the stack lives below our rsp, and the function restores rsp before returning. Data above rsp is safe; data below it is free space that anyone may overwrite.

Local variables

To get space for local data, subtract from rsp; to free it, add the same amount back. That is exactly how print_uint gets its 32-byte digit buffer. Here a 16-byte buffer is filled and printed:

nasm · try it yourself
section .text
global _start
_start:
    sub rsp, 16                 ; reserve 16 bytes
    mov dword [rsp], 'Stac'     ; NASM stores the characters in order
    mov dword [rsp + 4], 'k ok'
    mov byte [rsp + 8], 10

    mov eax, 1
    mov edi, 1
    mov rsi, rsp
    mov edx, 9
    syscall

    add rsp, 16                 ; release it
    mov eax, 60
    xor edi, edi
    syscall
Stack ok

Alignment

The System V ABI requires rsp to be a multiple of 16 immediately before a call instruction. At _start the kernel provides a 16-byte aligned rsp; each push or call moves it by 8. Functions from C libraries may use SSE instructions that crash on a misaligned stack, so when you call them you must keep track:

nasm · try it yourself
section .text
global _start
_start:
    mov rbx, rsp
    and ebx, 15                 ; rsp mod 16 at _start
    push rax                    ; move rsp by 8
    mov r12, rsp
    and r12d, 15                ; rsp mod 16 after one push
    pop rax

    mov rdi, rbx
    call print_uint             ; 0
    mov rdi, r12
    call print_uint             ; 8

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
0
8

Our own helpers like print_uint don't care about alignment, but the habit pays off once you call C functions (see Linking with C).

The stack has a limit

Linux gives the main thread a stack of 8 MB by default (ulimit -s). Pushing beyond that — typically through endless recursion — hits an unmapped page and ends with SIGSEGV: a stack overflow.

Go further: Stack Frames and the Return Address shows why a frame's layout makes stack buffer overflows dangerous, with a stack-frame lab.

Test yourself

After push rax, how has rsp changed?

  1. It increased by 8
  2. It decreased by 8
  3. It decreased by 1
  4. It is unchanged

You execute push 1, push 2, push 3, then pop rax, pop rbx. What is in rbx?

  1. 1
  2. 2
  3. 3
  4. 0

What alignment must rsp have right before a call according to the System V ABI?

  1. 4 bytes
  2. 8 bytes
  3. 16 bytes
  4. No requirement