THIS_MODULE在Linux内核模块驱动程序中的意义是什么?

Anu*_*kar 8 linux linux-device-driver linux-kernel

在linux设备驱动程序开发中,file_operations结构使用"struct module*owner".

  • 当我们总是用它初始化时,这种结构的用途是什么THIS_MODULE
  • 该字段何时可以设置为NULL?

Kum*_*rav 9

该字段告诉谁是struct file_operations的所有者.这可以防止模块在运行时卸载.使用THIS_MODULE初始化时,当前模块保留对其的所有权


Cir*_*四事件 7

最小可运行示例

每当您创建内核模块时,内核的构建机制都会struct module为您生成一个对象,并指向THIS_MODULE它。

该结构体包含许多字段,其中一些字段可以使用模块宏进行设置,例如MODULE_VERSION.

此示例展示了如何访问该信息module_info.c::

#include <linux/module.h>
#include <linux/kernel.h>

static int myinit(void)
{
    /* Set by default based on the module file name. */
    pr_info("name    = %s\n", THIS_MODULE->name);
    pr_info("version = %s\n", THIS_MODULE->version);
    return 0;
}

static void myexit(void) {}

module_init(myinit)
module_exit(myexit)
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL");
Run Code Online (Sandbox Code Playgroud)

Dmesg 输出:

name    = module_info
version = 1.0
Run Code Online (Sandbox Code Playgroud)

某些MODULE_INFO字段还可以通过以下方式“访问”:

  • cat /sys/module/module_info/version
  • modinfo /module_info.ko | grep -E '^version:'

由于该对象的地址struct module在所有模块中必须是唯一的,因此它可以作为一个很好的论据,fops.owner如下所述: https: //stackoverflow.com/a/19468893/895245。这是该用法的一个最小示例

使用此 QEMU + Buildroot 设置在 Linux 内核 4.16 中进行了测试。


小智 1

file_operation是用于连接驱动程序的设备号和文件操作的主要结构之一。

  • 该结构体中有很多函数指针。第一个指针struct module *owner根本不是函数指针,而是指向<linux/module.h>.
  • 初始化为 时THIS_MODULE,它拥有该模块的所有权。
  • 初始化的主要原因之一struct module *ownerTHIS_MODULE为了防止模块在使用时被卸载。