替换file_operations的“写入”功能无效吗? (内核5.2.9)

时间:2019-10-24 22:42:00

标签: c kernel

我正在为C内核编程类进行简单的分配,并且我需要使用LKM设置通信通道。我已经看到多个人成功地替换了write结构中的file_operations函数。尽管使用该代码作为参考,但我似乎似乎做不到。 write的替代版本似乎根本没有执行。请注意,我添加了一个简单的全局计数器来对其进行跟踪。

我分析了file_operations结构的地址,它似乎已按预期被替换。如果我尝试使用echo 1 > file或gedit写入文件,似乎没有任何反应。

我正在使用5.2.9内核。参考代码是为较早的内核(即4.4.0)编写的。任何帮助将不胜感激。

const static struct file_operations *fops_original = 0;
static struct file_operations fops_replacement;

static int counter = 0;

static ssize_t channel_write (struct file *f, const char __user * data, size_t sz, loff_t *l)
{
    pr_err("test");
    counter ++;
    return 1;
}

static int __init mod_init(void)
{
    struct file *fp;
    fp = filp_open("/root/Desktop/test", O_RDONLY, S_IRUSR);

    fops_original = (struct file_operations*)fp->f_op;

    fops_replacement = *fp->f_op;

    pr_err("The memory address of original f_ops is: %p\n", fp->f_op);

    fops_replacement.write = channel_write;

    pr_err("The memory address of replaced f_ops is: %p\n", (void *) &fops_replacement);

    fp->f_op = &fops_replacement;

    pr_err("The memory address of f_ops after replacement is: %p\n", fp->f_op);

    filp_close(fp, 0);

    return 0;
}

static void __exit mod_exit(void)
{
    struct file *fp;

    if(fops_original) {
        fp = filp_open("/root/Desktop/test", O_RDONLY, S_IRUSR);
        fp->f_op = fops_original;
        filp_close(fp, 0);
    }
    pr_err("Counter %d\n", counter);
}

0 个答案:

没有答案
相关问题