在ARM Linux内核中增加一个新的系统调用

来源:互联网 发布:c语言基础知识txt下载 编辑:程序博客网 时间:2024/05/18 22:50

实验平台内核版本为4.0-rc1,增加的系统调用仅仅是简单打印一个Hello World,最后我们在用户空间用swi指令验证。涉及到的改动如下:


1. 在内核中增加文件arch/arm/kernel/mysyscall.c,这个文件实现新的打印Hello World的系统调用。

#include <linux/printk.h>void sys_helloworld(void){printk("hello world\n");}

修改arch/arm/kernel下的Makefile编入该文件:

--- a/arch/arm/kernel/Makefile+++ b/arch/arm/kernel/Makefile@@ -18,7 +18,7 @@ CFLAGS_REMOVE_return_address.o = -pg obj-y          := elf.o entry-common.o irq.o opcodes.o \                   process.o ptrace.o return_address.o \                   setup.o signal.o sigreturn_codes.o \-                  stacktrace.o sys_arm.o time.o traps.o+                  stacktrace.o sys_arm.o time.o traps.o mysyscall.o  obj-$(CONFIG_ATAGS)            += atags_parse.o obj-$(CONFIG_ATAGS_PROC)       += atags_proc.o

2. 将sys_helloworld加入syscall的表,并修正syscall的数量:

数量修正,注意不是加1,而是加4,这个主要是因为padding对齐的原因。

--- a/arch/arm/include/asm/unistd.h+++ b/arch/arm/include/asm/unistd.h@@ -19,7 +19,7 @@  * This may need to be greater than __NR_last_syscall+1 in order to  * account for the padding in the syscall table  */-#define __NR_syscalls  (388)+#define __NR_syscalls  (392)  /*  * *NOTE*: This is a ghost syscall private to the kernel.  Only the

把sys_helloworld函数指针填入arch/arm/kernel/calls.S

--- a/arch/arm/kernel/calls.S+++ b/arch/arm/kernel/calls.S@@ -397,6 +397,7 @@ /* 385 */      CALL(sys_memfd_create)                CALL(sys_bpf)                CALL(sys_execveat)+               CALL(sys_helloworld) #ifndef syscalls_counted .equ syscalls_padding, ((NR_syscalls + 3) & ~3) - NR_syscalls #define syscalls_counted

编译内核时候,使能OABI的兼容:




重新编译内核后,写应用程序来验证这个系统调用。


3. 应用程序验证,OABI和EABI两种方式:

程序如下:

#include <stdio.h>#definesys_oabi_hello() __asm__ __volatile__ ("swi 0x900000+388\n\t")#definesys_eabi_hello() __asm__ __volatile__ ("mov r7,#388\n\t" "swi 0\n\t" )void main(void){printf("start hello\n");sys_oabi_hello();sys_eabi_hello();printf("end hello\n");}

OABI方式下,系统调用方式是“swi 0x900000+388”,EABI则是把388填入r7,之后发“swi 0"。


关于OABI和EABI的区别,可以在PC上运行man syscall,得到答案如下:


       arch/ABI   instruction          syscall #   retval Notes
       ───────────────────────────────────────────────────────────────────────────────────
       arm/OABI   swi NR               -           a1     NR is syscall #


       arm/EABI   swi 0x0              r7          r0


 

2 1