Let’s try to write a sample assembly language code and then compile and run it on Linux x86 platform. This code will just print Hello World
. There are several way to write the assembly code. You can find more details here. I have picked one of them.
Programming Using System Calls
64-bit Linux installations use the processor’s SYSCALL instruction to jump into the portion of memory where operating system services are stored. To use SYSCALL, first put the system call number in RAX, then the arguments, if any, in RDI, RSI, RDX, R10, R8, and R9, respectively. In our first example we will use system calls for writing to a file (call number 1) and exiting a process (call number 60). Here it is in the NASM assembly language:
$ cat hello.asm
; ----------------------------------------------------------------------------------------
; Writes "Hello, World" to the console using only system calls. Runs on 64-bit Linux only.
; To assemble and run:
;
; nasm -felf64 hello.asm && ld hello.o && ./a.out
; nasm -f elf64 hello.asm && ld -s -o hello hello.o && ./hello
; ----------------------------------------------------------------------------------------
global _start
section .text
_start: mov rax, 1 ; system call for write
mov rdi, 1 ; file handle 1 is stdout
mov rsi, message ; address of string to output
mov rdx, 13 ; number of bytes
syscall ; invoke operating system to do the write
mov rax, 60 ; system call for exit
xor rdi, rdi ; exit code 0
syscall ; invoke operating system to exit
section .data
message: db "Hello, World", 10 ; note the newline at the end
Install nasm if not available
$ sudo yum install nasm
Compile and Run
$ nasm -f elf64 hello.asm
$ ld -s -o hello hello.o
$ ./hello