../

Subroutines, Macros And Defining Values With EQU In NASM

Subroutines

Sample Program

section .data
        text db "Hello World!",10,0
        text2 db "Arigato",10,0
section .text
        global _start

_start:
        mov rax, text
        call _print

        mov rax, text2
        call _print

        mov rax, 60
        mov rdi, 0
        syscall

;input: rax as pointer to string
;output: print string at rax
;rbx = counter of the loop
_print:
        push rax
        mov rbx, 0
_printloop:
        inc rax
        inc rbx
        mov cl, [rax]
        cmp cl, 0
        jne _printloop

        mov rax,1
        mov rdi,1
        pop rsi
        mov rdx, rbx
        syscall
        ret

Macros

A macro is a single instruction that expands into a predefined set of instructions to perform a particular task.

Defining Macros

%macro <name> <argc>
    ...
    <macro body>
    ...
%endmacro

Defining Values With EQU

EQU is used for defining constants for future use.

<name> equ <value>

Sample Program

STDIN equ 0
STDOUT equ 1
STDERR equ 2

SYS_READ equ 0
SYS_WRITE equ 1
SYS_EXIT equ 60

section .data
        digit db 0,10

section .text
        global _start

%macro exit 0
        mov rax, SYS_EXIT
        mov rdi, 0
        syscall
%endmacro


%macro printdigit 1
        mov rax, %1
        call _printraxdigit
%endmacro


%macro printdigitsum 2
        mov rax, %1
        add rax, %2
        call _printraxdigit
%endmacro

_start:
        printdigit 49
        printdigit 50

        printdigitsum 49, 51

        exit

_printraxdigit:
        ;mov rax, 50
        mov [digit], al
        mov rax, SYS_WRITE
        mov rdi, STDOUT
        mov rsi, digit
        mov rdx, 2
        syscall
        ret

Tags: /assembly/ /subroutines/ /macros/ /nasm/ /64-bit/ /equ/