Linux 内核新增系统调用
关键信息
系统环境
| 选项 | 参数 |
|---|---|
| 系统 | ubuntu 14.04.6 desktop i386 |
| 内核 | 4.4.0-148-generic |
| 替换内核 | 4.4.148 北京交大镜像 |
| 磁盘大小 | 50 GiB in total, 30 GiB for /, finally 15.3 GiB used |
编译环境
| 选项 | 安装方式 |
|---|---|
libncurses5 |
apt-get 在线安装 |
libncurses5-dev |
apt-get 在线安装 |
libssl-dev |
apt-get 在线安装 |
arm-2014.05-29-arm-none-linux-gnueabi-i686-pc-linux-gnu |
下载压缩包离线安装 |
sudo apt-get install libncurses5 libncurses5-dev libssl-dev
arm-none-linux-gnueabi 网盘下载地址:https://blog.csdn.net/ee230/article/details/41513957
这东西资源挺少的,我就找到个网盘。
关键文件
| 文件位置 | 备注 |
|---|---|
/usr/src/linux-4.4.148 |
内核目录,以下使用 $kernel 代替 |
$kernel/arch/x86/entry/syscalls/syscall_64.tbl |
系统调用入口表 for 64 bit |
$kernel/arch/x86/entry/syscalls/syscall_32.tbl |
系统调用入口表 for 32 bit |
$kernel/include/linux/syscalls.h |
系统调用函数声明 |
$kernel/kernel/sys.c |
系统调用函数实现 |
make
| 命令 | 功能 |
|---|---|
make mrproper |
清除一些杂项文件,包括配置文件等 |
make clean |
清除以前生成的文件等 |
make menuconfig |
可视化配置内核 |
make oldconfig |
使用之前的配置 |
make -jx |
生成文件,x 表示多线程执行的个数,不指定时默认为 1make 耗时较长(虚拟机一般 30 min 起步),最好多线程执行 |
make modules_install |
安装模块 |
make install |
安装内核 |
具体步骤
默认已经准备好了编译环境,如果系统环境不同,可能需要的编译环境也会有差异,请自行解决。
之后的操作均在目录 $kernel 下!
新增系统调用号
编辑系统调用表 arch/x86/entry/syscalls/syscall_32.tbl
vim arch/x86/entry/syscalls/syscall_32.tbl
在底部新增系统调用 377 号,对应函数 sys_helloworld
377 i386 helloworld sys_helloworld
声明并实现系统调用函数
编辑头文件 include/linux/syscalls.h
vim include/linux/syscalls.h
在底部的 #endif 之前添加函数声明
asmlinkage int sys_helloworld(int number);
编辑文件 kernel/sys.c
vim kernel/sys.c
在底部的 #endif 之后实现函数
asmlinkage int sys_helloworld(int number)
{
// printk 是系统调用输出的函数,其输出需要使用 dmesg 命令查看
printk("hello,world\n");
return number;
}
make
依次执行以下命令,确保无冗余文件,并多线程执行 make 任务,减少运行时间:
make mrproper
make clean
make menuconfig # 可以不进行设置,直接退出
make -j4 # 4 线程执行 make 任务
make 完成之后准备安装模块,执行 make modules_install
make mudules_install
安装完成之后在 lib/modules 目录下会新增一个目录 4.4.148
最后执行 make install 安装内核
make install

更改 grub 的配置,保证看得见内核选择界面
vim /etc/default/grub
更改如下参数,设置显示时间 5 秒
GRUB_HIDDEN_TIMEOUT=5
执行 update-grub 更新设置
sudo update-grub
重启时按 esc 进入界面,选择 Ubuntu 高级选项 ,并选择你安装的内核
进入之后查看内核版本,已经从 4.4.0-148-generic 切换至 4.4.148
uname -r
测试系统调用
编写如下代码并编译执行
#include <stdio.h>
int main()
{
// 新增的系统调用为 377 号,传入参数 10,应当在终端打印 10
printf("%d\n",syscall(377,10));
return 0;
}

使用 dmesg 命令查看系统调用输出

因为执行了 4 次程序,所以总计输出了 4 次 hello,world,至此新增系统调用成功。
个人博客:https://wilfredshen.cn/

浙公网安备 33010602011771号