Nested Calls
Part of the Functions, Stack and Strings section of Coddy's Assembly journey. Lesson 8 of 33.
A helper can call another helper. Here cube calls square and multiplies the result by rdi once more:
; cube: rax = rdi * rdi * rdi
cube:
call square ; rax = rdi * rdi
imul rax, rdi
retEach call pushes its own return address, so the addresses stack up, the newest on top. When solve calls cube and cube calls square:
; rsp = 1000 in solve
call cube ; rsp = 992: back to solve
; in cube
call square ; rsp = 984: back to cubeThe returns happen in reverse order. square's ret pops the top address and lands back in cube (rsp = 992). Then cube's ret pops the next one and lands back in solve (rsp = 1000).
This chain works only if each procedure leaves the stack as it found it: when a ret runs, its own return address must be on top. The harness's call solve is the bottom of the chain, so while square runs, three return addresses are on the stack.
Challenge
EasyThe starter has square (rax = rdi * rdi). Write cube, which calls square and returns rdi * rdi * rdi in rax. solve receives n (-1000 to 1000) in rdi and returns the cube of n in rax by calling cube.
Example: for the input 2 the program prints 8.
Write your code in solution.asm. The locked main.asm reads the input, calls solve and prints the number in rax.
Try it yourself
bits 64
section .bss
input_buffer resb 256
output_buffer resb 32
values resq 4
section .text
global _start
extern solve
_start:
xor eax, eax
xor edi, edi
mov rsi, input_buffer
mov edx, 255
syscall
test rax, rax
jle .loaded
mov rsi, input_buffer
lea rdi, [input_buffer + rax]
xor ecx, ecx
.scan:
cmp rsi, rdi
jae .loaded
cmp ecx, 4
jae .loaded
movzx eax, byte [rsi]
cmp al, 32
jbe .space
mov r10, 1
cmp al, '-'
jne .number
mov r10, -1
inc rsi
.number:
xor eax, eax
.digit:
cmp rsi, rdi
jae .store
movzx edx, byte [rsi]
cmp dl, '0'
jb .store
cmp dl, '9'
ja .store
imul rax, rax, 10
sub edx, '0'
add rax, rdx
inc rsi
jmp .digit
.store:
imul rax, r10
mov [values + rcx * 8], rax
inc ecx
.space:
inc rsi
jmp .scan
.loaded:
mov rdi, [values]
mov rsi, [values + 8]
mov rdx, [values + 16]
mov rcx, [values + 24]
xor eax, eax
call solve
lea rsi, [output_buffer + 31]
mov byte [rsi], 10
mov ecx, 1
xor r8d, r8d
test rax, rax
jns .positive
mov r8d, 1
neg rax
.positive:
mov r9d, 10
.convert:
xor edx, edx
div r9
add dl, '0'
dec rsi
mov [rsi], dl
inc ecx
test rax, rax
jnz .convert
test r8d, r8d
jz .write
dec rsi
mov byte [rsi], '-'
inc ecx
.write:
mov edx, ecx
mov eax, 1
mov edi, 1
syscall
.exit:
mov eax, 60
xor edi, edi
syscallAll lessons in Functions, Stack and Strings
4Stack Frames and Recursion
Local VariablesFrames with RBPRecursionTwo Recursive CallsRecap: Digit Sum3The Calling Convention
Arguments in RegistersReturn ValuesCaller-Saved RegistersCallee-Saved RegistersRecap: Scoreboard6Project: Word Counter
The Read SyscallCount the CharactersPractice on your own: Assembly playground