Functions in Assembly Language

Functions are central in Assembly. We’ll learn about functions with a few different examples.

section .text
global _start

; Here's a function that takes two integers and returns their sum
plus:
    ; Function parameters are passed on the stack
    push ebp
    mov ebp, esp
    mov eax, [ebp+8]  ; First parameter
    add eax, [ebp+12] ; Second parameter
    pop ebp
    ret

; A function that takes three parameters and returns their sum
plusPlus:
    push ebp
    mov ebp, esp
    mov eax, [ebp+8]  ; First parameter
    add eax, [ebp+12] ; Second parameter
    add eax, [ebp+16] ; Third parameter
    pop ebp
    ret

_start:
    ; Call the plus function
    push 2
    push 1
    call plus
    add esp, 8  ; Clean up the stack

    ; Print the result (this is simplified, actual printing would require more code)
    ; ... printing code here ...

    ; Call the plusPlus function
    push 3
    push 2
    push 1
    call plusPlus
    add esp, 12 ; Clean up the stack

    ; Print the result (simplified)
    ; ... printing code here ...

    ; Exit the program
    mov eax, 1
    xor ebx, ebx
    int 0x80

In Assembly, functions are implemented using labels and the call instruction. Parameters are typically passed on the stack, and the result is often returned in a register (commonly eax for 32-bit x86 assembly).

The plus function takes two integers from the stack and returns their sum in eax. The plusPlus function similarly takes three integers and returns their sum.

In the _start section (equivalent to main in higher-level languages), we call these functions by pushing the arguments onto the stack in reverse order and then using the call instruction.

Note that Assembly requires manual stack management. After each function call, we need to clean up the stack by adding to esp the total size of the pushed parameters.

Printing in Assembly is more complex and typically involves system calls, so it’s simplified in this example. In a real program, you’d need to implement the printing logic separately.

Assembly doesn’t have built-in support for string formatting like fmt.Println. You would need to implement such functionality yourself or use system calls for output.

This example demonstrates the basic structure of functions in Assembly, but keep in mind that working with Assembly requires careful management of the stack, registers, and memory.