我建议在您的代码中更加防御:
#include <linux/module.h>
#include <linux/capability.h>
int do_my_work(void)
{
struct module *mod;
char name[MODULE_NAME_LEN];
int ret, forced = 0;
if (!capable(CAP_SYS_MODULE) || modules_disabled)
return -EPERM;
/* Set up the name, yada yada */
name[MODULE_NAME_LEN - 1] = '\0';
/* Unless you absolutely need an uninterruptible wait, do this. */
if (mutex_lock_interruptible(&module_mutex) != 0) {
ret = -EINTR;
goto out_stop;
}
mod = find_module(name);
if (!mod) {
ret = -ENOENT;
goto out;
}
if (!list_empty(&mod->modules_which_use_me)) {
/* Debug it. */
}
out:
mutex_unlock(&module_mutex);
out_stop:
return(ret);
}
module_mutex是内核在对模块的各种操作中获取的。它们都在/kernel/module.c中并且是:
- 单独初始化每个模块以及所有模块时(例如在启动时)。
- 删除模块
- 等到没有人引用(使用)模块。
- 当 /proc 文件系统需要一个模块列表时(oprofile 和 co. 使用它)。
- 在tracepoint相关代码中;迭代和更新跟踪点。