【发布时间】:2021-08-06 08:32:33
【问题描述】:
我正在尝试编写一个简单的设备驱动程序。驱动程序只有读/写操作。理想情况下,我希望 read() 函数以这样一种方式工作,即在读取设备文件时,会向终端打印一条消息以及读取设备文件的次数。该驱动程序包含以下库和全局变量:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/irq.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <linux/poll.h>
#include <linux/cdev.h>
#include "my_driver.h"
#define DEVICE_NAME "Edev"
#define SUCCESS 0
#define FAILURE -1
#define BUF_LEN 1024
static struct class * cls;
static int major_num;
static int counter=0;
static char message_buffer[BUF_LEN];
static char * message_pointer;
static char * write_pointer;
static struct file_operations elliott_fops = {
.read=device_read,
.write=device_write,
.owner=THIS_MODULE
};
读取函数是这样写的:
static ssize_t device_read(struct file * filp2, char *buffer2, size_t length2, loff_t *offset2){
ssize_t bytes_in_message=0;
sprintf(message_buffer,"Yes,you read from the driver this many times: %d",counter++);
message_pointer=message_buffer;
while (length2 && *message_pointer++){
put_user(*(message_pointer++),buffer2++);
bytes_in_message++;
length2--;
}
pr_info("Read %lu bytes with %lu bytes remaining in the buffer",bytes_in_message,length2);
return bytes_in_message;
}
我希望 read() 函数使用 sprint() 调用将消息打印到终端,然后 while 循环将获取消息的字节长度。消息字节长度信息以及剩余缓冲区大小将记录在内核中
write函数是这样写的:
static ssize_t device_write(struct file * filp, const char *buffer, size_t length, loff_t *offset){
ssize_t bytes_read_in=0;
while (length && *buffer++){
get_user(*(write_pointer++),buffer++);
bytes_read_in++;
}
pr_info("The device had %lu bytes written to it",bytes_read_in);
pr_info("Got message from user: %s",write_pointer);
return bytes_read_in;
}
理想情况下,如果有人使用 "echo "hello linux kernel" > /dev/Edev" 命令写入设备,写入设备文件的消息将在内核中打印,以及如何消息很长。但是,read() 和 write() 函数的行为根本不是这样。例如,如果我加载模块并写入设备文件,则内核中没有记录任何消息。如果我随后执行了 cat /dev/Edev 命令,则打印到终端输出的不是带有计数的消息,而是刚刚通过 echo 写入设备的内容。
我假设这可能与缓冲区相互覆盖有关,但我很困惑,因为写入的缓冲区是用户空间,而读取的缓冲区是内核空间。我也不确定为什么没有消息被记录到内核。
【问题讨论】:
-
看起来
device_write依赖用户空间来空终止它正在写入的数据。这不是一个安全的假设,尤其是echo不会这样做。此外,您的*buffer++从用户空间读取而不通过get_user这也是不安全的。 -
您似乎也无法防止长时间写入超出缓冲区。我知道这只是作为练习编写的测试代码,但同样令人恐惧 - 内核中的缓冲区溢出是您可以想象的最严重的漏洞之一。
-
哦,
device_write每次迭代都会增加两次buffer,这是错误的。message_pointer与device_read相同。 -
并且
length不会在device_write的循环中递减,因此这部分测试将始终保持为真。 -
而且你不检查
get_user或put_user的返回值。基本上,这可能是您需要在几个小时后回来阅读您实际编写的内容,而不是您认为自己正在编写的内容的情况。就目前而言,您每个 LOC 的错误密度非常高,很难弄清楚其中哪一个是您观察到的不当行为的原因。
标签: c linux-kernel linux-device-driver