System calls are some basic and necessary instructions to get the computer or hardware working. These are APIs for the interface between the user and the kernel. For example, the system calls sys_write and sys_exit are used to write to the screen and exit the program, respectively.
Assembly - System Call
System Call Whatever operating system you use, you can use that system call instructions in the assembly program. Here we will try to understand using Linux system calls in our assembly program.
You need to do following steps to use Linux system calls in your program -
- Insert the system call number into the EAX register.
- Store the arguments of system calls in registers EBX, ECX, etc.
- Call (80h) to complete the instructions.
- Whatever result comes when this code is run is usually stored in the EAX register.
These six registers (EBX, ECX, EDX, ESI, EDI, and EBP) are used to store system call arguments. These registers take consecutive arguments starting from the EBX register. If there are more than six arguments, the memory location of the first argument is stored in the EBX register.
Some system call nasm assembly instructions.
mov eax,1 ; System Call Number (sys_exit)
mov eax,4 ; System Call Number (sys_write)
int 0x80 ; Call Kernel
All system calls are listed with their numbers in /usr/include/asm/unistd.h (the value you put in EAX before you call 80h)
System Calls Table - NASM
This table shows some of the system calls used in the tutorial.-
%eax | Name | %ebx | %ecx | %edx | %esx | %edi |
---|---|---|---|---|---|---|
1 | sys_exit | int | - | - | - | - |
2 | sys_fork | struct pt_regs | - | - | - | - |
3 | sys_read | unsigned int | char * | size_t | - | - |
4 | sys_write | unsigned int | const char * | size_t | - | - |
5 | sys_open | const char * | int | int | - | - |
6 | sys_close | unsigned int | - | - | - | - |
Example - The following example takes a number input from the keyboard and displays it on the screen
section .data ;Data Segment
userMsg db 'Please enter a number: ' ;Input Message
lenUserMsg equ $-userMsg ;message length
dispMsg db 'You have entered: '
lenDispMsg equ $-dispMsg
section .bss ;uninitialized data
num resb 5
section .text ;Code Segment
global _start
_start: ;User Input Prompt
mov eax, 4
mov ebx, 1
mov ecx, userMsg
mov edx, lenUserMsg
int 80h
;Read and Store User Input
mov eax, 3
mov ebx, 2
mov ecx, num
mov edx, 5 ;5 bytes (numeric, 1 for sign) of that information
int 80h
;message output 'The entered number is: '
mov eax, 4
mov ebx, 1
mov ecx, dispMsg
mov edx, lenDispMsg
int 80h
;Output the number entered
mov eax, 4
mov ebx, 1
mov ecx, num
mov edx, 5
int 80h
; exit code
mov eax, 1
mov ebx, 0
int 80h
When the above code is assembled and run, it produces the following result -
Please enter a number -
4321
You have entered - 4321