Skip to content

Instantly share code, notes, and snippets.

@xterat
Last active October 31, 2022 17:49
Show Gist options
  • Select an option

  • Save xterat/be4efabd0e642ec0ab76670c473cf8cb to your computer and use it in GitHub Desktop.

Select an option

Save xterat/be4efabd0e642ec0ab76670c473cf8cb to your computer and use it in GitHub Desktop.

1. Add a new entry in syscall table

add a entry in arch/x86/entry/syscalls/syscall_64.tbl:

322     64      execveat                stub_execveat  
323     common  userfaultfd             sys_userfaultfd  
324     common  membarrier              sys_membarrier  
325     common  mlock2                  sys_mlock2  
326     common  hello                   sys_hello      <---- 加在这一行  

2. Declare the system call

add a declaration to our system call in include/linux/syscalls.h:

asmlinkage long sys_membarrier(int cmd, int flags);

asmlinkage long sys_mlock2(unsigned long start, size_t len, int flags);

asmlinkage long sys_hello(void);  <---- 加这一行  

3. Implement our system call

mkdir hello
touch hello/hello.c
touch hello/Makefile

File content in hello/hello.c:

#include <linux/kernel.h>

asmlinkage long sys_hello(void)  
{
    printk("Hello world\n");
    return 0;
}

File content in hello/Makefile

obj-y := hello.o  

4. Modifiy Makefile in linux-4.x/

Chane

core-y          += kernel/ certs/ mm/ fs/ ipc/ security/ crypto/ block/  

to

core-y          += kernel/ certs/ mm/ fs/ ipc/ security/ crypto/ block/ hello/  

5. Compile kernel

6. Write program to use the system call

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

#define __NR_hello 326

long hello_syscall(void)  
{
    return syscall(__NR_hello);
}

int main(int argc, char *argv[])  
{
    long int a = hello_syscall();
    printf("System call returned %ld\n", a);
    return 0;
}

If everything is OK, we can see "Hello World" in dmesg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment