md.*_*mal 2 c linux x86 system-calls linux-kernel
我正在深入研究系统调用,
在 syscall_32.tbl 和 syscall_64.tbl 中添加了系统调用
系统调用_32.tbl
434 i386 hello sys_hello __ia32_sys_hello
Run Code Online (Sandbox Code Playgroud)
系统调用_64.tbl
434 common hello __x64_sys_hello
Run Code Online (Sandbox Code Playgroud)
定义:
SYSCALL_DEFINE0(hello) {
pr_info("%s\n", __func__);
pr_info("Hello, world!\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
用户空间代码:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/syscall.h>
#include <string.h>
int main(void)
{
long return_value = syscall(434);
printf("return value from syscall: %ld, erron:%d\n", return_value, errno);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我在 x86_64 上运行此用户空间代码时,我在 dmesg 中得到以下输出
$ gcc userspace.c -o userspace
[ 800.837360] __x64_sys_hello
[ 800.837361] Hello, world!
Run Code Online (Sandbox Code Playgroud)
但是当我将其编译为 32 位时,我得到了
$ gcc userspace.c -o userspace -m32
[ 838.979286] __x64_sys_hello
[ 838.979286] Hello, world!
Run Code Online (Sandbox Code Playgroud)
syscall_32.tbl (__ia32_sys_hello) 中的入口点如何映射到 __x64_sys_hello?
在 64 位内核上,SYSCALL_DEFINE0将 compat(32 位)和其他 ABI(例如 x86_64 上的 x32)系统调用入口点定义为真正 64 位函数的别名。它不定义(并且无法定义;这不是预处理器的工作方式)从)宏求值之后出现的单个主体构建的多个函数。因此__func__扩展到其中写入的实际函数的名称__func__,而不是别名的名称。
对于SYSCALL_DEFINExx>0,它更复杂,因为必须转换参数,并且我相信涉及包装器。
arch/x86/include/asm/syscall_wrapper.h您可以在(顶级内核树下)找到所有魔力。
如果你真的想要/需要有单独的功能,我相信有一种方法可以跳过魔法并做到这一点。但这会让你的代码更难维护,因为当魔法背后的机制崩溃时,它可能会崩溃。最好探测调用(当前)用户空间进程是 32 位还是 64 位,并根据情况采取不同的操作。