【问题标题】:Crash by executing strstr() inside kernel module在内核模块中执行 strstr() 导致崩溃
【发布时间】:2021-12-11 05:40:38
【问题描述】:

我正在尝试检测特定位置 (myPath) 中的打开文件夹。我正在使用 strstr() 但我看到我的系统在执行此函数后总是崩溃(picture)。如果我删除检查(if(ret)),它会正常工作 这是我的代码:

struct task_struct *task_list;
struct fdtable *        fdt = NULL;
unsigned int process_count = 0;
struct path files_path;
char *access_mode;
char *cwd;
int res;
char *myPath = "/home/anh/src/";
char *buf = (char *)kmalloc(GFP_KERNEL,100*sizeof(char));
char * ret;
for_each_process(task_list) {
        fdt = files_fdtable(task_list->files);
        int i=0;
        while(fdt->fd[i] != NULL) { 
            files_path = fdt->fd[i]->f_path;
            cwd = d_path(&files_path,buf,100*sizeof(char));
            if(cwd){//Check if cwd != NULL
                ret = strstr(cwd, myPath);//check seeked file path and myPath
                if(ret) 
                {
                    printk(KERN_INFO "Open file with fd %d  cwd: %s", i,cwd);
                }   
            }    
            i++;
        }
        process_count++;    
    }

有人可以评论并支持我解决这个问题吗?为什么 strstr() 不能在 Linux 内核模块中使用,或者有其他方法可以验证字符串是否在字符串中?

最好的问候, 安赫

【问题讨论】:

  • 字符串 needle 和 haystack 0 都终止了吗?

标签: c string linux-kernel filepath strstr


【解决方案1】:

一个合理的解释是发生了错误,所以cwd 不是一个有效的指针。在此无效指针上调用 strstr 并崩溃。如果没有if(ret)strstr 调用会被优化掉,因此不会发生崩溃。

Linux 内核中的函数通常会在出错时返回错误代码。 documentation of d_path 明确指出是这种情况。

如果路径太长,则返回指向缓冲区的指针或错误代码。

if (cwd) 检查cwd 是否为非空。如果cwd 包含错误代码,则它是非空的。所以if (cwd) 不是一个有用的检查。对于返回指针的函数,正确的error checkIS_ERR()

            cwd = d_path(&files_path,buf,100*sizeof(char));
            if (IS_ERR(cwd)) {
                    printk(KERN_WARN "At i=%d: d_path -> %ld", i, PTR_ERR(cwd));
            } else {
                    ret = strstr(cwd, myPath);

【讨论】:

  • 你的解释很好。 cwd 有错误 -> 运行 strstr() 错误 -> 崩溃。非常感谢
猜你喜欢
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
相关资源
最近更新 更多