Unit #4-04
Learning Outcome
At the end of this lesson, you will be able to:
understand how to use functions
understand how to use the stack
Review
printing out characters
Lesson
go over functions
call and return
go over the stack
push and pop
Activity
nil
Daily Assignment
recreate the program below
the first 7 numbers in the fibonacci sequence
use this algorithm
use my PrintSingleDigitInt function to print the numbers out
HINT: I used registers for all the variables, made my life a lot easier!
Function and stack
Output for today's assignment, the first 7 numbers in the fibonaci sequence
; --------------------------------------------------------------
; Created by: Mr Coxall
; Created on: Sep 2022
; Writes out a number to STDOUT.
; Runs on 64-bit x86 Linux only.
; --------------------------------------------------------------
section .bss
someNumber: RESD 1 ; 4 bytes
section .data
; constants here
newLine: db 10 ; UNICODE 10 is new line character
done: db 10, "Done.", 10 ; string to print
doneLen: equ $-done ; length of string
section .text
global _start ; entry point for linker
_start: ; start here
mov r8, -1 ; move the integer 0 into r8
mov r9, 9 -1 ; move the integer 9 into r9
IncrementLabel:
; doing a do ... while loop!
inc r8
push r8
call PrintSingleDigitInt ; call our print single digit function
add rsp, 4 ; pop but throw away the value
cmp r8, 9-1 ; compare r8 and ascii 9
jle IncrementLabel ; jump if <= goto "LoopLable"
; write done to screen
mov rax, 1 ; system call for write
mov rdi, 1 ; file handle 1 is stdout
mov rsi, done ; address of string to output
mov rdx, doneLen ; number of bytes
syscall ; invoke operating system to do the write
mov rax, 60 ; system call for exit
mov rdi, 0 ; exit code 0
syscall ; invoke operating system to exit
PrintSingleDigitInt:
; takes in a single digit int and prints the assci equivalent
; when a function is called, the return value is placed on the stack
; we need to keep this, so that we can return to the corret place in our program!
pop r14 ; pop the return address to r9
pop r15 ; pop the "parameter" we placed on the stack
add r15, 48 ; add the ascii offset
push r15 ; place it back onto the stack
; write value on the stack to STDOUT
mov rax, 1 ; system call for write
mov rdi, 1 ; file handle 1 is stdout
mov rsi, rsp ; the string to write popped from the top of the stack
mov rdx, 1 ; number of bytes
syscall ; invoke operating system to do the write
;add $8, %rsp # restore sp -> not sure this is neede!
; https://stackoverflow.com/questions/8201613/printing-a-character-to-standard-output-in-assembly-x86
; print a new line
mov rax, 1 ; system call for write
mov rdi, 1 ; file handle 1 is stdout
mov rsi, newLine ; address of string to output
mov rdx, 1 ; number of bytes
syscall ; invoke operating system to do the write
push r14 ; put the return address back on the stack to get back
ret ; return