Nasm Code Examples: Learn With Practical Snippets
Developing in assembly language allows you to have absolute control over your code, but it can be daunting at first. NASM (Netwide Assembler) is a popular choice among assemblers, thanks to its flexibility and power. Let's dive into some NASM code examples to help you get started.
In this article, we'll explore the basics of NASM, starting with simple assembly instructions and then moving on to more complex code. By the end, you'll have a solid foundation in NASM programming, ready to tackle more advanced topics.
Setting Up and Hello World
First, ensure you have NASM installed on your system. If not, you can download it from the official website (nasm.us).
Let's start with the classic "Hello, World!" program to confirm that everything is working correctly.
Hello World in NASM
Create a new file, let's call it 'hello.asm'. Here's how you can print "Hello, World!" in NASM:
mov eax, 4
mov ebx, 1
mov ecx, hello_len
mov edx, hello_msg
mov eax, 0x4
int 0x80
mov eax, 1
int 0x80
hello_msg:
db 'H', 'e', 'l', 'l', 'o', ', ', 'W', 'o', 'r',
hello_len equ $-hello_msg
Compiling and Running
To compile the 'hello.asm' file, use the following command in the terminal:
nasm -f elf32 hello.asm -o hello.o
Then, link the object file with GCC to create an executable:
ld -m elf_i386 -o hello hello.o
Finally, run the program with:
./hello
You should see "Hello, World!" printed on the screen.
Working with Data
Now that we've covered the basics let's explore how to work with data in NASM.
NASM uses the data segment for storing global and static data, and the bss segment for storing uninitialized data.
Integers and Characters
You can initialize integers and characters directly in the data segment. Here's an example:
section .data
msg:
db 'Hello, World!'
len equ $-msg
num
dd 42
Working with Strings
NASM uses the 'db' directive for byte values and 'dd' for double words (32 bits or 4 bytes). You can also use the 'times' directive to repeat a value:
section .data
msg:
db 'Hello, World!'
times 20
db 0
This will create a null-terminated string with a maximum length of 21 characters.
Moving On to Functions
ASM functions follow a specific calling convention. In NASM, we'll use the Linux System Call convention, where parameters are passed in registers:
syndic
Here's a simple function that prints a message and returns a value:
section .text
global _start
_start:
call my_func
mov eax, 1
int 0x80
my_func:
mov eax, 4
mov ebx, 1
mov ecx, msg_len
mov edx, msg
mov eax, 0x4
int 0x80
ret
msg:
db 'This is a function!'
msg_len equ $-msg
Assembly programming might seem overwhelming at first, but with practice and understanding, you can achieve great things. This concludes our NASM code examples guide. Now it's your turn to dive deeper, explore more complex topics, and start coding in NASM!