add a system call in linux kernel
by Torstan, 2011-10-4 23:08
Today I successively add a system call in linux kernel, long foo(), to output the size of per-process kernel stack. The procedure is as follows.
step1. add an entry to the end of system call table.
torstan@stan:~/code/linux-2.6.24/arch/x86/kernel$ diff syscall_table_32.S.bk syscall_table_32.S
326a327
> .long sys_foo /*add for fun by Torstan*/
step2. for each architecture, define an system call number at the end of asm/unistd.h
Since the architecture of my computer is i686 (x86 32 bit) which can be got from uname -a, I only need modify relevant code of x86 architecture.
torstan@stan:~/code/linux-2.6.24/include/asm$ pwd
/home/torstan/code/linux-2.6.24/include/asm
torstan@stan:~/code/linux-2.6.24/include/asm$ diff unistd_32.h.bk unistd_32.h
332a333
> #define __NR_foo 325
336c337
< #define NR_syscalls 325
---
> #define NR_syscalls 326
step3. define the system call in kernel/sys.c, which containing miscellaneous system calls
torstan@stan:~/code/linux-2.6.24/kernel$ pwd
/home/torstan/code/linux-2.6.24/kernel
torstan@stan:~/code/linux-2.6.24/kernel$ diff sys.c.bk sys.c
35a36
> #include <asm/thread_info_32.h>
1751a1753,1760
> /*This sys call is added for fun by Torstan
> return the size of per-process kernel stack
> */
> asmlinkage long sys_foo(void)
> {
> return THREAD_SIZE;
> }
step4. compile the kernel
torstan@stan:~/code/linux-2.6.24$ uname -a
Linux stan 2.6.24 #1 SMP Tue Oct 4 17:45:57 CST 2011 i686 GNU/Linux
please refer to "how to compile linux kernel"
step5. add test code for the system call
source code of testSyscall.c
#include<linux/unistd.h>
#include<sys/syscall.h>
#include<stdio.h>
#define _NR_foo 325
//_syscall0 ( long, foo);
int main()
{
// long stacksize=foo();
long stacksize=syscall(_NR_foo);
printf("The kernel stack size is %ld\n", stacksize);
return 0;
}
output:
torstan@stan:~/code$ gcc testSyscall.c
torstan@stan:~/code$ ./a.out
The kernel stack size is 8192
check the result:
In include/asm/thread_info_32.h
#ifdef CONFIG_4KSTACKS
#define THREAD_SIZE (4096)
#else
#define THREAD_SIZE (8192)
#endif
torstan@stan:~/code/linux-2.6.24$ grep CONFIG_4KSTACKS .config
# CONFIG_4KSTACKS is not set
reference:
linux kernel development, 3rd edition.
http://www.ibm.com/developerworks/linux/library/l-system-calls/