Procedures
CALL and RET
CALL pushes the return address and jumps to the procedure. RET pops the return address and jumps back to it. Together they nest calls to any depth:
call double_it ; rax now holds the result jmp done double_it: add rax, rax ret done:
Stack frames
A procedure that needs locals builds a frame: save RBP, copy RSP into RBP, reserve space with SUB, and unwind with the mirror image in reverse:
my_proc: push rbp mov rbp, rsp sub rsp, 32 ; ... body ... mov rsp, rbp ; or LEAVE pop rbp ret
The calling convention
On Linux x86-64 (System V ABI), integer arguments arrive in RDI, RSI, RDX, RCX, R8, R9, and the return value leaves in RAX. RBX, RBP, and R12-R15 are callee-saved: use them, but save and restore them first.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does CALL push onto the stack?
Answer
The address of the next instruction
RET needs to know where to continue, so CALL saves that address.
-
What does RET do?
Answer
It pops the return address and jumps to it
RET takes the saved address from the top of the stack and continues there.
-
Which register holds the return value of a function in the System V ABI?
Answer
RAX
RAX carries the return value, as it carries a syscall result.
-
Which registers hold the first two integer arguments on Linux x86-64?
Answer
RDI and RSI
The first six arguments go in RDI, RSI, RDX, RCX, R8 and R9.
-
Which registers are callee-saved?
Answer
RBX, RBP, R12-R15
A procedure that uses RBX, RBP or R12-R15 must restore them before it returns.
-
In a frame, in which order do the steps run?
Answer
Push RBP, mov RBP to RSP, sub RSP
Save the old frame pointer, set the new base, then reserve the locals.
-
What does this program print?
default rel section .data digit db "0", 10 section .text global _start _start: mov rax, 3 call double_it add al, "0" mov [digit], al mov rax, 1 mov rdi, 1 mov rsi, digit mov rdx, 2 syscall mov rax, 60 xor rdi, rdi syscall double_it: add rax, rax retAnswer
6
The procedure doubles 3 to 6, and 6 becomes the digit 6.
-
What does this program print?
default rel section .data msg db "R", 10 section .text global _start _start: call emit mov rax, 60 xor rdi, rdi syscall emit: mov rax, 1 mov rdi, 1 mov rsi, msg mov rdx, 2 syscall retAnswer
R
The procedure writes the message once and returns to _start, which exits.
-
Why save RBP at the start of a procedure that builds a frame?
Answer
The caller may use its own frame pointer
RBP is callee-saved, so the old value comes back when the frame is unwound.
-
What unwinds a frame that pushed RBP and subtracted 32 from RSP?
Answer
Add 32 to RSP, then pop RBP
The exit is the entrance in reverse: restore RSP, then restore RBP.
The snippets on this page are fragments, not whole programs: they show CALL, RET and the frame layout. They were assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev