如何从 Linux 内核空间(即从自定义系统调用)添加自定义扩展属性

Pix*_*her 5 linux filesystems linux-kernel

如何添加像命令行函数setfattr -n user.custom_attrib -v 99 ex1.txt这样的扩展属性,但在内核中的自定义系统调用中进行添加。我已经看过了linux/xattrib.h,但我没有运气尝试从内核空间设置任何东西。每当我使用vfs_setxattr(struct dentry *, const char *, const void *, size_t, int);它时,它都会重新启动整个 VM。最后,我尝试添加一个新的整数类型作为文件的扩展属性,我还需要检索该扩展属性。我需要使用内核空间中允许的函数。

Pix*_*her 3

我能够使扩展属性起作用:vfs_setxattr(struct dentry *, const char *, const void *, size_t, int); 主要问题是想要传递const void *a 。char *该代码看起来像这样:

char * buf = "test\0";
int size = 5;     //number of bytes needed for attribute
int flag = 0;     //0 allows for replacement or creation of attribute
int err;          //gets error code negative error and positive success

err = vfs_setxattr(path_struct.dentry, "user.custom_attrib", buf, size, flag);
Run Code Online (Sandbox Code Playgroud)

我也能够开始vfs_getxattr(struct dentry *, const char *, const void *, size_t);工作了。缓冲区void *再次成为我陷入困境的地方。我必须分配一个缓冲区来保存正在传递的扩展属性。所以我的代码看起来像这样:

char buf[1024];
int size_buf = 1024;
int err;

err = vfs_getxattr(path_struct.dentry, "user.custom_attrib",buf, size_buf);
Run Code Online (Sandbox Code Playgroud)

所以现在 buf 将保存 dentry 中指定文件的值。错误代码对于弄清楚发生了什么非常有帮助。使用命令行工具也是如此。

要安装命令行工具:

sudo apt-get install attr
Run Code Online (Sandbox Code Playgroud)

要从命令行手动设置属性:

setfattr -n user.custom_attrib -v "test_if working" test.txt
Run Code Online (Sandbox Code Playgroud)

要从命令行手动获取属性:

getfattr -n user.custom_attrib test.txt  
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚是否可以将不同类型(例如 int)传递到扩展属性中,并且我的试验导致我多次破坏内核构建。希望这可以帮助一些人,或者如果有人有任何更正,请告诉我。