2

I've created WRITE_IOCTL in kernel module and I call it in user mode:

ioctl(fd, WRITE_IOCTL, "Hello, Kernel!");

In kernel mode I have:

static int device_ioctl(struct file *filp,
    unsigned int cmd, unsigned long args) {
  char buff[14];

  switch (cmd) {
  case WRITE_IOCTL:
    copy_from_user( buff,(char *)args, 14);
    printk("This message received from User Space: %s\n", buff);
    break;
  }
  return 0;
}

When I run this ioctl, I have some thing like theses in /var/log/kern.log :

This message received from User Space: Hello, Kernel!vE�
This message received from User Space: Hello, Kernel!M�
This message received from User Space: Hello, Kernel!M�

How can I solve this problem??

Milad Khajavi
  • 2,769
  • 9
  • 41
  • 66

1 Answers1

5

Probably copy_from_user() isn't putting the null-byte-terminattor because args is greater-or-equal than your n and printk() is expecting a null-terminatted one, so you're accessing garbage values. For solve that, initialize yourself buf to zeros:

  char buff[14 + 1] = {0}; // +1 for make room to 0-byte-terminattor.

It will fill all bytes of buf with zeros.

EDIT:

As @caf mentioned in comments, you need to left some space to null-byte-terminattor. So, instead of give exactly the buffer size to function, pass it n-1 so the function will loop untl n and then put the null-byte.

The Mask
  • 17,007
  • 37
  • 111
  • 185