当前位置:Linux教程 - Linux - 如何在Linux Kernel內新增一个System Call

如何在Linux Kernel內新增一个System Call

本文作者: gpmoney
使用 system call 去呼叫系統的函式是非常好玩的,但是要如何寫出一個自己的system call 呢?這邊有以下數個步驟,如果你是自己想要呼叫 system call 那可以跳過 (1) (2) 直接到第三項這邊假設你己經熟悉 kernel 的 compile 和如何利用新 compile 的 kernel 重新開機


(1) 設定 include 檔內的 syscall function


首先,找到 /usr/inlcude/asm/unistd.h 這個檔案,在這一行



#define __NR_getdents64 220
#define __NR_fcntl64 221



的後面加上 :


#define __NR_myfunc 222



然後找到 /usr/include/bits/syscall.h 這個檔案,再加上一行 :


#define SYS_myfunc __NR_myfunc



找到 /usr/src/linux/arch/i386/kernel/entry.S 這個檔案也是在最後面加上並修改標記為紅色的這二行



.long SYMBOL_NAME(sys_getdents64) /* 220 */
.long SYMBOL_NAME(sys_fcntl64)
.long SYMBOL_NAME(sys_myfunc) --> 增加這一行
#ifdef CONFIG_TUX
.long SYMBOL_NAME(__sys_tux)
#else
# ifdef CONFIG_TUX_MODULE
.long SYMBOL_NAME(sys_tux)
# endif
#endif

/*
* NOTE!! This doesn''t have to be exact - we just have
* to make sure we have _enough_ of the ""sys_ni_syscall""
* entries. Don''t panic if you notice that this hasn''t
* been shrunk every time we add a new system call.
*/
.rept NR_syscalls-222 ----> 改成 NR_syscalls-223
.long SYMBOL_NAME(sys_ni_syscall)
.endr




(2) 撰寫 syscall 的範例程式


假設你的 linux kernel code 在 /usr/src/linux 下找到 /usr/src/linux/kernel/sys.c

加上以上這幾行 :


asmlinkageintsys_myfunc(int input){
printk(""<1> Input value is : %d "",input);
return input*10;
}



改完以後,就可以重新 compile kernel 並且重新開機了。


(3) 撰寫 user space 的小程式



use_syscall.c
#include
#include
#include

static inline _syscall1(int,myfunc,int,a)

int main(void){
printf(""Return Value: %d "",myfunc(10));
}



這樣執行完以後,你就可以看到這個程式輸出 100

如果你還有興趣,可以使用 tail -f /var/log/message 會出現類似的訊息,表示你的程式有經由 printk 印到畫面上


Sep 3 22:02:02 private kernel: Input value is : 10



_syscall1 是一個 macro 指令,事實上是 _syscallN 的指令 , N 代表系統呼叫所需要用到的參數個數

_syscallN(arg1,arg2,arg3,arg4) :

arg1 : 代表的是傳回值
arg2 : 代表的是要呼叫的 syscall name
arg3 : 代表的是傳入參數的型態
arg4 : 代表的是傳入參數的名稱


系統總共定義了 6 個 _syscallN , 從 _syscall0 到 _syscall5 . 因為這是呼叫 int 0x80 的限制,各位大概發現了一件事,這個只是協助各位去呼叫 int 0x80 這個系統中斷函式,不過 linux 幫我們包的很好


(4) 編譯程式



#gcc -O2 use_syscall.c use_syscall
#./use_syscall



Return Value: 100