09-23-25 Lab 8
Hello world! in assembly:
section .data
msg db "Hello, world!", 10 ; Our string, including a newline character (ASCII 10)
len equ $ - msg ; Length of the string
section .text
global _start ; Entry point for the linker
_start:
; Write "Hello, world!" to standard output
mov rax, 1 ; syscall number for sys_write (1)
mov rdi, 1 ; File descriptor for standard output (1)
mov rsi, msg ; Address of the string to write
mov rdx, len ; Length of the string
syscall ; Invoke the kernel
; Exit the program
mov rax, 60 ; syscall number for sys_exit (60)
mov rdi, 0 ; Exit status (0 for success)
syscall ; Invoke the kernel
Explanation:
-
.section .data:
This section declares initialized data.msg db "Hello, world!", 10: Defines a byte string namedmsgcontaining "Hello, world!" followed by a newline character (ASCII 10).len equ $ - msg: Defines a constantlenwhich calculates the length of themsgstring.$represents the current address.
-
.section .text:
This section contains the executable code.global _start: Makes the_startlabel visible to the linker, marking it as the program's entry point.
-
_start::
The program's entry point.mov rax, 1: Loads the system call number forsys_write(which is 1) into theraxregister.mov rdi, 1: Loads the file descriptor for standard output (which is 1) into therdiregister.mov rsi, msg: Loads the memory address of ourmsgstring into thersiregister.mov rdx, len: Loads the length of ourmsgstring into therdxregister.syscall: Executes the system call, using the values inrax,rdi,rsi, andrdxas arguments.mov rax, 60: Loads the system call number forsys_exit(which is 60) into theraxregister.mov rdi, 0: Loads the exit status (0 for success) into therdiregister.syscall: Executes the system call to terminate the program.
Install NASM asembler:
sudo apt-get install nasm
Save the code as hello.asm and Assemble the code using NASM.
nasm -f elf64 -o hello.o hello.asm
Link the object file to create an executable:
ld -o hello hello.o
Run the executable
./hello
Jump table
...
Jump example code
With bug:
section .txt
global _start
_start:
mov eax, 3
mov ebx, 2
cmp eax, ebx
JL lesser
lesser:
mov ecx, 1
INT 80h
# What is the bug here?
# We want to go to the next instruction
# only if one is less than the other one.
Fixed:
section .txt
global _start
_start:
mov eax, 3
mov ebx, 2
cmp eax, ebx
JL lesser
JMP end
lesser:
mov ecx, 1
INT 80h
end:
INT 80h
Use gdb to debug assembly
Break at my _start
(gdb) break _start_
Go to the next assembly instruction
(gdb) stepi
- Try changing numbers in the code, comparing them and see on
gdbhow these change as well.