为了完成家庭作业,我必须修改linux内核。
我在一个虚拟机上工作,我向内核添加了一个系统调用,我称之为get_unique_id。以下是get_unique_id.c的代码:#include
#include
asmlinkage long sys_get_unique_id(int * uuid)
{
// static because we want its state to persist between calls
static int uid = 0;
++uid;
// assign new uid value to user-provided mem location
// returns non-zero if success or -EFAULT otherwise
int ret = put_user(uid, uuid);
return ret;
}
我还将这一行添加到syscalls.h:
asmlinkage long sys_get_unique_id(int * uuid);
这一行到syscall_32.tbl:
383 i386 get_unique_id sys_get_unique_id
最后这一行是syscall_64.tbl:
548 common get_unique_id sys_get_unique_id
在重新编译并重新加载内核之后,我编写了一个小的C程序来测试我的系统调用,下面是C测试文件的代码:
// get_unique_id_test.c
#include
#include
#include "syscalls_test.h"
int main(void)
{
// initialize the ints we want
int id1;
int id2;
// check the id's are unique and that no error occured
for (int i = INT_MIN; i < INT_MAX - 1; i += 2) {
long ret1 = get_unique_id(&id1);
long ret2 = get_unique_id(&id2);
if (ret1 != 0)
printf("ERROR: get_unique_id returned: %ld\n", ret1);
if (ret2 != 0)
printf("ERROR: get_unique_id returned: %ld\n", ret2);
if (id2 != id1 + 1)
printf("ERROR: successive id's did not increment properly: id1 = %d, id2 = %d\n", id1, id2);
}
return 0;
}
以及它的头文件:
// syscalls_test.h
#include
#include
#include
#include
#define __NR_get_unique_id 383
inline long get_unique_id(int * uuid)
{
return syscall(__NR_get_unique_id, uuid) ? errno : 0;
}
不幸的是,在尝试使用以下命令编译C测试文件时:gcc -std=c99 get_unique_id_test.c -o get_unique_id_test,出现以下错误:
In file included from get_unique_id_test.c:4:0:
syscalls_test.h: In function ‘get_unique_id’:
syscalls_test.h:10:5: warning: implicit declaration of function ‘syscall’ [-Wimplicit-function-declaration]
return syscall(__NR_get_unique_id, uuid) ? errno : 0;
^
syscalls_test.h: In function ‘get_unique_id’:
syscalls_test.h:10:5: warning: implicit declaration of function ‘syscall’ [-Wimplicit-function-declaration]
return syscall(__NR_get_unique_id, uuid) ? errno : 0;
^
/tmp/cc1euZ3r.o: In function `main':
get_unique_id_test.c:(.text+0x22): undefined reference to `get_unique_id'
get_unique_id_test.c:(.text+0x34): undefined reference to `get_unique_id'
collect2: error: ld returned 1 exit status
gcc似乎找不到在get_unique_id(int * uuid)中声明的函数syscalls_test.h,也找不到应该在syscall中声明的函数syscall.h,对吧?
我不明白为什么会这样。有人知道吗?
编辑:我的问题是通过使用a3f的解决方案(见下文)以及移动文件顶部的#include "syscalls_test.h"来解决的,正如他在评论中所说。非常感谢你。
最佳答案:
#define _GNU_SOURCE之前包括unistd.h或任何其他标题作为syscall(2)不是posix。
使用static inline而不是普通的inline。plaininline提供了一个内联定义,但是编译器可以忽略它并使用您没有提供的外部定义。