Resources for assembly

by Fredrik Daneby

The links and code snippets provided here are specific to assembly language aimed for the Intel x86-64 architecture using the NASM assembler. Linking is done using GNU LD on Ubuntu Linux or by using the GNU C compiler (GCC). Considering the difficulty of reading assembly code, the snippets are quite short. The idea is to, as simply as possible, illustrate basic concepts that I find important and interesting in order to learn while coding.

Useful links

The GNU compiler collection[ https://gcc.gnu.org/ ]
The GNU debugger[ https://sourceware.org/gdb/ ]
GNU ld (Binutils)[ https://sourceware.org/binutils/docs-2.27/ld/index.html ]
ELF and ABI standards[ https://refspecs.linuxfoundation.org/elf/index.html ]
DWARF debugging standard website[ https://dwarfstd.org/ ]
Using LD, the GNU linker[ https://ftp.gnu.org/old-gnu/Manuals/ld-2.9.1/html_node/ld_toc.html ]
NASM - The Netwide Assembler[ https://www.nasm.us/doc/ ]
A NASM tutorial[ https://cs.lmu.edu/~ray/notes/nasmtutorial/ ]
Intel 64 and IA-32 developer manuals[ https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html ]
Linux system call table[ https://www.chromium.org/chromium-os/developer-library/reference/linux-constants/syscalls/ ]
Basic assembler debugging with GDB (GNU debugger)[ http://dbp-consulting.com/tutorials/debugging/basicAsmDebuggingGDB.html ]
Compiler explorer[ https://godbolt.org/ ]

Snippets

Bash scripts for running examples

Debug (When there is no output)

#!/bin/bash
################################################################################
# Date: 2025-05-29
# Author: Fredrik Daneby
#
# A small script to assemble, build and debug an assembly file using NASM, GCC
# and GDB. The filename will be stripped of extension, if present.
#
# Usage:
#            $bash debug.sh [filename]
################################################################################

# First parameter must not be zero length
if [ -n "$1" ]
 then

    # Strip file extension
    base=$(basename "$1" .asm)

    ### Assemble (and generate DWARF debug info)

    cmdline="nasm -f elf64 -gdwarf $base.asm"
    echo "Assemble: [ $cmdline ]"                       
    $cmdline                                    


    ### Build

    cmdline="gcc -fverbose-asm -no-pie -m64 -g -o $base $base.o"
    echo "Build: [ $cmdline ]"
    $cmdline

    ### Debug

    cmdline="gdb $base"
    echo "Debug: [ $cmdline ]"
    $cmdline

else
    echo "Sorry. Can not continue without a filename."
fi

Run (When there is output)

#!/bin/bash
################################################################################
# Date: 2025-05-29
# Author: Fredrik Daneby
#
# A small script to assemble, link and run an assembly file using NASM and LD.
# Filename will be stripped of extension, if present.
#
# Usage:
#            $bash run.sh [filename]
################################################################################

# First parameter must not be zero length
if [ -n "$1" ]
 then

    # Strip file extension
    base=$(basename "$1" .asm)

    ### Assemble

    cmdline="nasm -f elf64 -o $base.o $base.asm"    
    echo "Assembling: [$cmdline]"                   
    $cmdline                                        

    ### Link

    cmdline="ld -static -o $base  $base.o"          
    echo "Linking: [$cmdline]"                      
    $cmdline                                        

    ### Execute

    echo "Excuting..."
    ./$base

else
    echo "Sorry. Can not continue without a filename."
fi

Program flow

A minimal program

; A minimal assembly program

; Suggestion of GDB commands to view the outcome
; ==============================================================================
; (gdb) layout asm                 
; (gdb) break _start
; (gdb) run
; (gdb) display $rax
; (gdb) display $rdi
; (gdb) step
; [repeat step as necessary]
; ==============================================================================

section .text

	GLOBAL _start		; An assembler directive defining _start as 
				; a global symbol which may be included in 
				; other modules (by using EXTERN). 

_start:				; _start begins here

	mov     rax, 0x3c	; System call to _exit on Linux x86-64
	mov     rdi, 0		; Exit value 0
	syscall			; Invoke system call (in RAX)

A minimal program with a label

; A minimal assembly program - extended with a label for exit

; Suggestion of GDB commands to view the outcome
; ==============================================================================
; (gdb) layout asm                 
; (gdb) break _start
; (gdb) run
; (gdb) display/1wx $rsp
; (gdb) step
; [repeat step as necessary]
; ==============================================================================

section .text

	GLOBAL _start

exit:				; A label for the exit procedure

	mov     rax, 0x3c               
	mov     rdi, 0                  
	syscall                         

_start:
				; Note that RSP holds ARGC (number of 
				; command line arguments)
	jmp exit    		; Jump to the adress where the symbol exit
				; is found. Note that the value at RSP
				; does not change upon jumping

A minimal program with a call

; A minimal assembly program - extended with a label for exit - function call

; Suggestion of GDB commands to view the outcome
; ==============================================================================
; (gdb) layout asm                 
; (gdb) break _start
; (gdb) run
; (gdb) display/1wx $rsp
; (gdb) step
; [repeat step as necessary]
; ==============================================================================

section .text

	GLOBAL _start

exit:                               

	mov     rax, 0x3c               
	mov     rdi, 0                  
	syscall             	; Program exit before return (the value at 
				; RSP is never used)                

_start:

	call exit		; Call exit as a function. Push return 
				; adress to stack (RSP points to return 
				; adress)

A minimal program with a function call using ret

; An assembly program - function call to sum with ret

; Suggestion of GDB commands to view the outcome
; ==============================================================================
; (gdb) layout asm
; (gdb) break _start
; (gdb) run 1 2
; (gdb) display $rcx
; (gdb) display/1wx $rsp
; (gdb) step
; [repeat step as necessary]
; ==============================================================================

section .text

	GLOBAL _start

sum:				; A function to add two numbers
				; Note that the value at RSP now holds the
				; adress to exit

	mov     rcx, 10		; Directly modify RCX
	add     rcx, 5		; Add 5 to RCX

	ret                 	; Return. This pops the return adress from
				; stack and RSP points to the original 
				; value (ARGC, which is 3 if program was run
				; as suggested)

exit:                               

	mov     rax, 0x3c               
	mov     rdi, 0                  
	syscall                                         

_start:

	call sum		; Call function to add numbers
	call exit

A simple loop

; An assembly program - simple loop and exit

; Suggestion of GDB commands to view the outcome
; ==============================================================================
; (gdb) layout asm                 
; (gdb) break _start
; (gdb) run
; (gdb) display $ps           <-- EFLAGS register (ZF == zero)
; (gdb) display $rcx
; (gdb) step
; [repeat step as necessary]
; ==============================================================================

section .text

    GLOBAL _start


_start:
	mov     rcx, 10            ; RCX will hold the iterator counter

continue:
	cmp     rcx, 0             ; Set zero flag if RCX == 0
	jz      break              ; If zero flag is set, jump to "break"
	dec     rcx                ; Otherwise, decrease RCX by 1
	jmp     continue           ; Iterate

break:
	call    exit

exit:                               
	mov     rax, 0x3c               
	mov     rdi, 0                  
	syscall

Simple Input/Output

Write output

; An assembly program - write output

; Suggestion of GDB commands to view the outcome
; ==============================================================================
; (gdb) break _start
; (gdb) run
; (gdb) x/14xc &str             <-- View the string in variable str
; (gdb) display $rax
; (gdb) display $rdi
; (gdb) step
; [repeat step as necessary]
; ==============================================================================

section .data               	     ; Data section

	str: db  "Hej vaerlden!", 10 ; Declare initialized data (string)
	strlen equ $-str             ; Label strlen is given the length
				     ; of the string declared by "str"

section .text                    

    GLOBAL _start

write:
	mov     rax, 0x01            ; System call to write()
	mov     rdi, 0x01            ; Write to STDOUT
	mov     rsi, str             ; Pointer to string
	mov     rdx, strlen          ; Number of bytes to write
	syscall                      ; Invoke system call (in rax)    
				     ; NOTE: No ret. Fallthrough to exit code

exit:                               

	mov     rax, 0x3c               
	mov     rdi, 0                  
	syscall                         

_start:
	call write
	call exit

Read input and echo output

; An assembly program - read input and echo

; Run this program directly (run.sh)
; Note that the program is naive and does not check if input fits in buffer

section .data                       ; Data section

    question:   db      "Please, input a color: "
    questionlen equ     $-question        

section .bss                        	; Section for uninitialized data

	input:      resb    255         ; Reserve 255 bytes for the input

section .text                    

    GLOBAL _start

ask:
	mov         rax, 0x01           ; Write
	mov         rdi, 0x01           ; STDOUT
	mov         rsi, question       ; data                  
	mov         rdx, questionlen    ; Length of data
	syscall                         
	ret

read:
	mov         rax, 0x00           ; Read
	mov         rdi, 0x00           ; STDIN
	mov         rsi, input          ; Buffer for input (max 255 bytes)
	syscall 
	ret

echo:
	mov         rax, 0x01           ; Write
	mov         rdi, 0x01           ; STDOUT
					; Pointer to data is already in RSI
	mov         rdx, 255            ; Length of data
	syscall
	ret

exit:                               

	mov     rax, 0x3c               
	mov     rdi, 0                  
	syscall                         

_start:
	call ask
	call read
	call echo
	call exit

Mixed

Comparing two numbers

; Compare two numbers

; Manually change RBX or RCX to test outcome
; To run without debug, use run.sh 

; Suggestion of GDB commands to view the outcome
; ==============================================================================
; (gdb) break _start
; (gdb) run
; (gdb) display $ps
; (gdb) step
; [repeat step as necessary]
; ==============================================================================

section .data

    rbx_str: db     "RBX is larger", 10  
    rbx_strlen  equ $-rbx_str
                            
    rcx_str: db     "RCX is larger", 10
    rcx_strlen  equ $-rcx_str

    equal_str: db     "RBX and RCX are equal", 10
    equal_strlen  equ $-equal_str

section .text

    GLOBAL _start


compare:                          	; Compare RBX and RCX using subtract

	mov     rbx, 11                 ; Manually change these values to test
	mov     rcx, 11
	sub     rcx, rbx                ; Subtract sets conditional flags
    
	js      rbx_larger              ; Signed flag (SF) is set (RCX is negative)
	je      rbx_rcx_equal           ; Zero flag (ZF) is set. Equal values
	jmp     rcx_larger              ; Otherwise, RCX must be larger
	
	; Load the correct output string
	
	rbx_larger:
		mov     rsi, rbx_str
		mov     rdx, rbx_strlen
		jmp     write		; Jump to write

	rbx_rcx_equal:
		mov     rsi, equal_str
		mov     rdx, equal_strlen
		jmp     write

	rcx_larger:
		mov     rsi, rcx_str
		mov     rdx, rcx_strlen
		jmp     write           ; Just for consistency

	write:
		mov     rax, 0x01       ; System call to write()
		mov     rdi, 0x01       ; Write to STDOUT
		syscall                 ; Invoke system call (in rax)

	ret                     	; NOTE: This is the ret for compare

exit:                               

	mov     rax, 0x3c               
	mov     rdi, 0                  
	syscall         

_start:

    call compare 
    call exit

Calling C functions

atoi, puts, printf

; This program takes two command line arguments, converts them to integers, adds
; them together and outputs the result

; ==============================================================================
; (gdb) break main
; (gdb) break checkpoint1
; (gdb) break checkpoint2
; (gdb) break checkpoint3
; (gdb) run 1 2
; (gdb) x/3xg $rsi              <-- Pointers to argv[0], argv[1], argv[2]
; (gdb) p *(char **)($rsi)      <-- argv[0] (string)
; (gdb) p *(char **)($rsi+8)    <-- argv[1] (string eq "1")
; (gdb) p *(char **)($rsi+16)   <-- argv[1] (string eq "2")
; (gdb) display $rdi            <-- argc is in RDI
; (gdb) display $rax            <-- return value from atoi()
; (gdb) display $r12            <-- argv[1]             
; (gdb) display $r13            <-- argv[2]
; (gdb) continue
; [repeat continue as necessary]
; ==============================================================================

section .data

    output:         db  "The answer is %d", 10, 0
    argc_errmsg:    db  "Error: Please supply two command-line argument", 10, 0
    atoi_errmsg:    db  "Error: atoi() failed", 10, 0

section .text

    GLOBAL main
    extern atoi
    extern puts
    extern printf

main:          
    push rbp

    cmp rdi, 3                  ; Two command-line arguments are required
    jne argc_error

    mov r12, [rsi+8]            ; Store argv[1]
    mov r13, [rsi+16]           ; Store argv[2]

    mov rdi, r12                ; argv[1]
    call atoi                   ; atoi() uses RDI as input. Result is in RAX

checkpoint1:                    ; atoi(argv[1]) has completed

    cmp rax, 0                  ; Check return value from atoi() (0 == fail)
    je  atoi_fail
    mov r12, rax                ; Store the argv[1] integer in R12 again

    mov rdi, r13                ; argv[2]
    call atoi

checkpoint2:                    ; atoi(argv[2]) has completed

    cmp rax, 0
    je  atoi_fail

checkpoint3:                    ; printf setup

print:                          ; Print results

    add r12, rax                ; Add the two values
    mov rdi, output             ; Move output string pointer to RDI
    mov rsi, r12                ; Move result to RSI for output
    mov rax, 0                  
    call printf                 
    mov rax, 0                  ; Exit success
    jmp done

argc_error:
    mov rdi, argc_errmsg
    call puts
    mov rax, 1                  ; Exit failure
    jmp done

atoi_fail:
    mov rdi, atoi_errmsg
    call puts
    mov rax, 2                  ; Exit failure
    jmp done

done:

exit:
    pop rbp
    ret