A program is rarely one straight run of instructions — it is built from functions that call each other. This challenge is about doing that correctly: splitting code into a function and calling it the way the rest of the system expects, following the System V convention from Stack & Calls.
Define a function that takes one integer argument and returns a value, then call it from _start, passing a single argument. Honor the calling convention — argument in rdi, return value in rax — and use the returned value as the program's exit status so you can verify it from the shell.
Open one hint at a time before reading the walk-through.
rdi, and the return value comes back in rax. That is the whole contract between caller and callee (Stack & Calls).call pushes the return address and jumps to the function; ret pops it back so execution resumes after the call. Put the function body after _start exits, so control never falls into it by accident.rax into rdi and call exit — then read it back with echo $?.Let the function be times_two(n), returning n * 2. In _start, load the argument into rdi (here 21) and call times_two. By the convention the function will leave its answer in rax, so move rax into rdi and exit with it.
The function itself is three instructions: copy the incoming argument out of rdi into rax, double it with add rax, rax, and ret. Because _start exits with its own syscall before the function's address, control only ever reaches times_two through the call. Watch the argument arrive and the result come back:
break times_twoBreakpoint 1 at 0x401014runBreakpoint 1, 0x0000000000401014 in times_two ()p/d $rdi$1 = 21break *0x40101aBreakpoint 2 at 0x40101acontinueBreakpoint 2, 0x000000000040101a in times_two ()p/d $rax$2 = 42At the function's entry rdi holds 21 — the argument, exactly where the convention says it will be. By the ret, rax holds 42, the doubled result ready for the caller to use.
1section .text
2 global _start
3_start:
4 mov rdi, 21 ; first argument in rdi
5 call times_two ./fn; echo $?4242 is 21 * 2 — the argument went in through rdi, the function returned its answer in rax, and the caller used it. That round trip is every function call on the platform, in miniature.