- 论坛徽章:
- 0
|
- 注:偶忘记在那里发现的了,文章虽然很简单,但是对初学者还是很不错哦
- 如何在 Linux Kernel 内新增一个 System Call
-
- 使用 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 \n",input);
- return input*10;
- }
-
- 改完以后,就可以重新 compile kernel 并且重新开机了。
- (3) 撰写 user space 的小程序
- use_syscall.c
- #include <stdio.h>;
- #include <stdlib.h>;
- #include <linux/unistd.h>;
- static inline _syscall1(int,myfunc,int,a)
- int main(void){
- printf("Return Value: %d\n",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
- 有任何问题欢迎来信讨论
复制代码 |
|