Functions and Procedures
Functions in assembly are blocks of reusable code. They can be implemented using labels and the call and ret instructions.
Steps to Create a Function
- Define the function with a label.
- Use
callto invoke the function. - Use
retto return control to the caller.
Example: Simple Function
section .text
global _start
_start:
call my_function ; Call the function
mov rax, 60 ; Exit system call
xor rdi, rdi ; Exit code: 0
syscall
my_function:
; Your function code here
ret ; Return to the caller
Example: Adding Two Numbers in a Function
section .text
global _start
_start:
mov rdi, 5 ; First parameter
mov rsi, 10 ; Second parameter
call add_numbers ; Call the function
mov rax, 60 ; Exit system call
xor rdi, rdi ; Exit code: 0
syscall
add_numbers:
add rdi, rsi ; Add the two numbers
ret ; Return with the result in rdi
This program demonstrates passing parameters and returning results in registers.