linux-kernel - 在给定文件路径的情况下检索 inode 结构

标签 linux-kernel

我已经看到很多关于从它的 inode 获取文件路径的问题,但几乎没有关于做相反的事情。我的内核模块需要这样做以获得有关传递给 open() 的请求主题的更多信息。 ,例如它的文件标志或它是否是一个设备。根据我从邮件列表、手册页和 Linux 源代码中搜集到的信息,我想出了这个小功能:

struct inode* get_inode_from_pathname(const char *pathname) {
    struct path path;
    kern_path(pathname, LOOKUP_FOLLOW, &path);
    return path.dentry->d_inode;
}

尝试在我的替换系统调用中使用它会使内核消息打印到控制台,但是:
struct inode *current_inode;
...
asmlinkage int custom_open(char const *__user file_name, int flags, int mode) {
    current_inode = get_inode_from_pathname(file_name);
    printk(KERN_INFO "intercepted: open(\"%s\", %X, %X)\n", file_name, flags, mode);
    printk(KERN_INFO "i_mode of %s:%hu\n", file_name, current_inode->i_mode);
    return real_open(file_name, flags, mode);
}

有一个更好的方法吗?我几乎可以肯定我的方式是错误的。

最佳答案

您可以使用 kern_path内核 API 从路径字符串中获取 inode 信息。该函数依次调用 do_path_lookup()执行路径查找操作的函数。您可以验证 kern_path 的结果通过打印从 i_ino 获得的 inode 的 inode 编号(inode 结构的 get_inode_from_pathname 字段)来发挥作用函数并将其与 ls 中的 inode 号匹配命令(ls -i <path of the file>)
我制作了以下内核模块,它没有使内核崩溃。我正在使用 2.6.39 内核。

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h> 
#include <linux/mount.h>
#include <linux/path.h>
#include <linux/namei.h>
#include <linux/fs.h>
#include <linux/namei.h>

char *path_name = "/home/shubham/test_prgs/temp.c";

int myinit(void)
{
    struct inode *inode;
    struct path path;
    kern_path(path_name, LOOKUP_FOLLOW, &path);
    inode = path.dentry->d_inode;
    printk("Path name : %s, inode :%lu\n", path_name, inode->i_ino);
    return 0;
}


void myexit(void)
{
    return;
}

module_init(myinit); 
module_exit(myexit);

//MODULE_AUTHOR("Shubham");
//MODULE_DESCRIPTION("Module to get inode from path");
MODULE_LICENSE("GPL");
MODULE_LICENSE("GPL v2");
你能发送崩溃堆栈跟踪吗?

关于linux-kernel - 在给定文件路径的情况下检索 inode 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27869570/

相关文章:

c - 为什么64位系统没有像creat这样的系统调用?

linux - 如何从内核代码 (BeagleBone Black) 访问或枚举可用的 LED?

c - 如何在 Windows 中将 linux header 添加到 Eclipse CDT

linux - 是否可以禁用 coreos 上的 spectre/meltdown/相关补丁?

linux - 如何在 linux 内核空间中读取环形缓冲区?

assembly - 在 Linux 内核中断处理程序中传递函数参数(从 asm 到 C)

c - Linux内核模块复制进程的.text段

linux-kernel - LINUX 系统中的互斥量和信号量是否为 "Busy wait"?

linux - 详解mkmakefile生成的Makefile(Linux内核、buildroot、busybox)

c - Linux 内核 0.11 中的进程 0 堆栈