w1coding.comAll tutorials

Assembly Functions

Assembly lessons
  1. Environment Setup
  2. Introduction
  3. Syntax
  4. Datamovement
  5. Operators
  6. Control
  7. Loops
  8. Interupts
  9. Functions
  10. Memory
  11. System
  12. Debugging
  13. Macros
  14. Execution
  15. Floating
  16. Interupts
  17. Optimization
  18. Linking
  19. Inline
  20. Registers
  21. Bootloader
  22. Macros
  23. Stack
  24. Call
  25. Technique
  26. Responsive

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.