-
Notifications
You must be signed in to change notification settings - Fork 0
/
modalias.cpp
105 lines (85 loc) · 2.46 KB
/
modalias.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/utsname.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libkmod.h>
#include <dirent.h>
#include "common.h"
namespace ldetect {
static std::string aliasdefault;
static std::string dirname("/lib/modules/");
static void set_default_alias_file(void) {
std::string fallback_aliases(table_name_dir + "fallback-modules.alias");
struct stat st_alias, st_fallback;
struct utsname buf;
uname(&buf);
dirname += buf.release;
std::string aliasfilename(dirname+"/modules.alias");
/* fallback on ldetect-lst's modules.alias and prefer it if more recent */
if (stat(aliasfilename.c_str(), &st_alias) ||
(!stat(fallback_aliases.c_str(), &st_fallback) && st_fallback.st_mtime > st_alias.st_mtime))
aliasdefault = fallback_aliases;
else
aliasdefault = aliasfilename;
}
struct kmod_ctx* modalias_init(void) {
if (aliasdefault.empty())
set_default_alias_file();
std::string dkms_file(table_name_dir + "dkms-modules.alias");
/* We only use canned aliases as last resort. */
const char *alias_filelist[] = {
"/run/modprobe.d",
"/etc/modprobe.d",
"/lib/modprobe.d",
"/lib/module-init-tools/ldetect-lst-modules.alias",
aliasdefault.c_str(),
dkms_file.c_str(),
nullptr,
};
/* Init libkmod */
struct kmod_ctx *ctx = kmod_new(dirname.c_str(), alias_filelist);
if (!ctx) {
fputs("Error: kmod_new() failed!\n", stderr);
kmod_unref(ctx);
ctx = nullptr;
}
kmod_load_resources(ctx);
return ctx;
}
std::vector<std::string> modalias_resolve_modules(struct kmod_ctx *ctx, const std::string &modalias) {
struct kmod_list *l = nullptr, *list = nullptr, *filtered = nullptr;
std::vector<std::string> modules;
int err = kmod_module_new_from_lookup(ctx, modalias.c_str(), &list);
if (err < 0)
goto exit;
// No module found...
if (list == nullptr)
goto exit;
// filter through blacklist
err = kmod_module_apply_filter(ctx, KMOD_FILTER_BLACKLIST, list, &filtered);
kmod_module_unref_list(list);
if (err <0)
goto exit;
list = filtered;
kmod_list_foreach(l, list) {
struct kmod_module *mod = kmod_module_get_module(l);
const char *str = kmod_module_get_name(mod);
if (modules.empty() || modules.back() != str)
modules.push_back(str);
kmod_module_unref(mod);
if (err < 0)
break;
}
kmod_module_unref_list(list);
exit:
return modules;
}
}