0

I (and fellow classmates) cannot figure out the following question:

"Consider the following FOPS read() method:

ssize_t my_chrdrv_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
{
    char readBuf[] = "ABCD";
    copy_to_user(buf, readBuf, len);
    ...
}

The method is called with the parameter count=2. What should the size of 'len' be?"

We're not sure whether the answer is 2, because count is 2 - or if the answer is 5, because 'ABCD + /0' = 5.

Are we missing something here?

  • 1
    It should be 2. Under no circumstance can an api overflow the caller's buffer. So if the caller tells you the buffer is 2 bytes then the function is only allowed to access at most 2 bytes of that buffer. – kaylum Apr 06 '15 at 10:29
  • 2
    Actually, to be even more correct, you need to take into account f_pos. For example, if f_pos is referencing the last byte of the "file" then len should actually be only 1. That is, len needs to be something like: max(sizeof(readbuf) - f_pos, count). Of course, that's not the actual code because f_pos needs to be converted to an actual offset value. – kaylum Apr 06 '15 at 10:33
  • Thank you. However; In another example, it isn't specified what count is, and he does not use the parameter in the method at all. Instead, he has a char-array with the data "hello_world" He also has a char which contains the length of his char-array (sizeof("hello_world")) Then he sets 'len' to the length of his char-array. Count is not used at all in this example - so what can we make of this? What significance does count have? – Mathias Siig Nørregaard Apr 06 '15 at 10:39
  • 1
    I can't comment on what your lecturer is intending without th full context of what he is doing. So you'll need to clarify that with him directly. However, from an API perspective it's pretty standard. If the caller gives you a buffer and a size of the buffer then clearly you can't write more to the buffer than the indicated size. For a clear example, have a look at existing Linux apis like "read". Do "man read". It's directly applicable. In particualar: "read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf. " – kaylum Apr 06 '15 at 10:46

0 Answers0