functions

Functions and Procedures in Assembly

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

  1. Define the function with a label.
  2. Use call to invoke the function.
  3. Use ret to 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.