SYSTEM PROGRAMMING

Adding a System Call to the Linux Kernel

In 2 Easy Steps

TechExplorer
2 min readMay 26, 2024

--

In this blog, we will see how to add a system call to the Linux kernel in two steps. This tutorial assumes you already know how to build and install the Linux kernel. If not, please refer to this article: Build the Latest Linux Kernel.

1. Add and Entry in the Table

The first thing to do is to add an entry to the system call table found in arch/x86/entry/syscalls/syscall_64.tblfor x86_64 artchitecture. There should be a similar file for other architectures. Find an empty slot and add your entry. In my case I added the following entry:

462     common  hello_world             sys_hello_world

2. Add the System Call Definition

Our system call will do the simple task of multiplying the argument by 2 and return it. Here’s its definition:

SYSCALL_DEFINE1(hello_world, int, number)
{
printk(KERN_INFO "Hello World %d", number);
return number << 1; /* using the shift operator to multiply by 2 */
}

Add the definition somewhere in the Linux kernel. For this example we will add it to fs/exec.c next to theexecve system call.

Now you can build and install the new kernel.

3. Testing Using a Userspace Program:

To test our system call we need to create a user program that will call it. The user program needs 2 parameters: the system call number and the argument number.

#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>

int main()
{
long int amma = syscall(462, 42); //syscall 462 with argument 42
printf(“System call sys_hello_world returned %ld\n”, amma);
return 0;
}

Compiling the program with the following command:

gcc syscall.c -o syscall

This will give the following result:

The system call does return the double of 42 which is 84. And we can see using dmesg (a command that print kernel messages) that the kernel does print the hello world message in addition to the argument number 42.

--

--

TechExplorer

Tech enthusiast with an interest in software and a love for cryptocurrencies. Check out my crypto donation page at: https://rb.gy/mqd43h