将数据从内核 space 复制到用户 space

copy data from kernel space to user space

我正在尝试进行自定义系统调用。

我的系统调用有 2 个参数 struct buffer **mybuffer & int size.

它强加了发生在 **mybuffer 上的任何更改应该反映在用户中-space,但它似乎不起作用。

所以我在其他地方看到我可以使用 copy_to_user(void *dest, void *src, int size) 将数据从内核 space 复制到用户 space。

在 user-space 我有一个叫做 buffer 的结构,这个结构在系统调用中也是一样的。

typedef struct buffer {
int n;
}buffer;

    int main(void)
   {
     buffer **buf = malloc(sizeof(buffer *));
     int i = 0
for(;i<8;i++)
buf[i] = malloc(sizeof(buffer));
    long int sys = systemcall(801,buf,8)
//print out buf 
   return 0;
   }

在系统调用中我有

asmlinkage long sys_something(buffer **buf,int size)
{
//allocate buffer same as it appears in int main
//fill buf with some data
for(i = 0; i<size,i++)
copy_to_user(buf[i],buf[i],sizeof(buffer));

我很确定我做错了什么。实际上如何将数据从内核 space 复制到用户 space ?

P.s。我正在使用 linux 内核 3.16.0

函数copy_to_user用于将数据从内核地址space复制到用户程序的地址space。例如,将已分配kmalloc的缓冲区复制到用户提供的缓冲区。

编辑: 你的例子有点复杂,因为你传递了一个指针数组给系统调用。访问这些指针 您必须首先使用 copy_from_user.

将数组 buf 复制到内核 space

因此,您的内核代码应如下所示:

asmlinkage long sys_something(buffer **buf, int size)
{
    /* Allocate buffers_in_kernel on stack just for demonstration.
     * These buffers would normally allocated by kmalloc.
     */
    buffer buffers_in_kernel[size];
    buffer *user_pointers[size]; 
    int i;
    unsigned long res;

    /* Fill buffers_in_kernel with some data */
    for (i = 0; i < size; i++)
        buffers_in_kernel[i].n = i;  /* just some example data */

    /* Get user pointers for access in kernel space. 
     * This is a shallow copy, so that, the entries in user_pointers 
     * still point to the user space.
     */
    res = copy_from_user(user_pointers, buf, sizeof(buffer *) * size);
    /* TODO: check result here */

    /* Now copy data to user space. */
    for (i = 0; i < size; i++) {
         res = copy_to_user(user_pointers[i], &buffers_in_kernel[i], sizeof(buffer));
         /* TODO: check result here */
    }
}

最后但并非最不重要的一点是,您的 main 函数中存在错误。在第一个 malloc 调用中,它只分配足够的 space 用于 1 个指针而不是 8 个。它应该是:

int main(void)
{
  const int size = 8;
  buffer **buf = malloc(sizeof(buffer *) * size);
  for(int i=0; i<size; i++) buf[i] = malloc(sizeof(buffer));
  long int sys = systemcall(801,buf,size)
  //print out buf 
  return 0;
}