Menu
CoddyTech

Saving a Register

Part of the Functions, Stack and Strings section of Coddy's Assembly journey. Lesson 3 of 33.

A program has few registers. When you need a register for a new job but its value matters later, push it, do the job, and pop it back.

push rdi        ; keep the input
mov rdi, 10     ; rdi has a new job
add rax, rdi
pop rdi         ; rdi holds the input again

Save before the register changes, restore after its new job ends. The value waits on the stack in between, and nothing else in your code touches it as long as every later push has its own pop.

Several saved registers come back in reverse order. Pop the last one you pushed first:

push rdi
push rsi
; ... use rdi and rsi ...
pop rsi
pop rdi

Count your pushes and pops: before ret they must match. A value left on the stack breaks ret, as chapter 2 shows.

challenge icon

Challenge

Easy

solve receives a number n (1 to 100) in rdi. Add 1 + 2 + ... + n with a loop that uses rdi as its counter and counts it down to 0. Save rdi with push before the loop and get it back with pop after it. Return the sum times the original n in rax.

Example: for the input 3 the program prints 18.

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
    syscall

All lessons in Functions, Stack and Strings

Practice on your own: Assembly playground