copy data from kernel space to user space

拜拜、爱过 提交于 2019-12-05 12:38:02

The function copy_to_user is used to copy data from the kernel address space to the address space of the user program. For example, to copy a buffer which has been allocated with kmalloc to the buffer provided by the user.

EDIT: Your example is a little bit more complex, because you pass an array of pointers to the system-call. To access these pointers you have to copy the array buf to kernel space first using copy_from_user.

Thus, your kernel code should look like this:

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 */
    }
}

Last but not least, there is a mistake in your main function. At the first malloc call, it allocates only enough space for 1 pointer instead of 8. It should be:

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!