Search code examples
cmodulelinux-kernelioctl

Weird behavior when passing strings to kernel module via IOCTL


I am passing a string to the IOCTL function using a pointer to a userspace struct with the parameters. My struct contains a pointer to the string, and I copy it to a local buffer to then use it. When I print the string from userspace, it is displayed correctly. However, when I printk it from the kernel module, I get some weird trailing characters, even if I copy it to a kernel allocated string of exactly the right string length (provided from userspace) and print that one. It is not only a printing bug, because the strings that I am passing are file paths, and if I try to create a file using those I get a file with the same gibberish name. Here's what I do inside the IOCTL:

    char *path = ((struct sparams*) ioctl_param)->path;
    printk(KERN_ALERT "User provided string: %s.\n", path);

    size_t path_len = ((struct sparams*) ioctl_param)->path_len;
    char kern_path[path_len + TRAILING]; // I leave some trailing bytes because I want to add a suffix later
    copy_from_user(kern_path, path, path_len);
    printk(KERN_ALERT "Copied string: %s.\n", kern_path);

In both cases I get some gibberish characters after the regular string passed as a parameter. What might I be doing wrong?


Solution

  • Strings to be printed via %s must have terminating null-character at their end.

    copy_from_user(kern_path, path, path_len);
    kern_path[path_len] = '\0'; /* add this */
    printk(KERN_ALERT "Copied string: %s.\n", kern_path);