Thursday 25 July 2013

Writing a linux system call

WHAT IS A SYSTEM CALL?

System call is an interface (the only interface) between user space and the kernel. It is more than a normal function. It creates a trap (soft interrupt) to make the kernel perform a specific task.

Examples of System call

The applications we use might use many system calls. But as a person with limited experience we might not be aware of this fact.
Some examples include - open, chown, seek etc.

Can I write my own system call?

Of course, we can. This is the beauty of it and the same can be stated as "kernel programming":)

How do I write a system call?

It is quite simple in latest Linux kernels, unlike the older ones (2.6 and older).
The steps are elaborated below.

1. Get the source of your kernel tree.
2. There is a syscall table in the kernel, which is specific to architecture.
<kernel>/arch/<architecture>/syscalls/syscall_32.tbl
This table contains the ID of system call, its name and its function name. Add your system call entry in this file. Please make sure that you give a unique ID number to your system call based on the current number of system calls.
3. Add the prototype of the system call in include/Linux/syscalls.h file.
4. Add the system call definition in any file (new or can be appended in existing file). In case of a new file. Make necessary modification in the Makefile of parent directories recursively, until this file is treated for compilation.
NOTE : in steps 3 and 4, asmlinkage is to be done.
5. Once these modifications are done, Compile this kernel and deploy the image
a) make menuconfig
b) make
c) make modules
d) make modules_install
e) make install

6. make install will take care of copying kernel image to /boot directory and to update grub configuration.
7. reboot. Select your kernel image during board bring up.
8. Write an application that will invoke your system  all and verify that your system call exists, it is called and it works as u intended it to.
This can be done by syscall(<SYSCALL ID>,<Parameters if any>)

What else should I remember?

1. The system call can return a value and can get arguments.
2. The number of arguments that can be passed to the system call is specific to the architecture.
This is because each architecture support different number of registers. Eg : x86 supports 6 registers.
3. Because of the above difference specific to architecture, the number of system calls for same kernel version might differ from architecture to architecture.
4. Although the usage of most of the common syscalls are still the same.
5. The syscall can get parameters of size of upto unsigned long int. (size of register dependent).


 

No comments:

Post a Comment