0
votes

I am currently writing a Linux Kernel Module (for the first time).

I am trying to use the stat function. I understand that regular imports are not going to work in Kernel code, so I imported their equivalent (that is what I thought...):

#include <linux/stat.h>
#include <linux/errno.h>
#include <linux/unistd.h>

I don't get any error about the imports directly, but I get the following messages:

  • error: implicit declaration of function ‘stat’ [-Werror=implicit-function-declaration]
  • error: ‘errno’ undeclared (first use in this function)

For the two lines respectively:

int ret = stat(pathname, statbuf);

and

errno = ENOENT;

Any help woule be welcome.

Thank you.

PS: I am working on Kali 4.9.0-kali4-amd64 but I am trying to write something generic, that could work on multiple versions of Linux.

1
If you're writing a system-call, then it should return the negative error code on error. E.g. return -ENOENT; if you want the system-call to fail with errno set to ENOENT. - Some programmer dude
Thank you. But I read that stat is returning -1 in case of error AND setting errno. That is why I was trying to do both. Should I just return ENOENT? - Julien Séveno-Piltant
Well first of all stat is the user-space system-call, what you should use instead I don't know myself. Secondly, system-calls should return the negative error code on error, as explained in my previous comment. Try looking at a few example system-calls (if that's what you're writing) to see how they do it. System-calls and error handling is handled very differently inside the kernel than from user-space. - Some programmer dude
I read the stat source code and it does exactly what you said. Thank you. I get it. - Julien Séveno-Piltant

1 Answers

-2
votes

First of all you most likely don't want to stat, regardless of what the implementation is. In the worst case you are supposed to either have 'struct file' object or straight up a pointer to dentry to the file you are interested in. Then in the unlikely case you need to obtain the info provided by stat you can use the appropriate routine which takes the file or dentry. Then you can continue operating on the file you are already have the pointer to. Just performing stat and then deciding what to do is typically a security or reliability problem: by the time you e.g. decide to open the target path, it can be a completely different file - someone could have removed the one present at the time of your stat call and planted a new one. This is part of the standard bug class: Time Of Check Time Of Use.

Second, there is no 'errno' variable in the kernel and the fact that you are trying to use it strongly suggests you are a very junior programmer. For this reason I suspect you should refrain from playing with the kernel for the time being.

You also probably want to read this paper: http://www.watson.org/~robert/2007woot/2007usenixwoot-exploitingconcurrency.pdf

So, what exactly are you trying to implement?