FIRST PROGRAM

Why NASM?

NASM offers a simplified syntax compared to the more complex AT&T syntax, commonly used on Linux systems. It’s designed to be more approachable for beginners while still providing all the necessary skills for x86 programming.


Setting up NASM

Install nasm on a Linux system, as it’s the most compatible environment for assembly programming.

sudo apt update
sudo apt -y install nasm

-y flag automatically confirms installation prompts.

Create a new file with a .s, .as, or .asm extension, such as first.s.


Program Structure

  • Divide the program into sections:
    • section .data stores variables used in the program;
    • section .text contains the actual code of the program;
section .data

section .text

Starting Execution

  • Use the global _start directive to declare the entry point of the program;
  • Define a label _start: to mark the beginning of the program execution;
global _start

_start:

Writing Code

  • Use the mov instruction to move data between locations, such as registers;
  • Example: mov eax, 1 moves the value 1 into the eax register;
  • I can move static values into registers for manipulation;
  • move destination, source;
mov eax, 1

Ending the Program

  • To terminate the program, use an interrupt instruction int;
  • Specify the desired action in the eax register;
  • For example, mov eax, 1 indicates the exit system call;
  • Set the exit status code in the ebx register;
  • Execute the interrupt with int 0x80 (hexadecimal value 80);
mov eax, 1
mov ebx, 0
int 0x80

Example Code

section .data

section .text
    global _start

_start:
    mov eax, 1
    mov ebx, 0
    int 0x80

Compiling and Running with NASM

Use nasm to compile the assembly code into an object file .o:

nasm -f elf -o first.o first.s

Link the object file to create an executable:

ld -m elf_i386 -o first first.o

-m elf_i386 flag specifies the target architecture. 32 bits for x86.

Execute the program and verify the exit status code:

./first
echo $?

Debugging with GDB

  • Use GDB (GNU Debugger) for debugging assembly programs. Also works with C and C++;
  • Set breakpoints and step through the program to observe execution;

Start GDB and load the executable.

gdb first

Here are some useful GDB commands:

Command Description
layout asm Switch to assembly view.
break _start Set a breakpoint at the start label.
run Start program execution.
stepi Step through one assembly instruction at a time.
info registers View register values.

I have available a detailed GDB cheatsheet here.