Инициализация из несовместимого типа указателя при назначении полей struct file_operations - PullRequest
0 голосов
/ 03 мая 2020

Я пишу диск устройства Linux, и я не понимаю, почему я получаю это предупреждение.

error: initialization from incompatible pointer type [-Werror=incompatible-pointer-types]
  .write = file_write,

Это мой код, который я создал, когда использую команду make Я получаю вышеуказанную ошибку. Я попытался изменить ssize_t на int, но все равно получаю ту же ошибку.

#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/random.h>

MODULE_LICENSE("NIKS");


static char msg[100]={0};
static short readPos =0;

static int file_open(struct inode * , struct file *);
static int file_release(struct inode * , struct file *);
static ssize_t file_read(struct file *, char *, size_t,loff_t * );
static ssize_t file_write(struct file *, char *, size_t,loff_t * );

static struct file_operations fo = 
{
    .read = file_read,
    .open = file_open,
    .write = file_write,
    .release = file_release,
};

int init_module(void)
{
    int t = register_chrdev(150,"encdev",&fo);
    if(t<0)
    {
        printk("error");
    }
    else
    {
        printk("success");
    }
    return t;
}

void cleanup_module(void)
{
    unregister_chrdev(150,"encdev");
}

static int file_open(struct inode *in , struct file *fil)
{
    return 0;
}

static ssize_t file_read(struct file *fil, char *buf, size_t len,loff_t *off )
{
    short count=0;
    printk("here %d",msg[0]!=0);
    while(len && (msg[readPos]!=0))
    {
        printk("read");
        put_user(msg[readPos],buf++);
        count++;
        len--;
        readPos++;
    }
    return count;
}

static ssize_t file_write(struct file *fil, char *buf, size_t len,loff_t *off )
{
    short ind = 0;
    short count =0;
    memset(msg,0,100);
    readPos = 0;
    int i =0;
    char bytes[16];
    char rand;
    while(i<16)
    {
        get_random_bytes(&rand, sizeof(rand));
        bytes[i]=rand;
        ++count;
        i++;
    }
    int _len = len+16;
    while(_len>0 || count%16){
        if(ind<16) msg[ind] = bytes[ind];
        else{
            msg[ind] = (_len>0?buf[ind-16]:'@')^msg[ind-16];
        }
        ++ind;
        --_len;
        ++count;
    }
    return count;

}

static int file_release(struct inode *in , struct file *fil)
{
    printk("done");
    return 0;
}

Я новичок в C, и я просто не могу понять, почему я получаю это предупреждение , Кто-нибудь может объяснить, почему я получаю это предупреждение и что с этим делать, пожалуйста?

1 Ответ

0 голосов
/ 03 мая 2020

Правильные типы для read и write функциональных указателей struct file_operations:

ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);

Поэтому в вашем модуле соответствующие сигнатуры:

static ssize_t file_read(struct file *, char __user *, size_t, loff_t *);
static ssize_t file_write(struct file *, const char __user *, size_t, loff_t *);

// ...

static ssize_t file_read(struct file *fil, char __user *buf, size_t len,loff_t *off)
{

// ...

static ssize_t file_write(struct file *fil, const char __user *buf, size_t len, loff_t *off)
{

Важной частью, которая отсутствовала, был квалификатор const, но также важно помнить, что любой указатель, переданный из пространства пользователя, должен быть помечен аннотацией __user (даже если компилятор не предупредит Если вы забудете об этом, он предназначен только для проверки состояния c для Разреженный ).


У вас также есть несколько объявлений после других утверждений, что недопустимо в С90. Компилятор предупредит вас о них, последует за предупреждениями и переместит их в начало тела функции.

...