Introduction
Writing assembler for Linux applications is far easier than it is for the Microsoft environment, and in many ways is not dissimilar to writing assembler in the good old days of DOS. I am using NASM as the assembler for this environment.
System calls
Unlike Microsoft Windows that provides us with a sophisticated set of Windows API calls for a multitude of system functions, Linux system functions are 'raw'. That is what gives Linux such sex-appeal compared to the 'let's remove the programmer from anything that vaguely looks interesting' Microsoft approach. Depending upon the flavour of the Linux operating system you are running, there are around 350 system calls. I am not going into details about each individual system call here as half the fun with programming are the experiments and learning for yourself. I will however provide details about the system calls that are used in the example below.
Each system call has to be set up, but rather than being stack-oriented like Microsoft Windows, system calls are register oriented. The eax register always contains the system call number - the value that let's the Linux kernel know what you want it to do. To execute a system call, we use the int 80H which is a software interrupt that switches to kernel mode.
; This program constitutes the 'C++ 'Hello World' example global _start ; main program entry point section .data hello_message db 'Hello world',0AH section .code _start: mov eax, 4 ; sys_write call number mov ebx, 1 ; output handle mov ecx, hello_message ; address of message to write mov edx, 12 ; length of message write int 80H ; write the text mov eax, 1 ; sys_exit call number xor ebx, ebx ; exit code int 80H ; leave the system
Writing data to a file handle
The system call for performing a write operation has a system call number of 4. The ebx register must contain the handle of the device that has been opened for writing, the ecx register must contain the address of the buffer to write the data from, and finally the edx register must contain the length of the message to write.
Terminating the application
To terminate the application, the system call for performing the exit has a system call number of 1. The ebx register contains the return code.
Compiling and running the code
Copy the code from above and enter into your favourite editor and save it to a file called hello.asm. Then from a command prompt enter
[[email protected] hello]$ nasm -f elf -o hello.o hello.asm [[email protected] hello]$ ld -m elf_i386 -o hello hello.o [[email protected] hello]$ hello Hello world [[email protected] hello]$