Translating GAS to NASM, part 2
February 27, 2021
Chapter 4 covers basic functions, and there’s not a lot to go over - function syntax is very similar between GAS and NASM.
A few things to note:
- GAS uses a new syntax for indexing memory using the base pointer register:
x($ebp)
, where x is an integer number of bytes away from the pointer. NASM uses the same syntax as the previous chapter, withrbp
used in pointer math in square brackets. - Though it’s used throughout the book, the line
.type foo, @function
is not required in GAS. The.type
directive is used to define the type of a symbol (in this case definingfoo
as a function), and is useful for debugging or making a function available in other programs. In NASM, the keywordglobal
is used to make a function available externally. - I mentioned in the last chapter that the push and pop instructions operate on 8 byte chunks, and it’s important to remember that for any interactions with the stack from this chapter onward.
- Since the program’s return value will be stored in
rdi
, I moved data to registers that would target that as an ultimate destination rather thanrax
.
Exercise 3 - Calling a basic function
section .text
global _start
_start:
push 3
push 2
call power
add rsp, 16
push rax
push 2
push 5
call power
add rsp, 16
pop rdi
add rdi, rax
mov rax, 60
syscall
power:
push rbp
mov rbp, rsp
sub rsp, 8
mov rax, [rbp + 16]
mov rcx, [rbp + 24]
mov [rbp - 8], rax
power_loop_start:
cmp rcx, 1
je end_power
mov rbx, [rbp - 8]
imul rbx, rax
mov [rbp - 8], rbx
dec rcx
jmp power_loop_start
end_power:
mov rax, [rbp - 8]
mov rsp, rbp
pop rbp
ret
Exercise 4a - Recursive factorial algorithm
section .text
global _start
_start:
push 4
call factorial
mov rdi, rax
mov rax, 60
syscall
factorial:
push rbp
mov rbp, rsp
mov rax, [rbp + 16]
cmp rax, 1
je end_factorial
dec rax
push rax
call factorial
mov rbx, [rbp + 16]
imul rax, rbx
end_factorial:
mov rsp, rbp
pop rbp
ret
Exercise 4b - Iterative factorial algorithm
This isn’t in the book, but I felt like making an iterative version of the factorial algorithm. For funsies.
section .text
global _start
_start:
push 4
call factorial
mov rdi, rax
mov rax, 60
syscall
factorial:
push rbp
mov rbp, rsp
mov rax, [rbp + 16]
mov rbx, 1
factorial_loop:
cmp rax, 1
je end_factorial
imul rbx, rax
dec rax
jmp factorial_loop
end_factorial:
mov rax, rbx
mov rsp, rbp
pop rbp
ret