问题
I'm trying to do a stat on files,
struct kstat stat;
int error = vfs_stat ("/bin/ls", &stat); // /bin/ls exists
if (error)
{
printk (KERN_INFO "error code %d\n", error);
}
else
{
printk (KERN_INFO "mode of ls: %o\n", stat.mode);
printk (KERN_INFO "owner of ls: %o\n", stat.uid);
}
return error;
But error was always set to 14 (Bad Address), what's wrong with the code?
I'm running 3.9 kernel.
回答1:
vfs_stat() is defined as:
int vfs_stat(const char __user *name, struct kstat *stat);
and __user is defined as:
# define __user __attribute__((noderef, address_space(1)))
In other words, vfs_stat() only supports using filename that is pointer into user space, and should not be dereferenced inside kernel space. Note that "/bin/ls" does NOT point into user space, but into kernel space, and thus cannot be used here.
Actually, error message 14 (bad address) tells this issue right into your face :)
回答2:
Use the following code:
#include <linux/uaccess.h>
int error;
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
error = vfs_stat ("/bin/ls", &stat);
set_fs(old_fs);
...
来源:https://stackoverflow.com/questions/19195560/whats-wrong-with-vfs-stat-call