Skip to content

Usage of lstat / stat from the linux kernel?

I’m hoping someone can fact check my assumptions on the question “Can lstat and/or stat be called form the Linux kernel 3.10.0 in Centos 7. I’ve been searching and reading as much as I can find and have only been able to confuse myself. I can’t tell if the examples I am finding are available to kernel space or user space only.

The basic question is, can I call lstat or stat from the kernel?

Specifically I am adding this to the exec.c under the fs directory.

The goal is to differentiate between files that are either symbolic links or hard links and is a learning experience only.

If this is true, would I be calling lstat/stat or the “64” version – I’m on an X86 architecture if that matters.

Added 11-18-2015 Per the comment below

// These two lines are in the original exec.c file
struct file *file;
file = do_filp_open(AT_FDCWD, &tmp, &open_exec_flags, LOOKUP_FOLLOW);

// In the open_exec function I added the following
struct stat buf;
int lstat(struct file, struct stat buf);
mm_segment_t security_old_fs;

security_old_fs = get_fs();
if (lstat(*file, buf) == -)
    printk(KERN_INFO "stat errorn");
    goto exit;

Then run “make” and see

LINK    vmlinux
LD      vmlinux.o
MODPOST vmlinux.o
GEN     .version
CHK     include/generated/compile.h
UPD     include/generated/compile.h
CC      init/version.o
D      init/built-in.o
fs/built-in.o: In function`open_exec':
/home/user/rpmbuild/SOURCES/linux-3.10.0-123.20.1.el7/fs/exec.c:946: undefined reference to `lstat'
make: *** [vmlinux] Error 1

Any pointers would be helpful.



There is no stat/lstat functions in the Linux kernel.

There are sys_stat/sys_lstat functions, which implements corresponded system calls, but calling these functions inside kernel is not recommended: these functions may use special conventions for passing arguments, which differ from the common conventions in the kernel.

Actually, there is vfs_stat function, which is called by sys_stat, and does the most work. Note, that this function expects name of the file be located in the user space. For use this function for kernel-allocated filename, set_fs approach can be used:

int my_stat(const char* name, struct kstat* stat)
    int res;
    mm_segment_t security_old_fs;

    security_old_fs = get_fs();

    res = vfs_stat((const char __user *)name, stat);


    return res;

Attributes of the file are stored in the variable of kernel’s type struct kstat, which is defined in include/linux/stat.h.

Similarly, vfs_lstat does the most work of sys_lstat.

Note, that both vfs_stat and vfs_lstat use 0/-E conventions for return value: 0 is returned on success, negative error code is returned on fail.

User contributions licensed under: CC BY-SA
8 People found this is helpful