2 * kmod-depmod - calculate modules.dep using libkmod.
4 * Copyright (C) 2011-2013 ProFUSION embedded systems
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
33 #include <sys/utsname.h>
35 #include <shared/array.h>
36 #include <shared/hash.h>
37 #include <shared/macro.h>
38 #include <shared/util.h>
39 #include <shared/scratchbuf.h>
41 #include <libkmod/libkmod-internal.h>
48 #define DEFAULT_VERBOSE LOG_WARNING
49 static int verbose = DEFAULT_VERBOSE;
51 static const char CFG_BUILTIN_KEY[] = "built-in";
52 static const char CFG_EXTERNAL_KEY[] = "external";
53 static const char *default_cfg_paths[] = {
55 SYSCONFDIR "/depmod.d",
60 static const char cmdopts_s[] = "aAb:C:E:F:euqrvnP:wmVh";
61 static const struct option cmdopts[] = {
62 { "all", no_argument, 0, 'a' },
63 { "quick", no_argument, 0, 'A' },
64 { "basedir", required_argument, 0, 'b' },
65 { "config", required_argument, 0, 'C' },
66 { "symvers", required_argument, 0, 'E' },
67 { "filesyms", required_argument, 0, 'F' },
68 { "errsyms", no_argument, 0, 'e' },
69 { "unresolved-error", no_argument, 0, 'u' }, /* deprecated */
70 { "quiet", no_argument, 0, 'q' }, /* deprecated */
71 { "root", no_argument, 0, 'r' }, /* deprecated */
72 { "verbose", no_argument, 0, 'v' },
73 { "show", no_argument, 0, 'n' },
74 { "dry-run", no_argument, 0, 'n' },
75 { "symbol-prefix", required_argument, 0, 'P' },
76 { "warn", no_argument, 0, 'w' },
77 { "map", no_argument, 0, 'm' }, /* deprecated */
78 { "version", no_argument, 0, 'V' },
79 { "help", no_argument, 0, 'h' },
83 static void help(void)
86 "\t%s -[aA] [options] [forced_version]\n"
88 "If no arguments (except options) are given, \"depmod -a\" is assumed\n"
90 "depmod will output a dependency list suitable for the modprobe utility.\n"
93 "\t-a, --all Probe all modules\n"
94 "\t-A, --quick Only does the work if there's a new module\n"
95 "\t-e, --errsyms Report not supplied symbols\n"
96 "\t-n, --show Write the dependency file on stdout only\n"
97 "\t-P, --symbol-prefix Architecture symbol prefix\n"
98 "\t-C, --config=PATH Read configuration from PATH\n"
99 "\t-v, --verbose Enable verbose mode\n"
100 "\t-w, --warn Warn on duplicates\n"
101 "\t-V, --version show version\n"
102 "\t-h, --help show this help\n"
104 "The following options are useful for people managing distributions:\n"
105 "\t-b, --basedir=DIR Use an image of a module tree.\n"
106 "\t-F, --filesyms=FILE Use the file instead of the\n"
107 "\t current kernel symbols.\n"
108 "\t-E, --symvers=FILE Use Module.symvers file to check\n"
109 "\t symbol versions.\n",
110 program_invocation_short_name);
113 _printf_format_(1, 2)
114 static inline void _show(const char *fmt, ...)
118 if (verbose <= DEFAULT_VERBOSE)
122 vfprintf(stdout, fmt, args);
126 #define SHOW(...) _show(__VA_ARGS__)
129 /* binary index write *************************************************/
130 #include <arpa/inet.h>
131 /* BEGIN: code from module-init-tools/index.c just modified to compile here.
133 * Original copyright:
134 * index.c: module index file shared functions for modprobe and depmod
135 * Copyright (C) 2008 Alan Jenkins <alan-jenkins@tuffmail.co.uk>.
137 * These programs are free software; you can redistribute it and/or modify
138 * it under the terms of the GNU General Public License as published by
139 * the Free Software Foundation; either version 2 of the License, or
140 * (at your option) any later version.
142 * This program is distributed in the hope that it will be useful,
143 * but WITHOUT ANY WARRANTY; without even the implied warranty of
144 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
145 * GNU General Public License for more details.
147 * You should have received a copy of the GNU General Public License
148 * along with these programs. If not, see <http://www.gnu.org/licenses/>.
151 /* see documentation in libkmod/libkmod-index.c */
153 #define INDEX_MAGIC 0xB007F457
154 #define INDEX_VERSION_MAJOR 0x0002
155 #define INDEX_VERSION_MINOR 0x0001
156 #define INDEX_VERSION ((INDEX_VERSION_MAJOR<<16)|INDEX_VERSION_MINOR)
157 #define INDEX_CHILDMAX 128
160 struct index_value *next;
161 unsigned int priority;
165 /* In-memory index (depmod only) */
167 char *prefix; /* path compression */
168 struct index_value *values;
169 unsigned char first; /* range of child nodes */
171 struct index_node *children[INDEX_CHILDMAX]; /* indexed by character */
175 /* Format of node offsets within index file */
177 INDEX_NODE_FLAGS = 0xF0000000, /* Flags in high nibble */
178 INDEX_NODE_PREFIX = 0x80000000,
179 INDEX_NODE_VALUES = 0x40000000,
180 INDEX_NODE_CHILDS = 0x20000000,
182 INDEX_NODE_MASK = 0x0FFFFFFF, /* Offset value */
185 static struct index_node *index_create(void)
187 struct index_node *node;
189 node = NOFAIL(calloc(sizeof(struct index_node), 1));
190 node->prefix = NOFAIL(strdup(""));
191 node->first = INDEX_CHILDMAX;
196 static void index_values_free(struct index_value *values)
199 struct index_value *value = values;
201 values = value->next;
206 static void index_destroy(struct index_node *node)
210 for (c = node->first; c <= node->last; c++) {
211 struct index_node *child = node->children[c];
214 index_destroy(child);
216 index_values_free(node->values);
221 static void index__checkstring(const char *str)
225 for (i = 0; str[i]; i++) {
228 if (ch >= INDEX_CHILDMAX)
229 CRIT("Module index: bad character '%c'=0x%x - only 7-bit ASCII is supported:"
230 "\n%s\n", (char) ch, (int) ch, str);
234 static int index_add_value(struct index_value **values,
235 const char *value, unsigned int priority)
237 struct index_value *v;
241 /* report the presence of duplicate values */
242 for (v = *values; v; v = v->next) {
243 if (streq(v->value, value))
247 /* find position to insert value */
248 while (*values && (*values)->priority < priority)
249 values = &(*values)->next;
252 v = NOFAIL(calloc(sizeof(struct index_value) + len + 1, 1));
254 v->priority = priority;
255 memcpy(v->value, value, len + 1);
261 static int index_insert(struct index_node *node, const char *key,
262 const char *value, unsigned int priority)
264 int i = 0; /* index within str */
267 index__checkstring(key);
268 index__checkstring(value);
271 int j; /* index within node->prefix */
273 /* Ensure node->prefix is a prefix of &str[i].
274 If it is not already, then we must split node. */
275 for (j = 0; node->prefix[j]; j++) {
276 ch = node->prefix[j];
278 if (ch != key[i+j]) {
279 char *prefix = node->prefix;
280 struct index_node *n;
282 /* New child is copy of node with prefix[j+1..N] */
283 n = NOFAIL(calloc(sizeof(struct index_node), 1));
284 memcpy(n, node, sizeof(struct index_node));
285 n->prefix = NOFAIL(strdup(&prefix[j+1]));
287 /* Parent has prefix[0..j], child at prefix[j] */
288 memset(node, 0, sizeof(struct index_node));
290 node->prefix = prefix;
293 node->children[ch] = n;
298 /* j is now length of node->prefix */
303 return index_add_value(&node->values, value, priority);
305 if (!node->children[ch]) {
306 struct index_node *child;
308 if (ch < node->first)
312 node->children[ch] = NOFAIL(calloc(sizeof(struct index_node), 1));
314 child = node->children[ch];
315 child->prefix = NOFAIL(strdup(&key[i+1]));
316 child->first = INDEX_CHILDMAX;
317 index_add_value(&child->values, value, priority);
322 /* Descend into child node and continue */
323 node = node->children[ch];
328 static int index__haschildren(const struct index_node *node)
330 return node->first < INDEX_CHILDMAX;
333 /* Recursive post-order traversal
335 Pre-order would make for better read-side buffering / readahead / caching.
336 (post-order means you go backwards in the file as you descend the tree).
337 However, index reading is already fast enough.
338 Pre-order is simpler for writing, and depmod is already slow.
340 static uint32_t index_write__node(const struct index_node *node, FILE *out)
342 uint32_t *child_offs = NULL;
349 /* Write children and save their offsets */
350 if (index__haschildren(node)) {
351 const struct index_node *child;
354 child_count = node->last - node->first + 1;
355 child_offs = NOFAIL(malloc(child_count * sizeof(uint32_t)));
357 for (i = 0; i < child_count; i++) {
358 child = node->children[node->first + i];
359 child_offs[i] = htonl(index_write__node(child, out));
363 /* Now write this node */
366 if (node->prefix[0]) {
367 fputs(node->prefix, out);
369 offset |= INDEX_NODE_PREFIX;
373 fputc(node->first, out);
374 fputc(node->last, out);
375 fwrite(child_offs, sizeof(uint32_t), child_count, out);
376 offset |= INDEX_NODE_CHILDS;
382 const struct index_value *v;
383 unsigned int value_count;
387 for (v = node->values; v != NULL; v = v->next)
389 u = htonl(value_count);
390 fwrite(&u, sizeof(u), 1, out);
392 for (v = node->values; v != NULL; v = v->next) {
393 u = htonl(v->priority);
394 fwrite(&u, sizeof(u), 1, out);
395 fputs(v->value, out);
398 offset |= INDEX_NODE_VALUES;
404 static void index_write(const struct index_node *node, FILE *out)
406 long initial_offset, final_offset;
409 u = htonl(INDEX_MAGIC);
410 fwrite(&u, sizeof(u), 1, out);
411 u = htonl(INDEX_VERSION);
412 fwrite(&u, sizeof(u), 1, out);
414 /* Second word is reserved for the offset of the root node */
415 initial_offset = ftell(out);
416 assert(initial_offset >= 0);
418 fwrite(&u, sizeof(uint32_t), 1, out);
421 u = htonl(index_write__node(node, out));
423 /* Update first word */
424 final_offset = ftell(out);
425 assert(final_offset >= 0);
426 (void)fseek(out, initial_offset, SEEK_SET);
427 fwrite(&u, sizeof(uint32_t), 1, out);
428 (void)fseek(out, final_offset, SEEK_SET);
431 /* END: code from module-init-tools/index.c just modified to compile here.
434 /* configuration parsing **********************************************/
435 struct cfg_override {
436 struct cfg_override *next;
448 struct cfg_search *next;
449 enum search_type type;
454 struct cfg_external {
455 struct cfg_external *next;
461 const char *kversion;
462 char dirname[PATH_MAX];
465 uint8_t check_symvers;
466 uint8_t print_unknown;
468 struct cfg_override *overrides;
469 struct cfg_search *searches;
470 struct cfg_external *externals;
473 static enum search_type cfg_define_search_type(const char *path)
475 if (streq(path, CFG_BUILTIN_KEY))
476 return SEARCH_BUILTIN;
477 if (streq(path, CFG_EXTERNAL_KEY))
478 return SEARCH_EXTERNAL;
482 static int cfg_search_add(struct cfg *cfg, const char *path)
484 struct cfg_search *s;
486 enum search_type type;
488 type = cfg_define_search_type(path);
490 if (type != SEARCH_PATH)
493 len = strlen(path) + 1;
495 s = malloc(sizeof(struct cfg_search) + len);
497 ERR("search add: out of memory\n");
501 if (type != SEARCH_PATH)
505 memcpy(s->path, path, len);
508 DBG("search add: %s, search type=%hhu\n", path, type);
510 s->next = cfg->searches;
515 static void cfg_search_free(struct cfg_search *s)
520 static int cfg_override_add(struct cfg *cfg, const char *modname, const char *subdir)
522 struct cfg_override *o;
523 size_t modnamelen = strlen(modname);
524 size_t subdirlen = strlen(subdir);
527 o = malloc(sizeof(struct cfg_override) + subdirlen + 1
530 ERR("override add: out of memory\n");
533 memcpy(o->path, subdir, subdirlen);
538 memcpy(o->path + i, modname, modnamelen);
540 o->path[i] = '\0'; /* no extension, so we can match .ko/.ko.gz */
544 DBG("override add: %s\n", o->path);
546 o->next = cfg->overrides;
551 static void cfg_override_free(struct cfg_override *o)
556 static int cfg_external_add(struct cfg *cfg, const char *path)
558 struct cfg_external *ext;
559 size_t len = strlen(path);
561 ext = malloc(sizeof(struct cfg_external) + len + 1);
563 ERR("external add: out of memory\n");
567 strcpy(ext->path, path);
570 DBG("external add: %s\n", ext->path);
572 ext->next = cfg->externals;
573 cfg->externals = ext;
577 static void cfg_external_free(struct cfg_external *ext)
582 static int cfg_kernel_matches(const struct cfg *cfg, const char *pattern)
588 if (streq(pattern, "*"))
591 if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
594 status = regexec(&re, cfg->kversion, 0, NULL, 0);
600 static int cfg_file_parse(struct cfg *cfg, const char *filename)
604 unsigned int linenum = 0;
607 fp = fopen(filename, "r");
610 ERR("file parse %s: %m\n", filename);
614 while ((line = freadline_wrapped(fp, &linenum)) != NULL) {
617 if (line[0] == '\0' || line[0] == '#')
620 cmd = strtok_r(line, "\t ", &saveptr);
624 if (streq(cmd, "search")) {
626 while ((sp = strtok_r(NULL, "\t ", &saveptr)) != NULL) {
627 cfg_search_add(cfg, sp);
629 } else if (streq(cmd, "override")) {
630 const char *modname = strtok_r(NULL, "\t ", &saveptr);
631 const char *version = strtok_r(NULL, "\t ", &saveptr);
632 const char *subdir = strtok_r(NULL, "\t ", &saveptr);
634 if (modname == NULL || version == NULL ||
638 if (!cfg_kernel_matches(cfg, version)) {
639 INF("%s:%u: override kernel did not match %s\n",
640 filename, linenum, version);
644 cfg_override_add(cfg, modname, subdir);
645 } else if (streq(cmd, "external")) {
646 const char *version = strtok_r(NULL, "\t ", &saveptr);
647 const char *dir = strtok_r(NULL, "\t ", &saveptr);
649 if (version == NULL || dir == NULL)
652 if (!cfg_kernel_matches(cfg, version)) {
653 INF("%s:%u: external directory did not match %s\n",
654 filename, linenum, version);
658 cfg_external_add(cfg, dir);
659 } else if (streq(cmd, "include")
660 || streq(cmd, "make_map_files")) {
661 INF("%s:%u: command %s not implemented yet\n",
662 filename, linenum, cmd);
665 ERR("%s:%u: ignoring bad line starting with '%s'\n",
666 filename, linenum, cmd);
678 static int cfg_files_filter_out(DIR *d, const char *dir, const char *name)
680 size_t len = strlen(name);
686 if (len < 6 || !streq(name + len - 5, ".conf")) {
687 INF("All cfg files need .conf: %s/%s\n", dir, name);
691 fstatat(dirfd(d), name, &st, 0);
692 if (S_ISDIR(st.st_mode)) {
693 ERR("Directories inside directories are not supported: %s/%s\n",
708 static void cfg_file_free(struct cfg_file *f)
713 static int cfg_files_insert_sorted(struct cfg_file ***p_files, size_t *p_n_files,
714 const char *dir, const char *name)
716 struct cfg_file **files, *f;
717 size_t i, n_files, namelen, dirlen;
720 dirlen = strlen(dir);
722 namelen = strlen(name);
724 name = basename(dir);
725 namelen = strlen(name);
726 dirlen -= namelen + 1;
729 n_files = *p_n_files;
731 for (i = 0; i < n_files; i++) {
732 int cmp = strcmp(name, files[i]->name);
734 DBG("Ignoring duplicate config file: %.*s/%s\n",
735 (int)dirlen, dir, name);
741 f = malloc(sizeof(struct cfg_file) + dirlen + namelen + 2);
743 ERR("files insert sorted: out of memory\n");
747 tmp = realloc(files, sizeof(struct cfg_file *) * (n_files + 1));
749 ERR("files insert sorted: out of memory\n");
753 *p_files = files = tmp;
756 memmove(files + i + 1, files + i,
757 sizeof(struct cfg_file *) * (n_files - i));
762 f->namelen = namelen;
763 f->name = f->path + dirlen + 1;
764 memcpy(f->path, dir, dirlen);
765 f->path[dirlen] = '/';
766 memcpy(f->path + dirlen + 1, name, namelen);
767 f->path[dirlen + 1 + namelen] = '\0';
769 *p_n_files = n_files + 1;
774 * Insert configuration files ignoring duplicates
776 static int cfg_files_list(struct cfg_file ***p_files, size_t *p_n_files,
784 if (stat(path, &st) != 0) {
786 DBG("could not stat '%s': %m\n", path);
790 if (!S_ISDIR(st.st_mode)) {
791 cfg_files_insert_sorted(p_files, p_n_files, path, NULL);
797 ERR("files list %s: %m\n", path);
801 for (dent = readdir(d); dent != NULL; dent = readdir(d)) {
802 if (cfg_files_filter_out(d, path, dent->d_name))
805 cfg_files_insert_sorted(p_files, p_n_files, path, dent->d_name);
809 DBG("parsed configuration files from %s\n", path);
813 static int cfg_load(struct cfg *cfg, const char * const *cfg_paths)
815 size_t i, n_files = 0;
816 struct cfg_file **files = NULL;
818 if (cfg_paths == NULL)
819 cfg_paths = default_cfg_paths;
821 for (i = 0; cfg_paths[i] != NULL; i++)
822 cfg_files_list(&files, &n_files, cfg_paths[i]);
824 for (i = 0; i < n_files; i++) {
825 struct cfg_file *f = files[i];
826 cfg_file_parse(cfg, f->path);
831 /* For backward compatibility add "updates" to the head of the search
832 * list here. But only if there was no "search" option specified.
834 if (cfg->searches == NULL)
835 cfg_search_add(cfg, "updates");
840 static void cfg_free(struct cfg *cfg)
842 while (cfg->overrides) {
843 struct cfg_override *tmp = cfg->overrides;
844 cfg->overrides = cfg->overrides->next;
845 cfg_override_free(tmp);
848 while (cfg->searches) {
849 struct cfg_search *tmp = cfg->searches;
850 cfg->searches = cfg->searches->next;
851 cfg_search_free(tmp);
854 while (cfg->externals) {
855 struct cfg_external *tmp = cfg->externals;
856 cfg->externals = cfg->externals->next;
857 cfg_external_free(tmp);
862 /* depmod calculations ***********************************************/
865 struct kmod_module *kmod;
867 const char *relpath; /* path relative to '$ROOT/lib/modules/$VER/' */
868 char *uncrelpath; /* same as relpath but ending in .ko */
869 struct kmod_list *info_list;
870 struct kmod_list *dep_sym_list;
871 struct array deps; /* struct symbol */
872 size_t baselen; /* points to start of basename/filename */
874 int sort_idx; /* sort index using modules.order */
875 int dep_sort_idx; /* topological sort index */
876 uint16_t idx; /* index in depmod->modules.array */
877 uint16_t users; /* how many modules depend on this one */
878 bool visited; /* helper field to report cycles */
879 struct vertex *vertex; /* helper field to report cycles */
890 const struct cfg *cfg;
891 struct kmod_ctx *ctx;
892 struct array modules;
893 struct hash *modules_by_uncrelpath;
894 struct hash *modules_by_name;
895 struct hash *symbols;
898 static void mod_free(struct mod *mod)
900 DBG("free %p kmod=%p, path=%s\n", mod, mod->kmod, mod->path);
901 array_free_array(&mod->deps);
902 kmod_module_unref(mod->kmod);
903 kmod_module_info_free_list(mod->info_list);
904 kmod_module_dependency_symbols_free_list(mod->dep_sym_list);
905 free(mod->uncrelpath);
910 static int mod_add_dependency(struct mod *mod, struct symbol *sym)
914 DBG("%s depends on %s %s\n", mod->path, sym->name,
915 sym->owner != NULL ? sym->owner->path : "(unknown)");
917 if (sym->owner == NULL)
920 err = array_append_unique(&mod->deps, sym->owner);
927 SHOW("%s needs \"%s\": %s\n", mod->path, sym->name, sym->owner->path);
931 static void symbol_free(struct symbol *sym)
933 DBG("free %p sym=%s, owner=%p %s\n", sym, sym->name, sym->owner,
934 sym->owner != NULL ? sym->owner->path : "");
938 static int depmod_init(struct depmod *depmod, struct cfg *cfg,
939 struct kmod_ctx *ctx)
946 array_init(&depmod->modules, 128);
948 depmod->modules_by_uncrelpath = hash_new(512, NULL);
949 if (depmod->modules_by_uncrelpath == NULL) {
951 goto modules_by_uncrelpath_failed;
954 depmod->modules_by_name = hash_new(512, NULL);
955 if (depmod->modules_by_name == NULL) {
957 goto modules_by_name_failed;
960 depmod->symbols = hash_new(2048, (void (*)(void *))symbol_free);
961 if (depmod->symbols == NULL) {
969 hash_free(depmod->modules_by_name);
970 modules_by_name_failed:
971 hash_free(depmod->modules_by_uncrelpath);
972 modules_by_uncrelpath_failed:
976 static void depmod_shutdown(struct depmod *depmod)
980 hash_free(depmod->symbols);
982 hash_free(depmod->modules_by_uncrelpath);
984 hash_free(depmod->modules_by_name);
986 for (i = 0; i < depmod->modules.count; i++)
987 mod_free(depmod->modules.array[i]);
988 array_free_array(&depmod->modules);
990 kmod_unref(depmod->ctx);
993 static int depmod_module_add(struct depmod *depmod, struct kmod_module *kmod)
995 const struct cfg *cfg = depmod->cfg;
996 const char *modname, *lastslash;
1001 modname = kmod_module_get_name(kmod);
1002 modnamesz = strlen(modname) + 1;
1004 mod = calloc(1, sizeof(struct mod) + modnamesz);
1008 mod->sort_idx = depmod->modules.count + 1;
1009 mod->dep_sort_idx = INT32_MAX;
1010 memcpy(mod->modname, modname, modnamesz);
1011 mod->modnamesz = modnamesz;
1013 array_init(&mod->deps, 4);
1015 mod->path = strdup(kmod_module_get_path(kmod));
1016 lastslash = strrchr(mod->path, '/');
1017 mod->baselen = lastslash - mod->path;
1018 if (strncmp(mod->path, cfg->dirname, cfg->dirnamelen) == 0 &&
1019 mod->path[cfg->dirnamelen] == '/')
1020 mod->relpath = mod->path + cfg->dirnamelen + 1;
1022 mod->relpath = NULL;
1024 err = hash_add_unique(depmod->modules_by_name, mod->modname, mod);
1026 ERR("hash_add_unique %s: %s\n", mod->modname, strerror(-err));
1030 if (mod->relpath != NULL) {
1031 size_t uncrelpathlen = lastslash - mod->relpath + modnamesz
1032 + strlen(KMOD_EXTENSION_UNCOMPRESSED);
1033 mod->uncrelpath = memdup(mod->relpath, uncrelpathlen + 1);
1034 mod->uncrelpath[uncrelpathlen] = '\0';
1035 err = hash_add_unique(depmod->modules_by_uncrelpath,
1036 mod->uncrelpath, mod);
1038 ERR("hash_add_unique %s: %s\n",
1039 mod->uncrelpath, strerror(-err));
1040 hash_del(depmod->modules_by_name, mod->modname);
1045 DBG("add %p kmod=%p, path=%s\n", mod, kmod, mod->path);
1050 free(mod->uncrelpath);
1055 static int depmod_module_del(struct depmod *depmod, struct mod *mod)
1057 DBG("del %p kmod=%p, path=%s\n", mod, mod->kmod, mod->path);
1059 if (mod->uncrelpath != NULL)
1060 hash_del(depmod->modules_by_uncrelpath, mod->uncrelpath);
1062 hash_del(depmod->modules_by_name, mod->modname);
1068 static const char *search_to_string(const struct cfg_search *s)
1071 case SEARCH_EXTERNAL:
1073 case SEARCH_BUILTIN:
1080 static bool depmod_is_path_starts_with(const char *path,
1085 if (pathlen <= prefix_len)
1087 if (path[prefix_len] != '/')
1089 if (memcmp(path, prefix, prefix_len) != 0)
1095 /* returns if existing module @mod is higher priority than newpath.
1096 * note this is the inverse of module-init-tools is_higher_priority()
1098 static int depmod_module_is_higher_priority(const struct depmod *depmod, const struct mod *mod, size_t baselen, size_t namelen, size_t modnamelen, const char *newpath)
1100 const struct cfg *cfg = depmod->cfg;
1101 const struct cfg_override *ov;
1102 const struct cfg_search *se;
1103 const struct cfg_external *ext;
1105 /* baselen includes the last '/' and mod->baselen doesn't. So it's
1106 * actually correct to use modnamelen in the first and modnamesz in
1108 size_t newlen = baselen + modnamelen;
1109 size_t oldlen = mod->baselen + mod->modnamesz;
1110 const char *oldpath = mod->path;
1111 int i, bprio = -1, oldprio = -1, newprio = -1;
1112 size_t relnewlen = 0;
1113 size_t reloldlen = 0;
1114 const char *relnewpath = NULL;
1115 const char *reloldpath = NULL;
1117 DBG("comparing priorities of %s and %s\n",
1120 if (strncmp(newpath, cfg->dirname, cfg->dirnamelen) == 0) {
1121 relnewpath = newpath + cfg->dirnamelen + 1;
1122 relnewlen = newlen - (cfg->dirnamelen + 1);
1124 if (strncmp(oldpath, cfg->dirname, cfg->dirnamelen) == 0) {
1125 reloldpath = oldpath + cfg->dirnamelen + 1;
1126 reloldlen = oldlen - (cfg->dirnamelen + 1);
1129 for (ov = cfg->overrides; ov != NULL; ov = ov->next) {
1130 DBG("override %s\n", ov->path);
1131 if (relnewlen == ov->len &&
1132 memcmp(ov->path, relnewpath, relnewlen) == 0)
1134 if (reloldlen == ov->len &&
1135 memcmp(ov->path, reloldpath, reloldlen) == 0)
1139 for (i = 0, se = cfg->searches; se != NULL; se = se->next, i++) {
1140 DBG("search %s\n", search_to_string(se));
1141 if (se->type == SEARCH_BUILTIN)
1143 else if (se->type == SEARCH_EXTERNAL) {
1144 for (ext = cfg->externals; ext != NULL; ext = ext->next, i++) {
1145 if (depmod_is_path_starts_with(newpath,
1150 if (depmod_is_path_starts_with(oldpath,
1156 } else if (relnewlen > se->len && relnewpath[se->len] == '/' &&
1157 memcmp(se->path, relnewpath, se->len) == 0)
1159 else if (reloldlen > se->len && reloldpath[se->len] == '/' &&
1160 memcmp(se->path, reloldpath, se->len) == 0)
1169 DBG("priorities: built-in: %d, old: %d, new: %d\n",
1170 bprio, oldprio, newprio);
1172 return newprio <= oldprio;
1175 static int depmod_modules_search_file(struct depmod *depmod, size_t baselen, size_t namelen, const char *path)
1177 struct kmod_module *kmod;
1179 const char *relpath;
1180 char modname[PATH_MAX];
1184 if (!path_ends_with_kmod_ext(path + baselen, namelen))
1187 if (path_to_modname(path, modname, &modnamelen) == NULL) {
1188 ERR("could not get modname from path %s\n", path);
1192 relpath = path + depmod->cfg->dirnamelen + 1;
1193 DBG("try %s (%s)\n", relpath, modname);
1195 mod = hash_find(depmod->modules_by_name, modname);
1199 if (depmod_module_is_higher_priority(depmod, mod, baselen,
1200 namelen, modnamelen, path)) {
1201 DBG("Ignored lower priority: %s, higher: %s\n",
1206 DBG("Replace lower priority %s with new module %s\n",
1207 mod->relpath, relpath);
1208 err = depmod_module_del(depmod, mod);
1210 ERR("could not del module %s: %s\n", mod->path, strerror(-err));
1215 err = kmod_module_new_from_path(depmod->ctx, path, &kmod);
1217 ERR("could not create module %s: %s\n", path, strerror(-err));
1221 err = depmod_module_add(depmod, kmod);
1223 ERR("could not add module %s: %s\n",
1224 path, strerror(-err));
1225 kmod_module_unref(kmod);
1231 static int depmod_modules_search_dir(struct depmod *depmod, DIR *d, size_t baselen, struct scratchbuf *s_path)
1234 int err = 0, dfd = dirfd(d);
1237 while ((de = readdir(d)) != NULL) {
1238 const char *name = de->d_name;
1242 if (name[0] == '.' && (name[1] == '\0' ||
1243 (name[1] == '.' && name[2] == '\0')))
1245 if (streq(name, "build") || streq(name, "source"))
1247 namelen = strlen(name);
1248 if (scratchbuf_alloc(s_path, baselen + namelen + 2) < 0) {
1254 path = scratchbuf_str(s_path);
1255 memcpy(path + baselen, name, namelen + 1);
1257 if (de->d_type == DT_REG)
1259 else if (de->d_type == DT_DIR)
1263 if (fstatat(dfd, name, &st, 0) < 0) {
1264 ERR("fstatat(%d, %s): %m\n", dfd, name);
1266 } else if (S_ISREG(st.st_mode))
1268 else if (S_ISDIR(st.st_mode))
1271 ERR("unsupported file type %s: %o\n",
1272 path, st.st_mode & S_IFMT);
1280 fd = openat(dfd, name, O_RDONLY);
1282 ERR("openat(%d, %s, O_RDONLY): %m\n",
1286 subdir = fdopendir(fd);
1287 if (subdir == NULL) {
1288 ERR("fdopendir(%d): %m\n", fd);
1292 path[baselen + namelen] = '/';
1293 path[baselen + namelen + 1] = '\0';
1294 err = depmod_modules_search_dir(depmod, subdir,
1295 baselen + namelen + 1,
1299 err = depmod_modules_search_file(depmod, baselen,
1304 path[baselen + namelen] = '\0';
1305 ERR("failed %s: %s\n", path, strerror(-err));
1306 err = 0; /* ignore errors */
1312 static int depmod_modules_search_path(struct depmod *depmod,
1316 _cleanup_(scratchbuf_release) struct scratchbuf s_path_buf =
1317 SCRATCHBUF_INITIALIZER(buf);
1326 ERR("could not open directory %s: %m\n", path);
1330 baselen = strlen(path);
1332 if (scratchbuf_alloc(&s_path_buf, baselen + 2) < 0) {
1336 path_buf = scratchbuf_str(&s_path_buf);
1338 memcpy(path_buf, path, baselen);
1339 path_buf[baselen] = '/';
1341 path_buf[baselen] = '\0';
1343 err = depmod_modules_search_dir(depmod, d, baselen, &s_path_buf);
1349 static int depmod_modules_search(struct depmod *depmod)
1352 struct cfg_external *ext;
1354 err = depmod_modules_search_path(depmod, depmod->cfg->dirname);
1358 for (ext = depmod->cfg->externals; ext != NULL; ext = ext->next) {
1359 err = depmod_modules_search_path(depmod, ext->path);
1360 if (err < 0 && err == -ENOENT)
1361 /* ignore external dir absense */
1368 static int mod_cmp(const void *pa, const void *pb) {
1369 const struct mod *a = *(const struct mod **)pa;
1370 const struct mod *b = *(const struct mod **)pb;
1371 return a->sort_idx - b->sort_idx;
1374 static int depmod_modules_build_array(struct depmod *depmod)
1376 struct hash_iter module_iter;
1380 hash_iter_init(depmod->modules_by_name, &module_iter);
1381 while (hash_iter_next(&module_iter, NULL, &v)) {
1382 struct mod *mod = (struct mod *) v;
1383 mod->idx = depmod->modules.count;
1384 err = array_append(&depmod->modules, mod);
1392 static FILE *dfdopen(const char *dname, const char *filename, int flags,
1398 dfd = open(dname, O_RDONLY);
1400 WRN("could not open directory %s: %m\n", dname);
1404 fd = openat(dfd, filename, flags);
1406 WRN("could not open %s at %s: %m\n", filename, dname);
1409 ret = fdopen(fd, mode);
1411 WRN("could not associate stream with %s: %m\n", filename);
1421 static void depmod_modules_sort(struct depmod *depmod)
1423 char line[PATH_MAX];
1424 const char *order_file = "modules.order";
1426 unsigned idx = 0, total = 0;
1428 fp = dfdopen(depmod->cfg->dirname, order_file, O_RDONLY, "r");
1432 while (fgets(line, sizeof(line), fp) != NULL) {
1433 size_t len = strlen(line);
1437 if (line[len - 1] != '\n') {
1438 ERR("%s/%s:%u corrupted line misses '\\n'\n",
1439 depmod->cfg->dirname, order_file, idx);
1445 fseek(fp, 0, SEEK_SET);
1446 while (fgets(line, sizeof(line), fp) != NULL) {
1447 size_t len = strlen(line);
1453 line[len - 1] = '\0';
1455 mod = hash_find(depmod->modules_by_uncrelpath, line);
1458 mod->sort_idx = idx - total;
1461 array_sort(&depmod->modules, mod_cmp);
1462 for (idx = 0; idx < depmod->modules.count; idx++) {
1463 struct mod *m = depmod->modules.array[idx];
1471 static int depmod_symbol_add(struct depmod *depmod, const char *name,
1472 bool prefix_skipped, uint64_t crc,
1473 const struct mod *owner)
1479 if (!prefix_skipped && (name[0] == depmod->cfg->sym_prefix))
1482 namelen = strlen(name) + 1;
1483 sym = malloc(sizeof(struct symbol) + namelen);
1487 sym->owner = (struct mod *)owner;
1489 memcpy(sym->name, name, namelen);
1491 err = hash_add(depmod->symbols, sym->name, sym);
1497 DBG("add %p sym=%s, owner=%p %s\n", sym, sym->name, owner,
1498 owner != NULL ? owner->path : "");
1503 static struct symbol *depmod_symbol_find(const struct depmod *depmod,
1506 if (name[0] == '.') /* PPC64 needs this: .foo == foo */
1508 if (name[0] == depmod->cfg->sym_prefix)
1510 return hash_find(depmod->symbols, name);
1513 static int depmod_load_modules(struct depmod *depmod)
1515 struct mod **itr, **itr_end;
1517 DBG("load symbols (%zd modules)\n", depmod->modules.count);
1519 itr = (struct mod **)depmod->modules.array;
1520 itr_end = itr + depmod->modules.count;
1521 for (; itr < itr_end; itr++) {
1522 struct mod *mod = *itr;
1523 struct kmod_list *l, *list = NULL;
1524 int err = kmod_module_get_symbols(mod->kmod, &list);
1527 DBG("ignoring %s: no symbols\n", mod->path);
1529 ERR("failed to load symbols from %s: %s\n",
1530 mod->path, strerror(-err));
1533 kmod_list_foreach(l, list) {
1534 const char *name = kmod_module_symbol_get_symbol(l);
1535 uint64_t crc = kmod_module_symbol_get_crc(l);
1536 depmod_symbol_add(depmod, name, false, crc, mod);
1538 kmod_module_symbols_free_list(list);
1541 kmod_module_get_info(mod->kmod, &mod->info_list);
1542 kmod_module_get_dependency_symbols(mod->kmod,
1543 &mod->dep_sym_list);
1544 kmod_module_unref(mod->kmod);
1548 DBG("loaded symbols (%zd modules, %u symbols)\n",
1549 depmod->modules.count, hash_get_count(depmod->symbols));
1554 static int depmod_load_module_dependencies(struct depmod *depmod, struct mod *mod)
1556 const struct cfg *cfg = depmod->cfg;
1557 struct kmod_list *l;
1559 DBG("do dependencies of %s\n", mod->path);
1560 kmod_list_foreach(l, mod->dep_sym_list) {
1561 const char *name = kmod_module_dependency_symbol_get_symbol(l);
1562 uint64_t crc = kmod_module_dependency_symbol_get_crc(l);
1563 int bindtype = kmod_module_dependency_symbol_get_bind(l);
1564 struct symbol *sym = depmod_symbol_find(depmod, name);
1565 uint8_t is_weak = bindtype == KMOD_SYMBOL_WEAK;
1568 DBG("%s needs (%c) unknown symbol %s\n",
1569 mod->path, bindtype, name);
1570 if (cfg->print_unknown && !is_weak)
1571 WRN("%s needs unknown symbol %s\n",
1576 if (cfg->check_symvers && sym->crc != crc && !is_weak) {
1577 DBG("symbol %s (%#"PRIx64") module %s (%#"PRIx64")\n",
1578 sym->name, sym->crc, mod->path, crc);
1579 if (cfg->print_unknown)
1580 WRN("%s disagrees about version of symbol %s\n",
1584 mod_add_dependency(mod, sym);
1590 static int depmod_load_dependencies(struct depmod *depmod)
1592 struct mod **itr, **itr_end;
1594 DBG("load dependencies (%zd modules, %u symbols)\n",
1595 depmod->modules.count, hash_get_count(depmod->symbols));
1597 itr = (struct mod **)depmod->modules.array;
1598 itr_end = itr + depmod->modules.count;
1599 for (; itr < itr_end; itr++) {
1600 struct mod *mod = *itr;
1602 if (mod->dep_sym_list == NULL) {
1603 DBG("ignoring %s: no dependency symbols\n", mod->path);
1607 depmod_load_module_dependencies(depmod, mod);
1610 DBG("loaded dependencies (%zd modules, %u symbols)\n",
1611 depmod->modules.count, hash_get_count(depmod->symbols));
1616 static int dep_cmp(const void *pa, const void *pb)
1618 const struct mod *a = *(const struct mod **)pa;
1619 const struct mod *b = *(const struct mod **)pb;
1620 return a->dep_sort_idx - b->dep_sort_idx;
1623 static void depmod_sort_dependencies(struct depmod *depmod)
1625 struct mod **itr, **itr_end;
1626 itr = (struct mod **)depmod->modules.array;
1627 itr_end = itr + depmod->modules.count;
1628 for (; itr < itr_end; itr++) {
1629 struct mod *m = *itr;
1630 if (m->deps.count > 1)
1631 array_sort(&m->deps, dep_cmp);
1636 struct vertex *parent;
1640 static struct vertex *vertex_new(struct mod *mod, struct vertex *parent)
1644 v = malloc(sizeof(*v));
1653 static void depmod_list_remove_data(struct kmod_list **list, void *data)
1655 struct kmod_list *l;
1657 l = kmod_list_remove_data(*list, data);
1661 static int depmod_report_one_cycle(struct depmod *depmod,
1662 struct vertex *vertex,
1663 struct kmod_list **roots,
1664 struct hash *loop_set)
1666 const char sep[] = " -> ";
1669 struct array reverse;
1675 array_init(&reverse, 3);
1678 for (v = vertex->parent, n = 0;
1680 v = v->parent, n++) {
1682 sz += v->mod->modnamesz - 1;
1683 array_append(&reverse, v);
1684 rc = hash_add(loop_set, v->mod->modname, NULL);
1687 /* the hash will be freed where created */
1689 sz += vertex->mod->modnamesz - 1;
1691 buf = malloc(sz + n * strlen(sep) + 1);
1694 for (i = reverse.count - 1; i >= 0; i--) {
1697 v = reverse.array[i];
1699 len = v->mod->modnamesz - 1;
1700 memcpy(buf + sz, v->mod->modname, len);
1702 strcpy(buf + sz, sep);
1705 depmod_list_remove_data(roots, v->mod);
1707 strcpy(buf + sz, vertex->mod->modname);
1708 ERR("Cycle detected: %s\n", buf);
1711 array_free_array(&reverse);
1716 static int depmod_report_cycles_from_root(struct depmod *depmod,
1717 struct mod *root_mod,
1718 struct kmod_list **roots,
1721 struct hash *loop_set)
1723 struct kmod_list *free_list = NULL; /* struct vertex */
1724 struct kmod_list *l;
1725 struct vertex *root;
1726 struct vertex *vertex;
1729 struct mod **itr, **itr_end;
1733 root = vertex_new(root_mod, NULL);
1735 ERR("No memory to report cycles\n");
1739 l = kmod_list_append(free_list, root);
1741 ERR("No memory to report cycles\n");
1747 stack[is++] = (void *)root;
1750 vertex = stack[--is];
1753 * because of the topological sort we can start only
1754 * from part of a loop or from a branch after a loop
1756 if (m->visited && m == root->mod) {
1758 rc = depmod_report_one_cycle(depmod, vertex,
1768 if (m->deps.count == 0) {
1770 * boundary condition: if there is more than one
1771 * single node branch (not a loop), it is
1772 * recognized as a loop by the code above:
1773 * m->visited because more then one,
1774 * m == root->mod since it is a single node.
1775 * So, prevent deeping into the branch second
1778 depmod_list_remove_data(roots, m);
1783 itr = (struct mod **) m->deps.array;
1784 itr_end = itr + m->deps.count;
1785 for (; itr < itr_end; itr++) {
1786 struct mod *dep = *itr;
1787 v = vertex_new(dep, vertex);
1789 ERR("No memory to report cycles\n");
1792 assert(is < stack_size);
1795 l = kmod_list_append(free_list, v);
1797 ERR("No memory to report cycles\n");
1808 v = free_list->data;
1809 l = kmod_list_remove(free_list);
1817 static void depmod_report_cycles(struct depmod *depmod, uint16_t n_mods,
1821 struct kmod_list *roots = NULL; /* struct mod */
1822 struct kmod_list *l;
1823 size_t n_r; /* local n_roots */
1826 _cleanup_free_ void **stack = NULL;
1829 struct hash *loop_set;
1831 for (i = 0, n_r = 0; i < n_mods; i++) {
1834 m = depmod->modules.array[i];
1835 l = kmod_list_append(roots, m);
1837 ERR("No memory to report cycles\n");
1844 stack = malloc(n_r * sizeof(void *));
1845 if (stack == NULL) {
1846 ERR("No memory to report cycles\n");
1850 loop_set = hash_new(16, NULL);
1851 if (loop_set == NULL) {
1852 ERR("No memory to report cycles\n");
1856 while (roots != NULL) {
1858 l = kmod_list_remove(roots);
1860 err = depmod_report_cycles_from_root(depmod,
1863 stack, n_r, loop_set);
1868 num_cyclic = hash_get_count(loop_set);
1869 ERR("Found %d modules in dependency cycles!\n", num_cyclic);
1872 hash_free(loop_set);
1874 while (roots != NULL) {
1875 /* no need to free data, come from outside */
1876 roots = kmod_list_remove(roots);
1880 static int depmod_calculate_dependencies(struct depmod *depmod)
1882 const struct mod **itrm;
1883 uint16_t *users, *roots, *sorted;
1884 uint16_t i, n_roots = 0, n_sorted = 0, n_mods = depmod->modules.count;
1887 users = malloc(sizeof(uint16_t) * n_mods * 3);
1890 roots = users + n_mods;
1891 sorted = roots + n_mods;
1893 DBG("calculate dependencies and ordering (%hu modules)\n", n_mods);
1895 assert(depmod->modules.count < UINT16_MAX);
1897 /* populate modules users (how many modules uses it) */
1898 itrm = (const struct mod **)depmod->modules.array;
1899 for (i = 0; i < n_mods; i++, itrm++) {
1900 const struct mod *m = *itrm;
1901 users[i] = m->users;
1902 if (users[i] == 0) {
1908 /* topological sort (outputs modules without users first) */
1909 while (n_roots > 0) {
1910 const struct mod **itr_dst, **itr_dst_end;
1912 uint16_t src_idx = roots[--n_roots];
1914 src = depmod->modules.array[src_idx];
1915 src->dep_sort_idx = n_sorted;
1916 sorted[n_sorted] = src_idx;
1919 itr_dst = (const struct mod **)src->deps.array;
1920 itr_dst_end = itr_dst + src->deps.count;
1921 for (; itr_dst < itr_dst_end; itr_dst++) {
1922 const struct mod *dst = *itr_dst;
1923 uint16_t dst_idx = dst->idx;
1924 assert(users[dst_idx] > 0);
1926 if (users[dst_idx] == 0) {
1927 roots[n_roots] = dst_idx;
1933 if (n_sorted < n_mods) {
1934 depmod_report_cycles(depmod, n_mods, users);
1939 depmod_sort_dependencies(depmod);
1941 DBG("calculated dependencies and ordering (%hu modules)\n", n_mods);
1948 static int depmod_load(struct depmod *depmod)
1952 err = depmod_load_modules(depmod);
1956 err = depmod_load_dependencies(depmod);
1960 err = depmod_calculate_dependencies(depmod);
1967 static size_t mod_count_all_dependencies(const struct mod *mod)
1969 size_t i, count = 0;
1970 for (i = 0; i < mod->deps.count; i++) {
1971 const struct mod *d = mod->deps.array[i];
1972 count += 1 + mod_count_all_dependencies(d);
1977 static int mod_fill_all_unique_dependencies(const struct mod *mod, const struct mod **deps, size_t n_deps, size_t *last)
1981 for (i = 0; i < mod->deps.count; i++) {
1982 const struct mod *d = mod->deps.array[i];
1986 for (j = 0; j < *last; j++) {
1996 if (*last >= n_deps)
2000 err = mod_fill_all_unique_dependencies(d, deps, n_deps, last);
2007 static const struct mod **mod_get_all_sorted_dependencies(const struct mod *mod, size_t *n_deps)
2009 const struct mod **deps;
2012 *n_deps = mod_count_all_dependencies(mod);
2016 deps = malloc(sizeof(struct mod *) * (*n_deps));
2020 if (mod_fill_all_unique_dependencies(mod, deps, *n_deps, &last) < 0) {
2025 qsort(deps, last, sizeof(struct mod *), dep_cmp);
2030 static inline const char *mod_get_compressed_path(const struct mod *mod)
2032 if (mod->relpath != NULL)
2033 return mod->relpath;
2037 static int output_deps(struct depmod *depmod, FILE *out)
2041 for (i = 0; i < depmod->modules.count; i++) {
2042 const struct mod **deps, *mod = depmod->modules.array[i];
2043 const char *p = mod_get_compressed_path(mod);
2046 fprintf(out, "%s:", p);
2048 if (mod->deps.count == 0)
2051 deps = mod_get_all_sorted_dependencies(mod, &n_deps);
2053 ERR("could not get all sorted dependencies of %s\n", p);
2057 for (j = 0; j < n_deps; j++) {
2058 const struct mod *d = deps[j];
2059 fprintf(out, " %s", mod_get_compressed_path(d));
2069 static int output_deps_bin(struct depmod *depmod, FILE *out)
2071 struct index_node *idx;
2077 idx = index_create();
2081 for (i = 0; i < depmod->modules.count; i++) {
2082 const struct mod **deps, *mod = depmod->modules.array[i];
2083 const char *p = mod_get_compressed_path(mod);
2085 size_t j, n_deps, linepos, linelen, slen;
2088 deps = mod_get_all_sorted_dependencies(mod, &n_deps);
2089 if (deps == NULL && n_deps > 0) {
2090 ERR("could not get all sorted dependencies of %s\n", p);
2094 linelen = strlen(p) + 1;
2095 for (j = 0; j < n_deps; j++) {
2096 const struct mod *d = deps[j];
2097 linelen += 1 + strlen(mod_get_compressed_path(d));
2100 line = malloc(linelen + 1);
2103 ERR("modules.deps.bin: out of memory\n");
2109 memcpy(line + linepos, p, slen);
2111 line[linepos] = ':';
2114 for (j = 0; j < n_deps; j++) {
2115 const struct mod *d = deps[j];
2118 line[linepos] = ' ';
2121 dp = mod_get_compressed_path(d);
2123 memcpy(line + linepos, dp, slen);
2126 line[linepos] = '\0';
2128 duplicate = index_insert(idx, mod->modname, line, mod->idx);
2129 if (duplicate && depmod->cfg->warn_dups)
2130 WRN("duplicate module deps:\n%s\n", line);
2135 index_write(idx, out);
2141 static int output_aliases(struct depmod *depmod, FILE *out)
2145 fputs("# Aliases extracted from modules themselves.\n", out);
2147 for (i = 0; i < depmod->modules.count; i++) {
2148 const struct mod *mod = depmod->modules.array[i];
2149 struct kmod_list *l;
2151 kmod_list_foreach(l, mod->info_list) {
2152 const char *key = kmod_module_info_get_key(l);
2153 const char *value = kmod_module_info_get_value(l);
2155 if (!streq(key, "alias"))
2158 fprintf(out, "alias %s %s\n", value, mod->modname);
2165 static int output_aliases_bin(struct depmod *depmod, FILE *out)
2167 struct index_node *idx;
2173 idx = index_create();
2177 for (i = 0; i < depmod->modules.count; i++) {
2178 const struct mod *mod = depmod->modules.array[i];
2179 struct kmod_list *l;
2181 kmod_list_foreach(l, mod->info_list) {
2182 const char *key = kmod_module_info_get_key(l);
2183 const char *value = kmod_module_info_get_value(l);
2188 if (!streq(key, "alias"))
2191 if (alias_normalize(value, buf, NULL) < 0) {
2192 WRN("Unmatched bracket in %s\n", value);
2197 duplicate = index_insert(idx, alias, mod->modname,
2199 if (duplicate && depmod->cfg->warn_dups)
2200 WRN("duplicate module alias:\n%s %s\n",
2201 alias, mod->modname);
2205 index_write(idx, out);
2211 static int output_softdeps(struct depmod *depmod, FILE *out)
2215 fputs("# Soft dependencies extracted from modules themselves.\n", out);
2217 for (i = 0; i < depmod->modules.count; i++) {
2218 const struct mod *mod = depmod->modules.array[i];
2219 struct kmod_list *l;
2221 kmod_list_foreach(l, mod->info_list) {
2222 const char *key = kmod_module_info_get_key(l);
2223 const char *value = kmod_module_info_get_value(l);
2225 if (!streq(key, "softdep"))
2228 fprintf(out, "softdep %s %s\n", mod->modname, value);
2235 static int output_symbols(struct depmod *depmod, FILE *out)
2237 struct hash_iter iter;
2240 fputs("# Aliases for symbols, used by symbol_request().\n", out);
2242 hash_iter_init(depmod->symbols, &iter);
2244 while (hash_iter_next(&iter, NULL, &v)) {
2245 const struct symbol *sym = v;
2246 if (sym->owner == NULL)
2249 fprintf(out, "alias symbol:%s %s\n",
2250 sym->name, sym->owner->modname);
2256 static int output_symbols_bin(struct depmod *depmod, FILE *out)
2258 struct index_node *idx;
2260 _cleanup_(scratchbuf_release) struct scratchbuf salias =
2261 SCRATCHBUF_INITIALIZER(alias);
2262 size_t baselen = sizeof("symbol:") - 1;
2263 struct hash_iter iter;
2270 idx = index_create();
2274 memcpy(alias, "symbol:", baselen);
2276 hash_iter_init(depmod->symbols, &iter);
2278 while (hash_iter_next(&iter, NULL, &v)) {
2280 const struct symbol *sym = v;
2283 if (sym->owner == NULL)
2286 len = strlen(sym->name);
2288 if (scratchbuf_alloc(&salias, baselen + len + 1) < 0) {
2290 goto err_scratchbuf;
2292 memcpy(scratchbuf_str(&salias) + baselen, sym->name, len + 1);
2293 duplicate = index_insert(idx, alias, sym->owner->modname,
2296 if (duplicate && depmod->cfg->warn_dups)
2297 WRN("duplicate module syms:\n%s %s\n",
2298 alias, sym->owner->modname);
2301 index_write(idx, out);
2307 ERR("output symbols: %s\n", strerror(-ret));
2312 static int output_builtin_bin(struct depmod *depmod, FILE *out)
2315 struct index_node *idx;
2316 char line[PATH_MAX], modname[PATH_MAX];
2321 in = dfdopen(depmod->cfg->dirname, "modules.builtin", O_RDONLY, "r");
2325 idx = index_create();
2331 while (fgets(line, sizeof(line), in) != NULL) {
2332 if (!isalpha(line[0])) {
2333 ERR("Invalid modules.builtin line: %s\n", line);
2337 path_to_modname(line, modname, NULL);
2338 index_insert(idx, modname, "", 0);
2341 index_write(idx, out);
2348 static int output_devname(struct depmod *depmod, FILE *out)
2353 for (i = 0; i < depmod->modules.count; i++) {
2354 const struct mod *mod = depmod->modules.array[i];
2355 struct kmod_list *l;
2356 const char *devname = NULL;
2358 unsigned int major = 0, minor = 0;
2360 kmod_list_foreach(l, mod->info_list) {
2361 const char *key = kmod_module_info_get_key(l);
2362 const char *value = kmod_module_info_get_value(l);
2363 unsigned int maj, min;
2365 if (!streq(key, "alias"))
2368 if (strstartswith(value, "devname:"))
2369 devname = value + sizeof("devname:") - 1;
2370 else if (sscanf(value, "char-major-%u-%u",
2375 } else if (sscanf(value, "block-major-%u-%u",
2382 if (type != '\0' && devname != NULL)
2386 if (devname != NULL) {
2389 fputs("# Device nodes to trigger on-demand module loading.\n",
2393 fprintf(out, "%s %s %c%u:%u\n", mod->modname,
2394 devname, type, major, minor);
2396 ERR("Module '%s' has devname (%s) but "
2397 "lacks major and minor information. "
2398 "Ignoring.\n", mod->modname, devname);
2405 static int output_builtin_alias_bin(struct depmod *depmod, FILE *out)
2407 int ret = 0, count = 0;
2408 struct index_node *idx;
2409 struct kmod_list *l, *builtin = NULL;
2411 idx = index_create();
2418 ret = kmod_module_get_builtin(depmod->ctx, &builtin);
2425 kmod_list_foreach(l, builtin) {
2426 struct kmod_list *ll, *info_list = NULL;
2427 struct kmod_module *mod = l->data;
2428 const char *modname = kmod_module_get_name(mod);
2430 ret = kmod_module_get_info(mod, &info_list);
2434 kmod_list_foreach(ll, info_list) {
2435 char alias[PATH_MAX];
2436 const char *key = kmod_module_info_get_key(ll);
2437 const char *value = kmod_module_info_get_value(ll);
2439 if (!streq(key, "alias"))
2443 if (alias_normalize(value, alias, NULL) < 0) {
2444 WRN("Unmatched bracket in %s\n", value);
2448 index_insert(idx, alias, modname, 0);
2451 kmod_module_info_free_list(info_list);
2453 index_insert(idx, modname, modname, 0);
2458 index_write(idx, out);
2462 kmod_module_unref_list(builtin);
2467 static int depmod_output(struct depmod *depmod, FILE *out)
2469 static const struct depfile {
2471 int (*cb)(struct depmod *depmod, FILE *out);
2472 } *itr, depfiles[] = {
2473 { "modules.dep", output_deps },
2474 { "modules.dep.bin", output_deps_bin },
2475 { "modules.alias", output_aliases },
2476 { "modules.alias.bin", output_aliases_bin },
2477 { "modules.softdep", output_softdeps },
2478 { "modules.symbols", output_symbols },
2479 { "modules.symbols.bin", output_symbols_bin },
2480 { "modules.builtin.bin", output_builtin_bin },
2481 { "modules.builtin.alias.bin", output_builtin_alias_bin },
2482 { "modules.devname", output_devname },
2485 const char *dname = depmod->cfg->dirname;
2489 gettimeofday(&tv, NULL);
2494 dfd = open(dname, O_RDONLY);
2497 CRIT("could not open directory %s: %m\n", dname);
2502 for (itr = depfiles; itr->name != NULL; itr++) {
2504 char tmp[NAME_MAX] = "";
2508 int flags = O_CREAT | O_EXCL | O_WRONLY;
2512 snprintf(tmp, sizeof(tmp), "%s.%i.%li.%li", itr->name, getpid(),
2513 tv.tv_usec, tv.tv_sec);
2514 fd = openat(dfd, tmp, flags, mode);
2516 ERR("openat(%s, %s, %o, %o): %m\n",
2517 dname, tmp, flags, mode);
2520 fp = fdopen(fd, "wb");
2522 ERR("fdopen(%d=%s/%s): %m\n", fd, dname, tmp);
2528 r = itr->cb(depmod, fp);
2532 ferr = ferror(fp) | fclose(fp);
2535 if (unlinkat(dfd, tmp, 0) != 0)
2536 ERR("unlinkat(%s, %s): %m\n", dname, tmp);
2538 ERR("Could not write index '%s': %s\n", itr->name,
2544 if (renameat(dfd, tmp, dfd, itr->name) != 0) {
2546 CRIT("renameat(%s, %s, %s, %s): %m\n",
2547 dname, tmp, dname, itr->name);
2553 ERR("Could not create index '%s'. Output is truncated: %s\n",
2554 itr->name, strerror(-err));
2565 static void depmod_add_fake_syms(struct depmod *depmod)
2567 /* __this_module is magic inserted by kernel loader. */
2568 depmod_symbol_add(depmod, "__this_module", true, 0, NULL);
2569 /* On S390, this is faked up too */
2570 depmod_symbol_add(depmod, "_GLOBAL_OFFSET_TABLE_", true, 0, NULL);
2571 /* On PowerPC64 ABIv2, .TOC. is more or less _GLOBAL_OFFSET_TABLE_ */
2572 if (!depmod_symbol_find(depmod, "TOC."))
2573 depmod_symbol_add(depmod, "TOC.", true, 0, NULL);
2576 static int depmod_load_symvers(struct depmod *depmod, const char *filename)
2580 unsigned int linenum = 0;
2582 fp = fopen(filename, "r");
2585 DBG("load symvers: %s: %m\n", filename);
2588 DBG("load symvers: %s\n", filename);
2590 /* eg. "0xb352177e\tfind_first_bit\tvmlinux\tEXPORT_SYMBOL" */
2591 while (fgets(line, sizeof(line), fp) != NULL) {
2592 const char *ver, *sym, *where;
2598 ver = strtok(line, " \t");
2599 sym = strtok(NULL, " \t");
2600 where = strtok(NULL, " \t");
2601 if (!ver || !sym || !where)
2604 if (!streq(where, "vmlinux"))
2607 crc = strtoull(ver, &verend, 16);
2608 if (verend[0] != '\0') {
2609 ERR("%s:%u Invalid symbol version %s: %m\n",
2610 filename, linenum, ver);
2614 depmod_symbol_add(depmod, sym, false, crc, NULL);
2616 depmod_add_fake_syms(depmod);
2618 DBG("loaded symvers: %s\n", filename);
2624 static int depmod_load_system_map(struct depmod *depmod, const char *filename)
2626 const char ksymstr[] = "__ksymtab_";
2627 const size_t ksymstr_len = sizeof(ksymstr) - 1;
2630 unsigned int linenum = 0;
2632 fp = fopen(filename, "r");
2635 DBG("load System.map: %s: %m\n", filename);
2638 DBG("load System.map: %s\n", filename);
2640 /* eg. c0294200 R __ksymtab_devfs_alloc_devnum */
2641 while (fgets(line, sizeof(line), fp) != NULL) {
2646 p = strchr(line, ' ');
2648 goto invalid_syntax;
2652 goto invalid_syntax;
2656 if (p[0] == depmod->cfg->sym_prefix)
2659 /* Covers gpl-only and normal symbols. */
2660 if (strncmp(p, ksymstr, ksymstr_len) != 0)
2663 end = strchr(p, '\n');
2667 depmod_symbol_add(depmod, p + ksymstr_len, true, 0, NULL);
2671 ERR("%s:%u: invalid line: %s\n", filename, linenum, line);
2673 depmod_add_fake_syms(depmod);
2675 DBG("loaded System.map: %s\n", filename);
2682 static int depfile_up_to_date_dir(DIR *d, time_t mtime, size_t baselen, char *path)
2685 int err = 1, dfd = dirfd(d);
2687 while ((de = readdir(d)) != NULL) {
2688 const char *name = de->d_name;
2692 if (name[0] == '.' && (name[1] == '\0' ||
2693 (name[1] == '.' && name[2] == '\0')))
2695 if (streq(name, "build") || streq(name, "source"))
2697 namelen = strlen(name);
2698 if (baselen + namelen + 2 >= PATH_MAX) {
2699 path[baselen] = '\0';
2700 ERR("path is too long %s%s\n", path, name);
2704 if (fstatat(dfd, name, &st, 0) < 0) {
2705 ERR("fstatat(%d, %s): %m\n", dfd, name);
2709 if (S_ISDIR(st.st_mode)) {
2712 memcpy(path + baselen, name, namelen + 1);
2713 if (baselen + namelen + 2 + NAME_MAX >= PATH_MAX) {
2714 ERR("directory path is too long %s\n", path);
2717 fd = openat(dfd, name, O_RDONLY);
2719 ERR("openat(%d, %s, O_RDONLY): %m\n",
2723 subdir = fdopendir(fd);
2724 if (subdir == NULL) {
2725 ERR("fdopendir(%d): %m\n", fd);
2729 path[baselen + namelen] = '/';
2730 path[baselen + namelen + 1] = '\0';
2731 err = depfile_up_to_date_dir(subdir, mtime,
2732 baselen + namelen + 1,
2735 } else if (S_ISREG(st.st_mode)) {
2736 if (!path_ends_with_kmod_ext(name, namelen))
2739 memcpy(path + baselen, name, namelen + 1);
2740 err = st.st_mtime <= mtime;
2742 DBG("%s %"PRIu64" is newer than %"PRIu64"\n",
2743 path, (uint64_t)st.st_mtime,
2747 ERR("unsupported file type %s: %o\n",
2748 path, st.st_mode & S_IFMT);
2753 break; /* outdated! */
2755 path[baselen + namelen] = '\0';
2756 ERR("failed %s: %s\n", path, strerror(-err));
2757 err = 1; /* ignore errors */
2764 /* uptodate: 1, outdated: 0, errors < 0 */
2765 static int depfile_up_to_date(const char *dirname)
2767 char path[PATH_MAX];
2768 DIR *d = opendir(dirname);
2774 ERR("could not open directory %s: %m\n", dirname);
2778 if (fstatat(dirfd(d), "modules.dep", &st, 0) != 0) {
2780 ERR("could not fstatat(%s, modules.dep): %m\n", dirname);
2785 baselen = strlen(dirname);
2786 memcpy(path, dirname, baselen);
2787 path[baselen] = '/';
2789 path[baselen] = '\0';
2791 err = depfile_up_to_date_dir(d, st.st_mtime, baselen, path);
2796 static int is_version_number(const char *version)
2798 unsigned int d1, d2;
2799 return (sscanf(version, "%u.%u", &d1, &d2) == 2);
2802 static int do_depmod(int argc, char *argv[])
2805 int err = 0, all = 0, maybe_all = 0, n_config_paths = 0;
2806 _cleanup_free_ char *root = NULL;
2807 _cleanup_free_ const char **config_paths = NULL;
2808 const char *system_map = NULL;
2809 const char *module_symvers = NULL;
2810 const char *null_kmod_config = NULL;
2812 struct kmod_ctx *ctx = NULL;
2814 struct depmod depmod;
2816 memset(&cfg, 0, sizeof(cfg));
2817 memset(&depmod, 0, sizeof(depmod));
2821 c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx);
2834 root = path_make_absolute_cwd(optarg);
2837 size_t bytes = sizeof(char *) * (n_config_paths + 2);
2838 void *tmp = realloc(config_paths, bytes);
2840 fputs("Error: out-of-memory\n", stderr);
2841 goto cmdline_failed;
2844 config_paths[n_config_paths] = optarg;
2846 config_paths[n_config_paths] = NULL;
2850 module_symvers = optarg;
2851 cfg.check_symvers = 1;
2854 system_map = optarg;
2857 cfg.print_unknown = 1;
2866 if (optarg[1] != '\0') {
2867 CRIT("-P only takes a single char\n");
2868 goto cmdline_failed;
2870 cfg.sym_prefix = optarg[0];
2880 WRN("Ignored deprecated option --%s\n",
2883 WRN("Ignored deprecated option -%c\n", c);
2888 return EXIT_SUCCESS;
2890 puts(PACKAGE " version " VERSION);
2891 puts(KMOD_FEATURES);
2892 return EXIT_SUCCESS;
2894 goto cmdline_failed;
2896 ERR("unexpected getopt_long() value '%c'.\n", c);
2897 goto cmdline_failed;
2901 if (optind < argc) {
2902 if (!is_version_number(argv[optind])) {
2903 ERR("Bad version passed %s\n", argv[optind]);
2904 goto cmdline_failed;
2906 cfg.kversion = argv[optind];
2909 if (uname(&un) < 0) {
2910 CRIT("uname() failed: %s\n", strerror(errno));
2911 goto cmdline_failed;
2913 cfg.kversion = un.release;
2916 cfg.dirnamelen = snprintf(cfg.dirname, PATH_MAX,
2917 "%s/lib/modules/%s",
2918 root == NULL ? "" : root, cfg.kversion);
2926 /* ignore up-to-date errors (< 0) */
2927 if (depfile_up_to_date(cfg.dirname) == 1)
2932 ctx = kmod_new(cfg.dirname, &null_kmod_config);
2934 CRIT("kmod_new(\"%s\", {NULL}) failed: %m\n", cfg.dirname);
2935 goto cmdline_failed;
2938 log_setup_kmod_log(ctx, verbose);
2940 err = depmod_init(&depmod, &cfg, ctx);
2942 CRIT("depmod_init: %s\n", strerror(-err));
2943 goto depmod_init_failed;
2945 ctx = NULL; /* owned by depmod */
2947 if (module_symvers != NULL) {
2948 err = depmod_load_symvers(&depmod, module_symvers);
2950 CRIT("could not load %s: %s\n", module_symvers,
2952 goto cmdline_failed;
2954 } else if (system_map != NULL) {
2955 err = depmod_load_system_map(&depmod, system_map);
2957 CRIT("could not load %s: %s\n", system_map,
2959 goto cmdline_failed;
2961 } else if (cfg.print_unknown) {
2962 WRN("-e needs -E or -F\n");
2963 cfg.print_unknown = 0;
2967 err = cfg_load(&cfg, config_paths);
2969 CRIT("could not load configuration files\n");
2970 goto cmdline_modules_failed;
2972 err = depmod_modules_search(&depmod);
2974 CRIT("could not search modules: %s\n", strerror(-err));
2975 goto cmdline_modules_failed;
2980 for (i = optind; i < argc; i++) {
2981 const char *path = argv[i];
2982 struct kmod_module *mod;
2984 if (path[0] != '/') {
2985 CRIT("%s: not absolute path.\n", path);
2986 goto cmdline_modules_failed;
2989 err = kmod_module_new_from_path(depmod.ctx, path, &mod);
2991 CRIT("could not create module %s: %s\n",
2992 path, strerror(-err));
2993 goto cmdline_modules_failed;
2996 err = depmod_module_add(&depmod, mod);
2998 CRIT("could not add module %s: %s\n",
2999 path, strerror(-err));
3000 kmod_module_unref(mod);
3001 goto cmdline_modules_failed;
3006 err = depmod_modules_build_array(&depmod);
3008 CRIT("could not build module array: %s\n",
3010 goto cmdline_modules_failed;
3013 depmod_modules_sort(&depmod);
3014 err = depmod_load(&depmod);
3016 goto cmdline_modules_failed;
3018 err = depmod_output(&depmod, out);
3021 depmod_shutdown(&depmod);
3023 return err >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
3025 cmdline_modules_failed:
3026 depmod_shutdown(&depmod);
3032 return EXIT_FAILURE;
3035 const struct kmod_cmd kmod_cmd_compat_depmod = {
3038 .help = "compat depmod command",