gpt4 book ai didi

c - 自定义文件打开函数在 Linux 内核中覆盖 sys_call_table 时的奇怪行为

转载 作者:太空狗 更新时间:2023-10-29 11:13:35 25 4
gpt4 key购买 nike

为了学习 Linux 内核,我编写了一个模块,它使用我的自定义 (custom_sys_open) 函数覆盖系统调用 sys_open。我的 custom_file_open 的代码:-

#define CUSTOM_CHECK_FILE "/home/xxxx/Programming/kernel_module/custom.txt"
asmlinkage long custom_file_open(const char __user *fileName, int flags, umode_t mode)
{
long retVal = 0;
int len = strlen(fileName);
if(strcmp(fileName+len-9,"check.txt")== 0){
retVal= (*orig_file_open)(CUSTOM_CHECK_FILE, flag, mode);
}
return retVal;
}

它不起作用,在这种情况下 retVal 始终为 -14。但是,如果我只是将 CUSTOM_FILE_CHECK 字符串复制到“fileName”中,它就会像下面的代码一样开始工作:-

asmlinkage long custom_file_open(const char __user *fileName, int flags, umode_t mode)
{
long retVal = 0;
int len = strlen(fileName);
if(strcmp(fileName+len-9,"check.txt")== 0){
memcpy((void*)fileName, (void*)CUSTOM_CHECK_FILE, strlen(CUSTOM_CHECK_FILE));
retVal = (*orig_file_open)(fileName, flag, mode);
}
return retVal;
}

它按预期工作。但我无法理解:-

  1. 以前的自定义文件打开功能有什么问题?
  2. 将参数传递给原始文件打开系统调用时我做错了什么吗?

请帮助我理解这一点。

最佳答案

在这里,您试图将在内核空间中分配的内存传递给系统调用,而系统调用需要在用户空间中分配内存。我不知道如何从内核空间在用户空间中分配内存,但我认为这个链接 ( Allocating memory for user space from kernel thread ) 对它有所启发。还有另一种方法来做你想做的事情,就是禁用内存地址有效性检查。为此,请尝试以下代码:-

mm_segment_t orig_fs = get_fs();
set_fs(KERNEL_DS);
retVal= (*orig_file_open)(CUSTOM_CHECK_FILE, flag, mode);
set_fs(orig_fs);

关于c - 自定义文件打开函数在 Linux 内核中覆盖 sys_call_table 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29300231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com