Structures involved are like the following. struct node { int a; int b; }
struct ioctl_node {
struct node **ptr;
int count; //Stores the no of pointers this ptr is pointing to.
};
In user space, I have populated a structure of ioctl_node with count = 3
. And ptr[0]
and ptr[2]
is pointing to two structs of type node, whereas ptr[1]
is NULL
. I want this to be passed to kernel. I have issued ioctl call to pass this info from user space to kernel space.
I did the following in kernel space.
struct ioctl_node k_node;
copy_from_user(&k_node, arg, sizeof(struct ioctl_node)) //arg is the source
//k_node.count is showing the right value what I have set in the user space.
struct node *tmp = NULL;
I then did, copy_from_user(&tmp, k_node.ptr, sizeof(struct node *)
and this call is also returning success. But, I am having difficulty, in copying the full contents of **ptr
properly in kernel space. Can anybody plese help, how can I be able to do that. How should I do the next copy_from_user to copy all the contents. I tried, but its giving copy error.
copy_from_user
copies one block of consecutive bytes from user space to kernel space. You'll need to first copy the struct ioctl_node
, then copy the pointers to individual nodes, then copy the struct node
's in a loop. Be sure to allocate the right amount of memory. Since you know the number of nodes in advance, you can allocate an array of them.
struct node_data {
size_t node_count;
struct nodes *nodes;
};
struct node_data *read_nodes(struct ioctl_node_user_pointer *arg)
{
struct node_data *nd = NULL;
struct ioctl_node kin = {0};
struct node *node_user_pointers = NULL;
int i;
int err;
/* Step 1: retrieve the root node */
nd = kmalloc(sizeof(*nd), GFP_KERNEL);
if (!nd) {
err = -ENOMEM;
goto error;
}
if (copy_from_user(ioctl_node_user_pointer, &kin, sizeof(kin))) {
err = -EFAULT;
goto error;
}
if (kin->count < 0 || kin->count > ((size_t)-1)/sizeof(*nodes)) {
err = -EINVAL;
goto error;
}
nd->node_count = kin.count;
/* Step 2: retrieve the pointers to individual nodes */
node_user_pointers = kmalloc(sizeof(*node_user_pointers) * nd->node_count, GFP_KERNEL);
if (node_user_pointers) {
err = -ENOMEM;
goto error;
}
if (copy_from_user(kin->nodes, node_user_pointers, sizeof(*node_user_pointers) * nd->node_count)) {
err = -EFAULT;
goto error;
}
/* Step 3: retrieve the nodes themselves */
nd->nodes = kmalloc(sizeof(*nodes) * nd->node_count, GFP_KERNEL);
if (!nd->nodes) {
err = -ENOMEM;
goto error;
}
for (i = 0; i < head.count; i++) {
if (copy_from_user(node_user_pointers[i], nd->nodes + i, sizeof(nd->nodes[0]))) {
err = -EFAULT;
goto error;
}
}
kfree(node_user_pointers);
return nd;
error:
if (nd) {
kfree(nd->nodes);
kfree(nd);
}
kfree(node_user_pointers);
return ERR_PTR(err);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.