Registers and the exit system call
Four instructions, no libraries — a program that asks the kernel to exit with a status of its choosing.
- Name the general-purpose registers and what mov, add and sub do to them
- Make a Linux system call with int 0x80
- Read a program's result from the shell's exit status
The smallest useful program does one thing: it stops, and tells the operating system how it went. Here is the whole of 01_intro.asm:
global _start
_start:
mov eax, 1
mov ebx, 42
sub ebx, 29
int 0x80
_start is where Linux begins executing a program that is linked without the C runtime, and global makes the label visible to the linker. Then:
-
mov eax, 1puts the number 1 into registereax. Registers are the CPU’s own 32-bit variables; there are only a handful, and every computation goes through them. -
mov ebx, 42thensub ebx, 29leaves \(42 - 29 = 13\) inebx. -
int 0x80raises a software interrupt: control passes to the kernel, which looks ineaxfor which service is wanted. Number 1 issys_exit, and its argument — the exit status — is taken fromebx.
Seeing the result
The program prints nothing, so the result is in the exit status:
nasm -f elf32 01_intro.asm -o intro.o
ld -m elf_i386 intro.o -o intro
./intro; echo $?
prints 13. The status is one byte, so only the low 8 bits survive: an exit status of 300 is reported as \(300 \bmod 256 = 44\).
Where the numbers come from
System-call numbers are fixed by the kernel’s 32-bit table, /usr/include/asm/unistd_32.h: 1 is exit, 3 is read, 4 is write. The convention for int 0x80 is number in eax, arguments in ebx, ecx, edx, esi, edi, and the kernel’s return value back in eax. The 64-bit convention differs completely (the syscall instruction, different numbers and registers). The object files are different too, which is why a 32-bit program needs -f elf32 to assemble and -m elf_i386 to link on a 64-bit system.
Try it yourself. Make the program exit with status 200 using only add instructions on ebx. Then set ebx to 256 and check echo $? — explain the result. Finally, delete the int 0x80 line: the program now dies with a segmentation fault (echo $? shows 139). Why does the CPU not simply stop at the end of the code?