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[] = {
54 SYSCONFDIR "/depmod.d",
56 "/usr/local/lib/depmod.d",
61 static const char cmdopts_s[] = "aAb:C:E:F:euqrvnP:wmVh";
62 static const struct option cmdopts[] = {
63 { "all", no_argument, 0, 'a' },
64 { "quick", no_argument, 0, 'A' },
65 { "basedir", required_argument, 0, 'b' },
66 { "config", required_argument, 0, 'C' },
67 { "symvers", required_argument, 0, 'E' },
68 { "filesyms", required_argument, 0, 'F' },
69 { "errsyms", no_argument, 0, 'e' },
70 { "unresolved-error", no_argument, 0, 'u' }, /* deprecated */
71 { "quiet", no_argument, 0, 'q' }, /* deprecated */
72 { "root", no_argument, 0, 'r' }, /* deprecated */
73 { "verbose", no_argument, 0, 'v' },
74 { "show", no_argument, 0, 'n' },
75 { "dry-run", no_argument, 0, 'n' },
76 { "symbol-prefix", required_argument, 0, 'P' },
77 { "warn", no_argument, 0, 'w' },
78 { "map", no_argument, 0, 'm' }, /* deprecated */
79 { "version", no_argument, 0, 'V' },
80 { "help", no_argument, 0, 'h' },
84 static void help(void)
87 "\t%s -[aA] [options] [forced_version]\n"
89 "If no arguments (except options) are given, \"depmod -a\" is assumed\n"
91 "depmod will output a dependency list suitable for the modprobe utility.\n"
94 "\t-a, --all Probe all modules\n"
95 "\t-A, --quick Only does the work if there's a new module\n"
96 "\t-e, --errsyms Report not supplied symbols\n"
97 "\t-n, --show Write the dependency file on stdout only\n"
98 "\t-P, --symbol-prefix Architecture symbol prefix\n"
99 "\t-C, --config=PATH Read configuration from PATH\n"
100 "\t-v, --verbose Enable verbose mode\n"
101 "\t-w, --warn Warn on duplicates\n"
102 "\t-V, --version show version\n"
103 "\t-h, --help show this help\n"
105 "The following options are useful for people managing distributions:\n"
106 "\t-b, --basedir=DIR Use an image of a module tree.\n"
107 "\t-F, --filesyms=FILE Use the file instead of the\n"
108 "\t current kernel symbols.\n"
109 "\t-E, --symvers=FILE Use Module.symvers file to check\n"
110 "\t symbol versions.\n",
111 program_invocation_short_name);
114 _printf_format_(1, 2)
115 static inline void _show(const char *fmt, ...)
119 if (verbose <= DEFAULT_VERBOSE)
123 vfprintf(stdout, fmt, args);
127 #define SHOW(...) _show(__VA_ARGS__)
130 /* binary index write *************************************************/
131 #include <arpa/inet.h>
132 /* BEGIN: code from module-init-tools/index.c just modified to compile here.
134 * Original copyright:
135 * index.c: module index file shared functions for modprobe and depmod
136 * Copyright (C) 2008 Alan Jenkins <alan-jenkins@tuffmail.co.uk>.
138 * These programs are free software; you can redistribute it and/or modify
139 * it under the terms of the GNU General Public License as published by
140 * the Free Software Foundation; either version 2 of the License, or
141 * (at your option) any later version.
143 * This program is distributed in the hope that it will be useful,
144 * but WITHOUT ANY WARRANTY; without even the implied warranty of
145 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
146 * GNU General Public License for more details.
148 * You should have received a copy of the GNU General Public License
149 * along with these programs. If not, see <http://www.gnu.org/licenses/>.
152 /* see documentation in libkmod/libkmod-index.c */
154 #define INDEX_MAGIC 0xB007F457
155 #define INDEX_VERSION_MAJOR 0x0002
156 #define INDEX_VERSION_MINOR 0x0001
157 #define INDEX_VERSION ((INDEX_VERSION_MAJOR<<16)|INDEX_VERSION_MINOR)
158 #define INDEX_CHILDMAX 128
161 struct index_value *next;
162 unsigned int priority;
166 /* In-memory index (depmod only) */
168 char *prefix; /* path compression */
169 struct index_value *values;
170 unsigned char first; /* range of child nodes */
172 struct index_node *children[INDEX_CHILDMAX]; /* indexed by character */
176 /* Format of node offsets within index file */
178 INDEX_NODE_FLAGS = 0xF0000000, /* Flags in high nibble */
179 INDEX_NODE_PREFIX = 0x80000000,
180 INDEX_NODE_VALUES = 0x40000000,
181 INDEX_NODE_CHILDS = 0x20000000,
183 INDEX_NODE_MASK = 0x0FFFFFFF, /* Offset value */
186 static struct index_node *index_create(void)
188 struct index_node *node;
190 node = NOFAIL(calloc(sizeof(struct index_node), 1));
191 node->prefix = NOFAIL(strdup(""));
192 node->first = INDEX_CHILDMAX;
197 static void index_values_free(struct index_value *values)
200 struct index_value *value = values;
202 values = value->next;
207 static void index_destroy(struct index_node *node)
211 for (c = node->first; c <= node->last; c++) {
212 struct index_node *child = node->children[c];
215 index_destroy(child);
217 index_values_free(node->values);
222 static void index__checkstring(const char *str)
226 for (i = 0; str[i]; i++) {
229 if (ch >= INDEX_CHILDMAX)
230 CRIT("Module index: bad character '%c'=0x%x - only 7-bit ASCII is supported:"
231 "\n%s\n", (char) ch, (int) ch, str);
235 static int index_add_value(struct index_value **values,
236 const char *value, unsigned int priority)
238 struct index_value *v;
242 /* report the presence of duplicate values */
243 for (v = *values; v; v = v->next) {
244 if (streq(v->value, value))
248 /* find position to insert value */
249 while (*values && (*values)->priority < priority)
250 values = &(*values)->next;
253 v = NOFAIL(calloc(sizeof(struct index_value) + len + 1, 1));
255 v->priority = priority;
256 memcpy(v->value, value, len + 1);
262 static int index_insert(struct index_node *node, const char *key,
263 const char *value, unsigned int priority)
265 int i = 0; /* index within str */
268 index__checkstring(key);
269 index__checkstring(value);
272 int j; /* index within node->prefix */
274 /* Ensure node->prefix is a prefix of &str[i].
275 If it is not already, then we must split node. */
276 for (j = 0; node->prefix[j]; j++) {
277 ch = node->prefix[j];
279 if (ch != key[i+j]) {
280 char *prefix = node->prefix;
281 struct index_node *n;
283 /* New child is copy of node with prefix[j+1..N] */
284 n = NOFAIL(calloc(sizeof(struct index_node), 1));
285 memcpy(n, node, sizeof(struct index_node));
286 n->prefix = NOFAIL(strdup(&prefix[j+1]));
288 /* Parent has prefix[0..j], child at prefix[j] */
289 memset(node, 0, sizeof(struct index_node));
291 node->prefix = prefix;
294 node->children[ch] = n;
299 /* j is now length of node->prefix */
304 return index_add_value(&node->values, value, priority);
306 if (!node->children[ch]) {
307 struct index_node *child;
309 if (ch < node->first)
313 node->children[ch] = NOFAIL(calloc(sizeof(struct index_node), 1));
315 child = node->children[ch];
316 child->prefix = NOFAIL(strdup(&key[i+1]));
317 child->first = INDEX_CHILDMAX;
318 index_add_value(&child->values, value, priority);
323 /* Descend into child node and continue */
324 node = node->children[ch];
329 static int index__haschildren(const struct index_node *node)
331 return node->first < INDEX_CHILDMAX;
334 /* Recursive post-order traversal
336 Pre-order would make for better read-side buffering / readahead / caching.
337 (post-order means you go backwards in the file as you descend the tree).
338 However, index reading is already fast enough.
339 Pre-order is simpler for writing, and depmod is already slow.
341 static uint32_t index_write__node(const struct index_node *node, FILE *out)
343 uint32_t *child_offs = NULL;
350 /* Write children and save their offsets */
351 if (index__haschildren(node)) {
352 const struct index_node *child;
355 child_count = node->last - node->first + 1;
356 child_offs = NOFAIL(malloc(child_count * sizeof(uint32_t)));
358 for (i = 0; i < child_count; i++) {
359 child = node->children[node->first + i];
360 child_offs[i] = htonl(index_write__node(child, out));
364 /* Now write this node */
367 if (node->prefix[0]) {
368 fputs(node->prefix, out);
370 offset |= INDEX_NODE_PREFIX;
374 fputc(node->first, out);
375 fputc(node->last, out);
376 fwrite(child_offs, sizeof(uint32_t), child_count, out);
377 offset |= INDEX_NODE_CHILDS;
383 const struct index_value *v;
384 unsigned int value_count;
388 for (v = node->values; v != NULL; v = v->next)
390 u = htonl(value_count);
391 fwrite(&u, sizeof(u), 1, out);
393 for (v = node->values; v != NULL; v = v->next) {
394 u = htonl(v->priority);
395 fwrite(&u, sizeof(u), 1, out);
396 fputs(v->value, out);
399 offset |= INDEX_NODE_VALUES;
405 static void index_write(const struct index_node *node, FILE *out)
407 long initial_offset, final_offset;
410 u = htonl(INDEX_MAGIC);
411 fwrite(&u, sizeof(u), 1, out);
412 u = htonl(INDEX_VERSION);
413 fwrite(&u, sizeof(u), 1, out);
415 /* Second word is reserved for the offset of the root node */
416 initial_offset = ftell(out);
417 assert(initial_offset >= 0);
419 fwrite(&u, sizeof(uint32_t), 1, out);
422 u = htonl(index_write__node(node, out));
424 /* Update first word */
425 final_offset = ftell(out);
426 assert(final_offset >= 0);
427 (void)fseek(out, initial_offset, SEEK_SET);
428 fwrite(&u, sizeof(uint32_t), 1, out);
429 (void)fseek(out, final_offset, SEEK_SET);
432 /* END: code from module-init-tools/index.c just modified to compile here.
435 /* configuration parsing **********************************************/
436 struct cfg_override {
437 struct cfg_override *next;
449 struct cfg_search *next;
450 enum search_type type;
455 struct cfg_external {
456 struct cfg_external *next;
462 const char *kversion;
463 char dirname[PATH_MAX];
466 uint8_t check_symvers;
467 uint8_t print_unknown;
469 struct cfg_override *overrides;
470 struct cfg_search *searches;
471 struct cfg_external *externals;
474 static enum search_type cfg_define_search_type(const char *path)
476 if (streq(path, CFG_BUILTIN_KEY))
477 return SEARCH_BUILTIN;
478 if (streq(path, CFG_EXTERNAL_KEY))
479 return SEARCH_EXTERNAL;
483 static int cfg_search_add(struct cfg *cfg, const char *path)
485 struct cfg_search *s;
487 enum search_type type;
489 type = cfg_define_search_type(path);
491 if (type != SEARCH_PATH)
494 len = strlen(path) + 1;
496 s = malloc(sizeof(struct cfg_search) + len);
498 ERR("search add: out of memory\n");
502 if (type != SEARCH_PATH)
506 memcpy(s->path, path, len);
509 DBG("search add: %s, search type=%hhu\n", path, type);
511 s->next = cfg->searches;
516 static void cfg_search_free(struct cfg_search *s)
521 static int cfg_override_add(struct cfg *cfg, const char *modname, const char *subdir)
523 struct cfg_override *o;
524 size_t modnamelen = strlen(modname);
525 size_t subdirlen = strlen(subdir);
528 o = malloc(sizeof(struct cfg_override) + subdirlen + 1
531 ERR("override add: out of memory\n");
534 memcpy(o->path, subdir, subdirlen);
539 memcpy(o->path + i, modname, modnamelen);
541 o->path[i] = '\0'; /* no extension, so we can match .ko/.ko.gz */
545 DBG("override add: %s\n", o->path);
547 o->next = cfg->overrides;
552 static void cfg_override_free(struct cfg_override *o)
557 static int cfg_external_add(struct cfg *cfg, const char *path)
559 struct cfg_external *ext;
560 size_t len = strlen(path);
562 ext = malloc(sizeof(struct cfg_external) + len + 1);
564 ERR("external add: out of memory\n");
568 strcpy(ext->path, path);
571 DBG("external add: %s\n", ext->path);
573 ext->next = cfg->externals;
574 cfg->externals = ext;
578 static void cfg_external_free(struct cfg_external *ext)
583 static int cfg_kernel_matches(const struct cfg *cfg, const char *pattern)
589 if (streq(pattern, "*"))
592 if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
595 status = regexec(&re, cfg->kversion, 0, NULL, 0);
601 static int cfg_file_parse(struct cfg *cfg, const char *filename)
605 unsigned int linenum = 0;
608 fp = fopen(filename, "r");
611 ERR("file parse %s: %m\n", filename);
615 while ((line = freadline_wrapped(fp, &linenum)) != NULL) {
618 if (line[0] == '\0' || line[0] == '#')
621 cmd = strtok_r(line, "\t ", &saveptr);
625 if (streq(cmd, "search")) {
627 while ((sp = strtok_r(NULL, "\t ", &saveptr)) != NULL) {
628 cfg_search_add(cfg, sp);
630 } else if (streq(cmd, "override")) {
631 const char *modname = strtok_r(NULL, "\t ", &saveptr);
632 const char *version = strtok_r(NULL, "\t ", &saveptr);
633 const char *subdir = strtok_r(NULL, "\t ", &saveptr);
635 if (modname == NULL || version == NULL ||
639 if (!cfg_kernel_matches(cfg, version)) {
640 INF("%s:%u: override kernel did not match %s\n",
641 filename, linenum, version);
645 cfg_override_add(cfg, modname, subdir);
646 } else if (streq(cmd, "external")) {
647 const char *version = strtok_r(NULL, "\t ", &saveptr);
648 const char *dir = strtok_r(NULL, "\t ", &saveptr);
650 if (version == NULL || dir == NULL)
653 if (!cfg_kernel_matches(cfg, version)) {
654 INF("%s:%u: external directory did not match %s\n",
655 filename, linenum, version);
659 cfg_external_add(cfg, dir);
660 } else if (streq(cmd, "include")
661 || streq(cmd, "make_map_files")) {
662 INF("%s:%u: command %s not implemented yet\n",
663 filename, linenum, cmd);
666 ERR("%s:%u: ignoring bad line starting with '%s'\n",
667 filename, linenum, cmd);
679 static int cfg_files_filter_out(DIR *d, const char *dir, const char *name)
681 size_t len = strlen(name);
687 if (len < 6 || !streq(name + len - 5, ".conf")) {
688 INF("All cfg files need .conf: %s/%s\n", dir, name);
692 fstatat(dirfd(d), name, &st, 0);
693 if (S_ISDIR(st.st_mode)) {
694 ERR("Directories inside directories are not supported: %s/%s\n",
709 static void cfg_file_free(struct cfg_file *f)
714 static int cfg_files_insert_sorted(struct cfg_file ***p_files, size_t *p_n_files,
715 const char *dir, const char *name)
717 struct cfg_file **files, *f;
718 size_t i, n_files, namelen, dirlen;
721 dirlen = strlen(dir);
723 namelen = strlen(name);
725 name = basename(dir);
726 namelen = strlen(name);
727 dirlen -= namelen + 1;
730 n_files = *p_n_files;
732 for (i = 0; i < n_files; i++) {
733 int cmp = strcmp(name, files[i]->name);
735 DBG("Ignoring duplicate config file: %.*s/%s\n",
736 (int)dirlen, dir, name);
742 f = malloc(sizeof(struct cfg_file) + dirlen + namelen + 2);
744 ERR("files insert sorted: out of memory\n");
748 tmp = realloc(files, sizeof(struct cfg_file *) * (n_files + 1));
750 ERR("files insert sorted: out of memory\n");
754 *p_files = files = tmp;
757 memmove(files + i + 1, files + i,
758 sizeof(struct cfg_file *) * (n_files - i));
763 f->namelen = namelen;
764 f->name = f->path + dirlen + 1;
765 memcpy(f->path, dir, dirlen);
766 f->path[dirlen] = '/';
767 memcpy(f->path + dirlen + 1, name, namelen);
768 f->path[dirlen + 1 + namelen] = '\0';
770 *p_n_files = n_files + 1;
775 * Insert configuration files ignoring duplicates
777 static int cfg_files_list(struct cfg_file ***p_files, size_t *p_n_files,
785 if (stat(path, &st) != 0) {
787 DBG("could not stat '%s': %m\n", path);
791 if (!S_ISDIR(st.st_mode)) {
792 cfg_files_insert_sorted(p_files, p_n_files, path, NULL);
798 ERR("files list %s: %m\n", path);
802 for (dent = readdir(d); dent != NULL; dent = readdir(d)) {
803 if (cfg_files_filter_out(d, path, dent->d_name))
806 cfg_files_insert_sorted(p_files, p_n_files, path, dent->d_name);
810 DBG("parsed configuration files from %s\n", path);
814 static int cfg_load(struct cfg *cfg, const char * const *cfg_paths)
816 size_t i, n_files = 0;
817 struct cfg_file **files = NULL;
819 if (cfg_paths == NULL)
820 cfg_paths = default_cfg_paths;
822 for (i = 0; cfg_paths[i] != NULL; i++)
823 cfg_files_list(&files, &n_files, cfg_paths[i]);
825 for (i = 0; i < n_files; i++) {
826 struct cfg_file *f = files[i];
827 cfg_file_parse(cfg, f->path);
832 /* For backward compatibility add "updates" to the head of the search
833 * list here. But only if there was no "search" option specified.
835 if (cfg->searches == NULL)
836 cfg_search_add(cfg, "updates");
841 static void cfg_free(struct cfg *cfg)
843 while (cfg->overrides) {
844 struct cfg_override *tmp = cfg->overrides;
845 cfg->overrides = cfg->overrides->next;
846 cfg_override_free(tmp);
849 while (cfg->searches) {
850 struct cfg_search *tmp = cfg->searches;
851 cfg->searches = cfg->searches->next;
852 cfg_search_free(tmp);
855 while (cfg->externals) {
856 struct cfg_external *tmp = cfg->externals;
857 cfg->externals = cfg->externals->next;
858 cfg_external_free(tmp);
863 /* depmod calculations ***********************************************/
866 struct kmod_module *kmod;
868 const char *relpath; /* path relative to '$ROOT/lib/modules/$VER/' */
869 char *uncrelpath; /* same as relpath but ending in .ko */
870 struct kmod_list *info_list;
871 struct kmod_list *dep_sym_list;
872 struct array deps; /* struct symbol */
873 size_t baselen; /* points to start of basename/filename */
875 int sort_idx; /* sort index using modules.order */
876 int dep_sort_idx; /* topological sort index */
877 uint16_t idx; /* index in depmod->modules.array */
878 uint16_t users; /* how many modules depend on this one */
879 bool visited; /* helper field to report cycles */
880 struct vertex *vertex; /* helper field to report cycles */
891 const struct cfg *cfg;
892 struct kmod_ctx *ctx;
893 struct array modules;
894 struct hash *modules_by_uncrelpath;
895 struct hash *modules_by_name;
896 struct hash *symbols;
899 static void mod_free(struct mod *mod)
901 DBG("free %p kmod=%p, path=%s\n", mod, mod->kmod, mod->path);
902 array_free_array(&mod->deps);
903 kmod_module_unref(mod->kmod);
904 kmod_module_info_free_list(mod->info_list);
905 kmod_module_dependency_symbols_free_list(mod->dep_sym_list);
906 free(mod->uncrelpath);
911 static int mod_add_dependency(struct mod *mod, struct symbol *sym)
915 DBG("%s depends on %s %s\n", mod->path, sym->name,
916 sym->owner != NULL ? sym->owner->path : "(unknown)");
918 if (sym->owner == NULL)
921 err = array_append_unique(&mod->deps, sym->owner);
928 SHOW("%s needs \"%s\": %s\n", mod->path, sym->name, sym->owner->path);
932 static void symbol_free(struct symbol *sym)
934 DBG("free %p sym=%s, owner=%p %s\n", sym, sym->name, sym->owner,
935 sym->owner != NULL ? sym->owner->path : "");
939 static int depmod_init(struct depmod *depmod, struct cfg *cfg,
940 struct kmod_ctx *ctx)
947 array_init(&depmod->modules, 128);
949 depmod->modules_by_uncrelpath = hash_new(512, NULL);
950 if (depmod->modules_by_uncrelpath == NULL) {
952 goto modules_by_uncrelpath_failed;
955 depmod->modules_by_name = hash_new(512, NULL);
956 if (depmod->modules_by_name == NULL) {
958 goto modules_by_name_failed;
961 depmod->symbols = hash_new(2048, (void (*)(void *))symbol_free);
962 if (depmod->symbols == NULL) {
970 hash_free(depmod->modules_by_name);
971 modules_by_name_failed:
972 hash_free(depmod->modules_by_uncrelpath);
973 modules_by_uncrelpath_failed:
977 static void depmod_shutdown(struct depmod *depmod)
981 hash_free(depmod->symbols);
983 hash_free(depmod->modules_by_uncrelpath);
985 hash_free(depmod->modules_by_name);
987 for (i = 0; i < depmod->modules.count; i++)
988 mod_free(depmod->modules.array[i]);
989 array_free_array(&depmod->modules);
991 kmod_unref(depmod->ctx);
994 static int depmod_module_add(struct depmod *depmod, struct kmod_module *kmod)
996 const struct cfg *cfg = depmod->cfg;
997 const char *modname, *lastslash;
1002 modname = kmod_module_get_name(kmod);
1003 modnamesz = strlen(modname) + 1;
1005 mod = calloc(1, sizeof(struct mod) + modnamesz);
1009 mod->sort_idx = depmod->modules.count + 1;
1010 mod->dep_sort_idx = INT32_MAX;
1011 memcpy(mod->modname, modname, modnamesz);
1012 mod->modnamesz = modnamesz;
1014 array_init(&mod->deps, 4);
1016 mod->path = strdup(kmod_module_get_path(kmod));
1017 lastslash = strrchr(mod->path, '/');
1018 mod->baselen = lastslash - mod->path;
1019 if (strncmp(mod->path, cfg->dirname, cfg->dirnamelen) == 0 &&
1020 mod->path[cfg->dirnamelen] == '/')
1021 mod->relpath = mod->path + cfg->dirnamelen + 1;
1023 mod->relpath = NULL;
1025 err = hash_add_unique(depmod->modules_by_name, mod->modname, mod);
1027 ERR("hash_add_unique %s: %s\n", mod->modname, strerror(-err));
1031 if (mod->relpath != NULL) {
1032 size_t uncrelpathlen = lastslash - mod->relpath + modnamesz
1033 + strlen(KMOD_EXTENSION_UNCOMPRESSED);
1034 mod->uncrelpath = memdup(mod->relpath, uncrelpathlen + 1);
1035 mod->uncrelpath[uncrelpathlen] = '\0';
1036 err = hash_add_unique(depmod->modules_by_uncrelpath,
1037 mod->uncrelpath, mod);
1039 ERR("hash_add_unique %s: %s\n",
1040 mod->uncrelpath, strerror(-err));
1041 hash_del(depmod->modules_by_name, mod->modname);
1046 DBG("add %p kmod=%p, path=%s\n", mod, kmod, mod->path);
1051 free(mod->uncrelpath);
1056 static int depmod_module_del(struct depmod *depmod, struct mod *mod)
1058 DBG("del %p kmod=%p, path=%s\n", mod, mod->kmod, mod->path);
1060 if (mod->uncrelpath != NULL)
1061 hash_del(depmod->modules_by_uncrelpath, mod->uncrelpath);
1063 hash_del(depmod->modules_by_name, mod->modname);
1069 static const char *search_to_string(const struct cfg_search *s)
1072 case SEARCH_EXTERNAL:
1074 case SEARCH_BUILTIN:
1081 static bool depmod_is_path_starts_with(const char *path,
1086 if (pathlen <= prefix_len)
1088 if (path[prefix_len] != '/')
1090 if (memcmp(path, prefix, prefix_len) != 0)
1096 /* returns if existing module @mod is higher priority than newpath.
1097 * note this is the inverse of module-init-tools is_higher_priority()
1099 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)
1101 const struct cfg *cfg = depmod->cfg;
1102 const struct cfg_override *ov;
1103 const struct cfg_search *se;
1104 const struct cfg_external *ext;
1106 /* baselen includes the last '/' and mod->baselen doesn't. So it's
1107 * actually correct to use modnamelen in the first and modnamesz in
1109 size_t newlen = baselen + modnamelen;
1110 size_t oldlen = mod->baselen + mod->modnamesz;
1111 const char *oldpath = mod->path;
1112 int i, bprio = -1, oldprio = -1, newprio = -1;
1113 size_t relnewlen = 0;
1114 size_t reloldlen = 0;
1115 const char *relnewpath = NULL;
1116 const char *reloldpath = NULL;
1118 DBG("comparing priorities of %s and %s\n",
1121 if (strncmp(newpath, cfg->dirname, cfg->dirnamelen) == 0) {
1122 relnewpath = newpath + cfg->dirnamelen + 1;
1123 relnewlen = newlen - (cfg->dirnamelen + 1);
1125 if (strncmp(oldpath, cfg->dirname, cfg->dirnamelen) == 0) {
1126 reloldpath = oldpath + cfg->dirnamelen + 1;
1127 reloldlen = oldlen - (cfg->dirnamelen + 1);
1130 for (ov = cfg->overrides; ov != NULL; ov = ov->next) {
1131 DBG("override %s\n", ov->path);
1132 if (relnewlen == ov->len &&
1133 memcmp(ov->path, relnewpath, relnewlen) == 0)
1135 if (reloldlen == ov->len &&
1136 memcmp(ov->path, reloldpath, reloldlen) == 0)
1140 for (i = 0, se = cfg->searches; se != NULL; se = se->next, i++) {
1141 DBG("search %s\n", search_to_string(se));
1142 if (se->type == SEARCH_BUILTIN)
1144 else if (se->type == SEARCH_EXTERNAL) {
1145 for (ext = cfg->externals; ext != NULL; ext = ext->next, i++) {
1146 if (depmod_is_path_starts_with(newpath,
1151 if (depmod_is_path_starts_with(oldpath,
1157 } else if (relnewlen > se->len && relnewpath[se->len] == '/' &&
1158 memcmp(se->path, relnewpath, se->len) == 0)
1160 else if (reloldlen > se->len && reloldpath[se->len] == '/' &&
1161 memcmp(se->path, reloldpath, se->len) == 0)
1170 DBG("priorities: built-in: %d, old: %d, new: %d\n",
1171 bprio, oldprio, newprio);
1173 return newprio <= oldprio;
1176 static int depmod_modules_search_file(struct depmod *depmod, size_t baselen, size_t namelen, const char *path)
1178 struct kmod_module *kmod;
1180 const char *relpath;
1181 char modname[PATH_MAX];
1185 if (!path_ends_with_kmod_ext(path + baselen, namelen))
1188 if (path_to_modname(path, modname, &modnamelen) == NULL) {
1189 ERR("could not get modname from path %s\n", path);
1193 relpath = path + depmod->cfg->dirnamelen + 1;
1194 DBG("try %s (%s)\n", relpath, modname);
1196 mod = hash_find(depmod->modules_by_name, modname);
1200 if (depmod_module_is_higher_priority(depmod, mod, baselen,
1201 namelen, modnamelen, path)) {
1202 DBG("Ignored lower priority: %s, higher: %s\n",
1207 DBG("Replace lower priority %s with new module %s\n",
1208 mod->relpath, relpath);
1209 err = depmod_module_del(depmod, mod);
1211 ERR("could not del module %s: %s\n", mod->path, strerror(-err));
1216 err = kmod_module_new_from_path(depmod->ctx, path, &kmod);
1218 ERR("could not create module %s: %s\n", path, strerror(-err));
1222 err = depmod_module_add(depmod, kmod);
1224 ERR("could not add module %s: %s\n",
1225 path, strerror(-err));
1226 kmod_module_unref(kmod);
1232 static int depmod_modules_search_dir(struct depmod *depmod, DIR *d, size_t baselen, struct scratchbuf *s_path)
1235 int err = 0, dfd = dirfd(d);
1238 while ((de = readdir(d)) != NULL) {
1239 const char *name = de->d_name;
1243 if (name[0] == '.' && (name[1] == '\0' ||
1244 (name[1] == '.' && name[2] == '\0')))
1246 if (streq(name, "build") || streq(name, "source"))
1248 namelen = strlen(name);
1249 if (scratchbuf_alloc(s_path, baselen + namelen + 2) < 0) {
1255 path = scratchbuf_str(s_path);
1256 memcpy(path + baselen, name, namelen + 1);
1258 if (de->d_type == DT_REG)
1260 else if (de->d_type == DT_DIR)
1264 if (fstatat(dfd, name, &st, 0) < 0) {
1265 ERR("fstatat(%d, %s): %m\n", dfd, name);
1267 } else if (S_ISREG(st.st_mode))
1269 else if (S_ISDIR(st.st_mode))
1272 ERR("unsupported file type %s: %o\n",
1273 path, st.st_mode & S_IFMT);
1281 fd = openat(dfd, name, O_RDONLY);
1283 ERR("openat(%d, %s, O_RDONLY): %m\n",
1287 subdir = fdopendir(fd);
1288 if (subdir == NULL) {
1289 ERR("fdopendir(%d): %m\n", fd);
1293 path[baselen + namelen] = '/';
1294 path[baselen + namelen + 1] = '\0';
1295 err = depmod_modules_search_dir(depmod, subdir,
1296 baselen + namelen + 1,
1300 err = depmod_modules_search_file(depmod, baselen,
1305 path[baselen + namelen] = '\0';
1306 ERR("failed %s: %s\n", path, strerror(-err));
1307 err = 0; /* ignore errors */
1313 static int depmod_modules_search_path(struct depmod *depmod,
1317 _cleanup_(scratchbuf_release) struct scratchbuf s_path_buf =
1318 SCRATCHBUF_INITIALIZER(buf);
1327 ERR("could not open directory %s: %m\n", path);
1331 baselen = strlen(path);
1333 if (scratchbuf_alloc(&s_path_buf, baselen + 2) < 0) {
1337 path_buf = scratchbuf_str(&s_path_buf);
1339 memcpy(path_buf, path, baselen);
1340 path_buf[baselen] = '/';
1342 path_buf[baselen] = '\0';
1344 err = depmod_modules_search_dir(depmod, d, baselen, &s_path_buf);
1350 static int depmod_modules_search(struct depmod *depmod)
1353 struct cfg_external *ext;
1355 err = depmod_modules_search_path(depmod, depmod->cfg->dirname);
1359 for (ext = depmod->cfg->externals; ext != NULL; ext = ext->next) {
1360 err = depmod_modules_search_path(depmod, ext->path);
1361 if (err < 0 && err == -ENOENT)
1362 /* ignore external dir absense */
1369 static int mod_cmp(const void *pa, const void *pb) {
1370 const struct mod *a = *(const struct mod **)pa;
1371 const struct mod *b = *(const struct mod **)pb;
1372 return a->sort_idx - b->sort_idx;
1375 static int depmod_modules_build_array(struct depmod *depmod)
1377 struct hash_iter module_iter;
1381 hash_iter_init(depmod->modules_by_name, &module_iter);
1382 while (hash_iter_next(&module_iter, NULL, &v)) {
1383 struct mod *mod = (struct mod *) v;
1384 mod->idx = depmod->modules.count;
1385 err = array_append(&depmod->modules, mod);
1393 static FILE *dfdopen(const char *dname, const char *filename, int flags,
1399 dfd = open(dname, O_RDONLY);
1401 WRN("could not open directory %s: %m\n", dname);
1405 fd = openat(dfd, filename, flags);
1407 WRN("could not open %s at %s: %m\n", filename, dname);
1410 ret = fdopen(fd, mode);
1412 WRN("could not associate stream with %s: %m\n", filename);
1422 static void depmod_modules_sort(struct depmod *depmod)
1424 char line[PATH_MAX];
1425 const char *order_file = "modules.order";
1427 unsigned idx = 0, total = 0;
1429 fp = dfdopen(depmod->cfg->dirname, order_file, O_RDONLY, "r");
1433 while (fgets(line, sizeof(line), fp) != NULL) {
1434 size_t len = strlen(line);
1438 if (line[len - 1] != '\n') {
1439 ERR("%s/%s:%u corrupted line misses '\\n'\n",
1440 depmod->cfg->dirname, order_file, idx);
1446 fseek(fp, 0, SEEK_SET);
1447 while (fgets(line, sizeof(line), fp) != NULL) {
1448 size_t len = strlen(line);
1454 line[len - 1] = '\0';
1456 mod = hash_find(depmod->modules_by_uncrelpath, line);
1459 mod->sort_idx = idx - total;
1462 array_sort(&depmod->modules, mod_cmp);
1463 for (idx = 0; idx < depmod->modules.count; idx++) {
1464 struct mod *m = depmod->modules.array[idx];
1472 static int depmod_symbol_add(struct depmod *depmod, const char *name,
1473 bool prefix_skipped, uint64_t crc,
1474 const struct mod *owner)
1480 if (!prefix_skipped && (name[0] == depmod->cfg->sym_prefix))
1483 namelen = strlen(name) + 1;
1484 sym = malloc(sizeof(struct symbol) + namelen);
1488 sym->owner = (struct mod *)owner;
1490 memcpy(sym->name, name, namelen);
1492 err = hash_add(depmod->symbols, sym->name, sym);
1498 DBG("add %p sym=%s, owner=%p %s\n", sym, sym->name, owner,
1499 owner != NULL ? owner->path : "");
1504 static struct symbol *depmod_symbol_find(const struct depmod *depmod,
1507 if (name[0] == '.') /* PPC64 needs this: .foo == foo */
1509 if (name[0] == depmod->cfg->sym_prefix)
1511 return hash_find(depmod->symbols, name);
1514 static int depmod_load_modules(struct depmod *depmod)
1516 struct mod **itr, **itr_end;
1518 DBG("load symbols (%zd modules)\n", depmod->modules.count);
1520 itr = (struct mod **)depmod->modules.array;
1521 itr_end = itr + depmod->modules.count;
1522 for (; itr < itr_end; itr++) {
1523 struct mod *mod = *itr;
1524 struct kmod_list *l, *list = NULL;
1525 int err = kmod_module_get_symbols(mod->kmod, &list);
1528 DBG("ignoring %s: no symbols\n", mod->path);
1530 ERR("failed to load symbols from %s: %s\n",
1531 mod->path, strerror(-err));
1534 kmod_list_foreach(l, list) {
1535 const char *name = kmod_module_symbol_get_symbol(l);
1536 uint64_t crc = kmod_module_symbol_get_crc(l);
1537 depmod_symbol_add(depmod, name, false, crc, mod);
1539 kmod_module_symbols_free_list(list);
1542 kmod_module_get_info(mod->kmod, &mod->info_list);
1543 kmod_module_get_dependency_symbols(mod->kmod,
1544 &mod->dep_sym_list);
1545 kmod_module_unref(mod->kmod);
1549 DBG("loaded symbols (%zd modules, %u symbols)\n",
1550 depmod->modules.count, hash_get_count(depmod->symbols));
1555 static int depmod_load_module_dependencies(struct depmod *depmod, struct mod *mod)
1557 const struct cfg *cfg = depmod->cfg;
1558 struct kmod_list *l;
1560 DBG("do dependencies of %s\n", mod->path);
1561 kmod_list_foreach(l, mod->dep_sym_list) {
1562 const char *name = kmod_module_dependency_symbol_get_symbol(l);
1563 uint64_t crc = kmod_module_dependency_symbol_get_crc(l);
1564 int bindtype = kmod_module_dependency_symbol_get_bind(l);
1565 struct symbol *sym = depmod_symbol_find(depmod, name);
1566 uint8_t is_weak = bindtype == KMOD_SYMBOL_WEAK;
1569 DBG("%s needs (%c) unknown symbol %s\n",
1570 mod->path, bindtype, name);
1571 if (cfg->print_unknown && !is_weak)
1572 WRN("%s needs unknown symbol %s\n",
1577 if (cfg->check_symvers && sym->crc != crc && !is_weak) {
1578 DBG("symbol %s (%#"PRIx64") module %s (%#"PRIx64")\n",
1579 sym->name, sym->crc, mod->path, crc);
1580 if (cfg->print_unknown)
1581 WRN("%s disagrees about version of symbol %s\n",
1585 mod_add_dependency(mod, sym);
1591 static int depmod_load_dependencies(struct depmod *depmod)
1593 struct mod **itr, **itr_end;
1595 DBG("load dependencies (%zd modules, %u symbols)\n",
1596 depmod->modules.count, hash_get_count(depmod->symbols));
1598 itr = (struct mod **)depmod->modules.array;
1599 itr_end = itr + depmod->modules.count;
1600 for (; itr < itr_end; itr++) {
1601 struct mod *mod = *itr;
1603 if (mod->dep_sym_list == NULL) {
1604 DBG("ignoring %s: no dependency symbols\n", mod->path);
1608 depmod_load_module_dependencies(depmod, mod);
1611 DBG("loaded dependencies (%zd modules, %u symbols)\n",
1612 depmod->modules.count, hash_get_count(depmod->symbols));
1617 static int dep_cmp(const void *pa, const void *pb)
1619 const struct mod *a = *(const struct mod **)pa;
1620 const struct mod *b = *(const struct mod **)pb;
1621 return a->dep_sort_idx - b->dep_sort_idx;
1624 static void depmod_sort_dependencies(struct depmod *depmod)
1626 struct mod **itr, **itr_end;
1627 itr = (struct mod **)depmod->modules.array;
1628 itr_end = itr + depmod->modules.count;
1629 for (; itr < itr_end; itr++) {
1630 struct mod *m = *itr;
1631 if (m->deps.count > 1)
1632 array_sort(&m->deps, dep_cmp);
1637 struct vertex *parent;
1641 static struct vertex *vertex_new(struct mod *mod, struct vertex *parent)
1645 v = malloc(sizeof(*v));
1654 static void depmod_list_remove_data(struct kmod_list **list, void *data)
1656 struct kmod_list *l;
1658 l = kmod_list_remove_data(*list, data);
1662 static int depmod_report_one_cycle(struct depmod *depmod,
1663 struct vertex *vertex,
1664 struct kmod_list **roots,
1665 struct hash *loop_set)
1667 const char sep[] = " -> ";
1670 struct array reverse;
1676 array_init(&reverse, 3);
1679 for (v = vertex->parent, n = 0;
1681 v = v->parent, n++) {
1683 sz += v->mod->modnamesz - 1;
1684 array_append(&reverse, v);
1685 rc = hash_add(loop_set, v->mod->modname, NULL);
1688 /* the hash will be freed where created */
1690 sz += vertex->mod->modnamesz - 1;
1692 buf = malloc(sz + n * strlen(sep) + 1);
1695 for (i = reverse.count - 1; i >= 0; i--) {
1698 v = reverse.array[i];
1700 len = v->mod->modnamesz - 1;
1701 memcpy(buf + sz, v->mod->modname, len);
1703 strcpy(buf + sz, sep);
1706 depmod_list_remove_data(roots, v->mod);
1708 strcpy(buf + sz, vertex->mod->modname);
1709 ERR("Cycle detected: %s\n", buf);
1712 array_free_array(&reverse);
1717 static int depmod_report_cycles_from_root(struct depmod *depmod,
1718 struct mod *root_mod,
1719 struct kmod_list **roots,
1722 struct hash *loop_set)
1724 struct kmod_list *free_list = NULL; /* struct vertex */
1725 struct kmod_list *l;
1726 struct vertex *root;
1727 struct vertex *vertex;
1730 struct mod **itr, **itr_end;
1734 root = vertex_new(root_mod, NULL);
1736 ERR("No memory to report cycles\n");
1740 l = kmod_list_append(free_list, root);
1742 ERR("No memory to report cycles\n");
1748 stack[is++] = (void *)root;
1751 vertex = stack[--is];
1754 * because of the topological sort we can start only
1755 * from part of a loop or from a branch after a loop
1757 if (m->visited && m == root->mod) {
1759 rc = depmod_report_one_cycle(depmod, vertex,
1769 if (m->deps.count == 0) {
1771 * boundary condition: if there is more than one
1772 * single node branch (not a loop), it is
1773 * recognized as a loop by the code above:
1774 * m->visited because more then one,
1775 * m == root->mod since it is a single node.
1776 * So, prevent deeping into the branch second
1779 depmod_list_remove_data(roots, m);
1784 itr = (struct mod **) m->deps.array;
1785 itr_end = itr + m->deps.count;
1786 for (; itr < itr_end; itr++) {
1787 struct mod *dep = *itr;
1788 v = vertex_new(dep, vertex);
1790 ERR("No memory to report cycles\n");
1793 assert(is < stack_size);
1796 l = kmod_list_append(free_list, v);
1798 ERR("No memory to report cycles\n");
1809 v = free_list->data;
1810 l = kmod_list_remove(free_list);
1818 static void depmod_report_cycles(struct depmod *depmod, uint16_t n_mods,
1822 struct kmod_list *roots = NULL; /* struct mod */
1823 struct kmod_list *l;
1824 size_t n_r; /* local n_roots */
1827 _cleanup_free_ void **stack = NULL;
1830 struct hash *loop_set;
1832 for (i = 0, n_r = 0; i < n_mods; i++) {
1835 m = depmod->modules.array[i];
1836 l = kmod_list_append(roots, m);
1838 ERR("No memory to report cycles\n");
1845 stack = malloc(n_r * sizeof(void *));
1846 if (stack == NULL) {
1847 ERR("No memory to report cycles\n");
1851 loop_set = hash_new(16, NULL);
1852 if (loop_set == NULL) {
1853 ERR("No memory to report cycles\n");
1857 while (roots != NULL) {
1859 l = kmod_list_remove(roots);
1861 err = depmod_report_cycles_from_root(depmod,
1864 stack, n_r, loop_set);
1869 num_cyclic = hash_get_count(loop_set);
1870 ERR("Found %d modules in dependency cycles!\n", num_cyclic);
1873 hash_free(loop_set);
1875 while (roots != NULL) {
1876 /* no need to free data, come from outside */
1877 roots = kmod_list_remove(roots);
1881 static int depmod_calculate_dependencies(struct depmod *depmod)
1883 const struct mod **itrm;
1884 uint16_t *users, *roots, *sorted;
1885 uint16_t i, n_roots = 0, n_sorted = 0, n_mods = depmod->modules.count;
1888 users = malloc(sizeof(uint16_t) * n_mods * 3);
1891 roots = users + n_mods;
1892 sorted = roots + n_mods;
1894 DBG("calculate dependencies and ordering (%hu modules)\n", n_mods);
1896 assert(depmod->modules.count < UINT16_MAX);
1898 /* populate modules users (how many modules uses it) */
1899 itrm = (const struct mod **)depmod->modules.array;
1900 for (i = 0; i < n_mods; i++, itrm++) {
1901 const struct mod *m = *itrm;
1902 users[i] = m->users;
1903 if (users[i] == 0) {
1909 /* topological sort (outputs modules without users first) */
1910 while (n_roots > 0) {
1911 const struct mod **itr_dst, **itr_dst_end;
1913 uint16_t src_idx = roots[--n_roots];
1915 src = depmod->modules.array[src_idx];
1916 src->dep_sort_idx = n_sorted;
1917 sorted[n_sorted] = src_idx;
1920 itr_dst = (const struct mod **)src->deps.array;
1921 itr_dst_end = itr_dst + src->deps.count;
1922 for (; itr_dst < itr_dst_end; itr_dst++) {
1923 const struct mod *dst = *itr_dst;
1924 uint16_t dst_idx = dst->idx;
1925 assert(users[dst_idx] > 0);
1927 if (users[dst_idx] == 0) {
1928 roots[n_roots] = dst_idx;
1934 if (n_sorted < n_mods) {
1935 depmod_report_cycles(depmod, n_mods, users);
1940 depmod_sort_dependencies(depmod);
1942 DBG("calculated dependencies and ordering (%hu modules)\n", n_mods);
1949 static int depmod_load(struct depmod *depmod)
1953 err = depmod_load_modules(depmod);
1957 err = depmod_load_dependencies(depmod);
1961 err = depmod_calculate_dependencies(depmod);
1968 static size_t mod_count_all_dependencies(const struct mod *mod)
1970 size_t i, count = 0;
1971 for (i = 0; i < mod->deps.count; i++) {
1972 const struct mod *d = mod->deps.array[i];
1973 count += 1 + mod_count_all_dependencies(d);
1978 static int mod_fill_all_unique_dependencies(const struct mod *mod, const struct mod **deps, size_t n_deps, size_t *last)
1982 for (i = 0; i < mod->deps.count; i++) {
1983 const struct mod *d = mod->deps.array[i];
1987 for (j = 0; j < *last; j++) {
1997 if (*last >= n_deps)
2001 err = mod_fill_all_unique_dependencies(d, deps, n_deps, last);
2008 static const struct mod **mod_get_all_sorted_dependencies(const struct mod *mod, size_t *n_deps)
2010 const struct mod **deps;
2013 *n_deps = mod_count_all_dependencies(mod);
2017 deps = malloc(sizeof(struct mod *) * (*n_deps));
2021 if (mod_fill_all_unique_dependencies(mod, deps, *n_deps, &last) < 0) {
2026 qsort(deps, last, sizeof(struct mod *), dep_cmp);
2031 static inline const char *mod_get_compressed_path(const struct mod *mod)
2033 if (mod->relpath != NULL)
2034 return mod->relpath;
2038 static int output_deps(struct depmod *depmod, FILE *out)
2042 for (i = 0; i < depmod->modules.count; i++) {
2043 const struct mod **deps, *mod = depmod->modules.array[i];
2044 const char *p = mod_get_compressed_path(mod);
2047 fprintf(out, "%s:", p);
2049 if (mod->deps.count == 0)
2052 deps = mod_get_all_sorted_dependencies(mod, &n_deps);
2054 ERR("could not get all sorted dependencies of %s\n", p);
2058 for (j = 0; j < n_deps; j++) {
2059 const struct mod *d = deps[j];
2060 fprintf(out, " %s", mod_get_compressed_path(d));
2070 static int output_deps_bin(struct depmod *depmod, FILE *out)
2072 struct index_node *idx;
2078 idx = index_create();
2082 for (i = 0; i < depmod->modules.count; i++) {
2083 const struct mod **deps, *mod = depmod->modules.array[i];
2084 const char *p = mod_get_compressed_path(mod);
2086 size_t j, n_deps, linepos, linelen, slen;
2089 deps = mod_get_all_sorted_dependencies(mod, &n_deps);
2090 if (deps == NULL && n_deps > 0) {
2091 ERR("could not get all sorted dependencies of %s\n", p);
2095 linelen = strlen(p) + 1;
2096 for (j = 0; j < n_deps; j++) {
2097 const struct mod *d = deps[j];
2098 linelen += 1 + strlen(mod_get_compressed_path(d));
2101 line = malloc(linelen + 1);
2104 ERR("modules.deps.bin: out of memory\n");
2110 memcpy(line + linepos, p, slen);
2112 line[linepos] = ':';
2115 for (j = 0; j < n_deps; j++) {
2116 const struct mod *d = deps[j];
2119 line[linepos] = ' ';
2122 dp = mod_get_compressed_path(d);
2124 memcpy(line + linepos, dp, slen);
2127 line[linepos] = '\0';
2129 duplicate = index_insert(idx, mod->modname, line, mod->idx);
2130 if (duplicate && depmod->cfg->warn_dups)
2131 WRN("duplicate module deps:\n%s\n", line);
2136 index_write(idx, out);
2142 static int output_aliases(struct depmod *depmod, FILE *out)
2146 fputs("# Aliases extracted from modules themselves.\n", out);
2148 for (i = 0; i < depmod->modules.count; i++) {
2149 const struct mod *mod = depmod->modules.array[i];
2150 struct kmod_list *l;
2152 kmod_list_foreach(l, mod->info_list) {
2153 const char *key = kmod_module_info_get_key(l);
2154 const char *value = kmod_module_info_get_value(l);
2156 if (!streq(key, "alias"))
2159 fprintf(out, "alias %s %s\n", value, mod->modname);
2166 static int output_aliases_bin(struct depmod *depmod, FILE *out)
2168 struct index_node *idx;
2174 idx = index_create();
2178 for (i = 0; i < depmod->modules.count; i++) {
2179 const struct mod *mod = depmod->modules.array[i];
2180 struct kmod_list *l;
2182 kmod_list_foreach(l, mod->info_list) {
2183 const char *key = kmod_module_info_get_key(l);
2184 const char *value = kmod_module_info_get_value(l);
2189 if (!streq(key, "alias"))
2192 if (alias_normalize(value, buf, NULL) < 0) {
2193 WRN("Unmatched bracket in %s\n", value);
2198 duplicate = index_insert(idx, alias, mod->modname,
2200 if (duplicate && depmod->cfg->warn_dups)
2201 WRN("duplicate module alias:\n%s %s\n",
2202 alias, mod->modname);
2206 index_write(idx, out);
2212 static int output_softdeps(struct depmod *depmod, FILE *out)
2216 fputs("# Soft dependencies extracted from modules themselves.\n", out);
2218 for (i = 0; i < depmod->modules.count; i++) {
2219 const struct mod *mod = depmod->modules.array[i];
2220 struct kmod_list *l;
2222 kmod_list_foreach(l, mod->info_list) {
2223 const char *key = kmod_module_info_get_key(l);
2224 const char *value = kmod_module_info_get_value(l);
2226 if (!streq(key, "softdep"))
2229 fprintf(out, "softdep %s %s\n", mod->modname, value);
2236 static int output_symbols(struct depmod *depmod, FILE *out)
2238 struct hash_iter iter;
2241 fputs("# Aliases for symbols, used by symbol_request().\n", out);
2243 hash_iter_init(depmod->symbols, &iter);
2245 while (hash_iter_next(&iter, NULL, &v)) {
2246 const struct symbol *sym = v;
2247 if (sym->owner == NULL)
2250 fprintf(out, "alias symbol:%s %s\n",
2251 sym->name, sym->owner->modname);
2257 static int output_symbols_bin(struct depmod *depmod, FILE *out)
2259 struct index_node *idx;
2261 _cleanup_(scratchbuf_release) struct scratchbuf salias =
2262 SCRATCHBUF_INITIALIZER(alias);
2263 size_t baselen = sizeof("symbol:") - 1;
2264 struct hash_iter iter;
2271 idx = index_create();
2275 memcpy(alias, "symbol:", baselen);
2277 hash_iter_init(depmod->symbols, &iter);
2279 while (hash_iter_next(&iter, NULL, &v)) {
2281 const struct symbol *sym = v;
2284 if (sym->owner == NULL)
2287 len = strlen(sym->name);
2289 if (scratchbuf_alloc(&salias, baselen + len + 1) < 0) {
2291 goto err_scratchbuf;
2293 memcpy(scratchbuf_str(&salias) + baselen, sym->name, len + 1);
2294 duplicate = index_insert(idx, alias, sym->owner->modname,
2297 if (duplicate && depmod->cfg->warn_dups)
2298 WRN("duplicate module syms:\n%s %s\n",
2299 alias, sym->owner->modname);
2302 index_write(idx, out);
2308 ERR("output symbols: %s\n", strerror(-ret));
2313 static int output_builtin_bin(struct depmod *depmod, FILE *out)
2316 struct index_node *idx;
2317 char line[PATH_MAX], modname[PATH_MAX];
2322 in = dfdopen(depmod->cfg->dirname, "modules.builtin", O_RDONLY, "r");
2326 idx = index_create();
2332 while (fgets(line, sizeof(line), in) != NULL) {
2333 if (!isalpha(line[0])) {
2334 ERR("Invalid modules.builtin line: %s\n", line);
2338 path_to_modname(line, modname, NULL);
2339 index_insert(idx, modname, "", 0);
2342 index_write(idx, out);
2349 static int output_devname(struct depmod *depmod, FILE *out)
2354 for (i = 0; i < depmod->modules.count; i++) {
2355 const struct mod *mod = depmod->modules.array[i];
2356 struct kmod_list *l;
2357 const char *devname = NULL;
2359 unsigned int major = 0, minor = 0;
2361 kmod_list_foreach(l, mod->info_list) {
2362 const char *key = kmod_module_info_get_key(l);
2363 const char *value = kmod_module_info_get_value(l);
2364 unsigned int maj, min;
2366 if (!streq(key, "alias"))
2369 if (strstartswith(value, "devname:"))
2370 devname = value + sizeof("devname:") - 1;
2371 else if (sscanf(value, "char-major-%u-%u",
2376 } else if (sscanf(value, "block-major-%u-%u",
2383 if (type != '\0' && devname != NULL)
2387 if (devname != NULL) {
2390 fputs("# Device nodes to trigger on-demand module loading.\n",
2394 fprintf(out, "%s %s %c%u:%u\n", mod->modname,
2395 devname, type, major, minor);
2397 ERR("Module '%s' has devname (%s) but "
2398 "lacks major and minor information. "
2399 "Ignoring.\n", mod->modname, devname);
2406 static int output_builtin_alias_bin(struct depmod *depmod, FILE *out)
2408 int ret = 0, count = 0;
2409 struct index_node *idx;
2410 struct kmod_list *l, *builtin = NULL;
2415 idx = index_create();
2419 ret = kmod_module_get_builtin(depmod->ctx, &builtin);
2426 kmod_list_foreach(l, builtin) {
2427 struct kmod_list *ll, *info_list = NULL;
2428 struct kmod_module *mod = l->data;
2429 const char *modname = kmod_module_get_name(mod);
2431 ret = kmod_module_get_info(mod, &info_list);
2435 kmod_list_foreach(ll, info_list) {
2436 char alias[PATH_MAX];
2437 const char *key = kmod_module_info_get_key(ll);
2438 const char *value = kmod_module_info_get_value(ll);
2440 if (!streq(key, "alias"))
2444 if (alias_normalize(value, alias, NULL) < 0) {
2445 WRN("Unmatched bracket in %s\n", value);
2449 index_insert(idx, alias, modname, 0);
2452 kmod_module_info_free_list(info_list);
2454 index_insert(idx, modname, modname, 0);
2459 /* do not bother writing the index if we are going to discard it */
2461 index_write(idx, out);
2464 kmod_module_unref_list(builtin);
2471 static int depmod_output(struct depmod *depmod, FILE *out)
2473 static const struct depfile {
2475 int (*cb)(struct depmod *depmod, FILE *out);
2476 } *itr, depfiles[] = {
2477 { "modules.dep", output_deps },
2478 { "modules.dep.bin", output_deps_bin },
2479 { "modules.alias", output_aliases },
2480 { "modules.alias.bin", output_aliases_bin },
2481 { "modules.softdep", output_softdeps },
2482 { "modules.symbols", output_symbols },
2483 { "modules.symbols.bin", output_symbols_bin },
2484 { "modules.builtin.bin", output_builtin_bin },
2485 { "modules.builtin.alias.bin", output_builtin_alias_bin },
2486 { "modules.devname", output_devname },
2489 const char *dname = depmod->cfg->dirname;
2493 gettimeofday(&tv, NULL);
2498 dfd = open(dname, O_RDONLY);
2501 CRIT("could not open directory %s: %m\n", dname);
2506 for (itr = depfiles; itr->name != NULL; itr++) {
2508 char tmp[NAME_MAX] = "";
2512 int flags = O_CREAT | O_EXCL | O_WRONLY;
2516 snprintf(tmp, sizeof(tmp), "%s.%i.%li.%li", itr->name, getpid(),
2517 tv.tv_usec, tv.tv_sec);
2518 fd = openat(dfd, tmp, flags, mode);
2520 ERR("openat(%s, %s, %o, %o): %m\n",
2521 dname, tmp, flags, mode);
2524 fp = fdopen(fd, "wb");
2526 ERR("fdopen(%d=%s/%s): %m\n", fd, dname, tmp);
2532 r = itr->cb(depmod, fp);
2536 ferr = ferror(fp) | fclose(fp);
2539 if (unlinkat(dfd, tmp, 0) != 0)
2540 ERR("unlinkat(%s, %s): %m\n", dname, tmp);
2542 ERR("Could not write index '%s': %s\n", itr->name,
2548 if (renameat(dfd, tmp, dfd, itr->name) != 0) {
2550 CRIT("renameat(%s, %s, %s, %s): %m\n",
2551 dname, tmp, dname, itr->name);
2557 ERR("Could not create index '%s'. Output is truncated: %s\n",
2558 itr->name, strerror(-err));
2569 static void depmod_add_fake_syms(struct depmod *depmod)
2571 /* __this_module is magic inserted by kernel loader. */
2572 depmod_symbol_add(depmod, "__this_module", true, 0, NULL);
2573 /* On S390, this is faked up too */
2574 depmod_symbol_add(depmod, "_GLOBAL_OFFSET_TABLE_", true, 0, NULL);
2575 /* On PowerPC64 ABIv2, .TOC. is more or less _GLOBAL_OFFSET_TABLE_ */
2576 if (!depmod_symbol_find(depmod, "TOC."))
2577 depmod_symbol_add(depmod, "TOC.", true, 0, NULL);
2580 static int depmod_load_symvers(struct depmod *depmod, const char *filename)
2584 unsigned int linenum = 0;
2586 fp = fopen(filename, "r");
2589 DBG("load symvers: %s: %m\n", filename);
2592 DBG("load symvers: %s\n", filename);
2594 /* eg. "0xb352177e\tfind_first_bit\tvmlinux\tEXPORT_SYMBOL" */
2595 while (fgets(line, sizeof(line), fp) != NULL) {
2596 const char *ver, *sym, *where;
2602 ver = strtok(line, " \t");
2603 sym = strtok(NULL, " \t");
2604 where = strtok(NULL, " \t");
2605 if (!ver || !sym || !where)
2608 if (!streq(where, "vmlinux"))
2611 crc = strtoull(ver, &verend, 16);
2612 if (verend[0] != '\0') {
2613 ERR("%s:%u Invalid symbol version %s: %m\n",
2614 filename, linenum, ver);
2618 depmod_symbol_add(depmod, sym, false, crc, NULL);
2620 depmod_add_fake_syms(depmod);
2622 DBG("loaded symvers: %s\n", filename);
2628 static int depmod_load_system_map(struct depmod *depmod, const char *filename)
2630 const char ksymstr[] = "__ksymtab_";
2631 const size_t ksymstr_len = sizeof(ksymstr) - 1;
2634 unsigned int linenum = 0;
2636 fp = fopen(filename, "r");
2639 DBG("load System.map: %s: %m\n", filename);
2642 DBG("load System.map: %s\n", filename);
2644 /* eg. c0294200 R __ksymtab_devfs_alloc_devnum */
2645 while (fgets(line, sizeof(line), fp) != NULL) {
2650 p = strchr(line, ' ');
2652 goto invalid_syntax;
2656 goto invalid_syntax;
2660 if (p[0] == depmod->cfg->sym_prefix)
2663 /* Covers gpl-only and normal symbols. */
2664 if (strncmp(p, ksymstr, ksymstr_len) != 0)
2667 end = strchr(p, '\n');
2671 depmod_symbol_add(depmod, p + ksymstr_len, true, 0, NULL);
2675 ERR("%s:%u: invalid line: %s\n", filename, linenum, line);
2677 depmod_add_fake_syms(depmod);
2679 DBG("loaded System.map: %s\n", filename);
2686 static int depfile_up_to_date_dir(DIR *d, time_t mtime, size_t baselen, char *path)
2689 int err = 1, dfd = dirfd(d);
2691 while ((de = readdir(d)) != NULL) {
2692 const char *name = de->d_name;
2696 if (name[0] == '.' && (name[1] == '\0' ||
2697 (name[1] == '.' && name[2] == '\0')))
2699 if (streq(name, "build") || streq(name, "source"))
2701 namelen = strlen(name);
2702 if (baselen + namelen + 2 >= PATH_MAX) {
2703 path[baselen] = '\0';
2704 ERR("path is too long %s%s\n", path, name);
2708 if (fstatat(dfd, name, &st, 0) < 0) {
2709 ERR("fstatat(%d, %s): %m\n", dfd, name);
2713 if (S_ISDIR(st.st_mode)) {
2716 memcpy(path + baselen, name, namelen + 1);
2717 if (baselen + namelen + 2 + NAME_MAX >= PATH_MAX) {
2718 ERR("directory path is too long %s\n", path);
2721 fd = openat(dfd, name, O_RDONLY);
2723 ERR("openat(%d, %s, O_RDONLY): %m\n",
2727 subdir = fdopendir(fd);
2728 if (subdir == NULL) {
2729 ERR("fdopendir(%d): %m\n", fd);
2733 path[baselen + namelen] = '/';
2734 path[baselen + namelen + 1] = '\0';
2735 err = depfile_up_to_date_dir(subdir, mtime,
2736 baselen + namelen + 1,
2739 } else if (S_ISREG(st.st_mode)) {
2740 if (!path_ends_with_kmod_ext(name, namelen))
2743 memcpy(path + baselen, name, namelen + 1);
2744 err = st.st_mtime <= mtime;
2746 DBG("%s %"PRIu64" is newer than %"PRIu64"\n",
2747 path, (uint64_t)st.st_mtime,
2751 ERR("unsupported file type %s: %o\n",
2752 path, st.st_mode & S_IFMT);
2757 break; /* outdated! */
2759 path[baselen + namelen] = '\0';
2760 ERR("failed %s: %s\n", path, strerror(-err));
2761 err = 1; /* ignore errors */
2768 /* uptodate: 1, outdated: 0, errors < 0 */
2769 static int depfile_up_to_date(const char *dirname)
2771 char path[PATH_MAX];
2772 DIR *d = opendir(dirname);
2778 ERR("could not open directory %s: %m\n", dirname);
2782 if (fstatat(dirfd(d), "modules.dep", &st, 0) != 0) {
2784 ERR("could not fstatat(%s, modules.dep): %m\n", dirname);
2789 baselen = strlen(dirname);
2790 memcpy(path, dirname, baselen);
2791 path[baselen] = '/';
2793 path[baselen] = '\0';
2795 err = depfile_up_to_date_dir(d, st.st_mtime, baselen, path);
2800 static int is_version_number(const char *version)
2802 unsigned int d1, d2;
2803 return (sscanf(version, "%u.%u", &d1, &d2) == 2);
2806 static int do_depmod(int argc, char *argv[])
2809 int err = 0, all = 0, maybe_all = 0, n_config_paths = 0;
2810 _cleanup_free_ char *root = NULL;
2811 _cleanup_free_ const char **config_paths = NULL;
2812 const char *system_map = NULL;
2813 const char *module_symvers = NULL;
2814 const char *null_kmod_config = NULL;
2816 struct kmod_ctx *ctx = NULL;
2818 struct depmod depmod;
2820 memset(&cfg, 0, sizeof(cfg));
2821 memset(&depmod, 0, sizeof(depmod));
2825 c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx);
2838 root = path_make_absolute_cwd(optarg);
2841 size_t bytes = sizeof(char *) * (n_config_paths + 2);
2842 void *tmp = realloc(config_paths, bytes);
2844 fputs("Error: out-of-memory\n", stderr);
2845 goto cmdline_failed;
2848 config_paths[n_config_paths] = optarg;
2850 config_paths[n_config_paths] = NULL;
2854 module_symvers = optarg;
2855 cfg.check_symvers = 1;
2858 system_map = optarg;
2861 cfg.print_unknown = 1;
2870 if (optarg[1] != '\0') {
2871 CRIT("-P only takes a single char\n");
2872 goto cmdline_failed;
2874 cfg.sym_prefix = optarg[0];
2884 WRN("Ignored deprecated option --%s\n",
2887 WRN("Ignored deprecated option -%c\n", c);
2892 return EXIT_SUCCESS;
2894 puts(PACKAGE " version " VERSION);
2895 puts(KMOD_FEATURES);
2896 return EXIT_SUCCESS;
2898 goto cmdline_failed;
2900 ERR("unexpected getopt_long() value '%c'.\n", c);
2901 goto cmdline_failed;
2905 if (optind < argc) {
2906 if (!is_version_number(argv[optind])) {
2907 ERR("Bad version passed %s\n", argv[optind]);
2908 goto cmdline_failed;
2910 cfg.kversion = argv[optind];
2913 if (uname(&un) < 0) {
2914 CRIT("uname() failed: %s\n", strerror(errno));
2915 goto cmdline_failed;
2917 cfg.kversion = un.release;
2920 cfg.dirnamelen = snprintf(cfg.dirname, PATH_MAX,
2921 "%s/lib/modules/%s",
2922 root == NULL ? "" : root, cfg.kversion);
2930 /* ignore up-to-date errors (< 0) */
2931 if (depfile_up_to_date(cfg.dirname) == 1)
2936 ctx = kmod_new(cfg.dirname, &null_kmod_config);
2938 CRIT("kmod_new(\"%s\", {NULL}) failed: %m\n", cfg.dirname);
2939 goto cmdline_failed;
2942 log_setup_kmod_log(ctx, verbose);
2944 err = depmod_init(&depmod, &cfg, ctx);
2946 CRIT("depmod_init: %s\n", strerror(-err));
2947 goto depmod_init_failed;
2949 ctx = NULL; /* owned by depmod */
2951 if (module_symvers != NULL) {
2952 err = depmod_load_symvers(&depmod, module_symvers);
2954 CRIT("could not load %s: %s\n", module_symvers,
2956 goto cmdline_failed;
2958 } else if (system_map != NULL) {
2959 err = depmod_load_system_map(&depmod, system_map);
2961 CRIT("could not load %s: %s\n", system_map,
2963 goto cmdline_failed;
2965 } else if (cfg.print_unknown) {
2966 WRN("-e needs -E or -F\n");
2967 cfg.print_unknown = 0;
2971 err = cfg_load(&cfg, config_paths);
2973 CRIT("could not load configuration files\n");
2974 goto cmdline_modules_failed;
2976 err = depmod_modules_search(&depmod);
2978 CRIT("could not search modules: %s\n", strerror(-err));
2979 goto cmdline_modules_failed;
2984 for (i = optind; i < argc; i++) {
2985 const char *path = argv[i];
2986 struct kmod_module *mod;
2988 if (path[0] != '/') {
2989 CRIT("%s: not absolute path.\n", path);
2990 goto cmdline_modules_failed;
2993 err = kmod_module_new_from_path(depmod.ctx, path, &mod);
2995 CRIT("could not create module %s: %s\n",
2996 path, strerror(-err));
2997 goto cmdline_modules_failed;
3000 err = depmod_module_add(&depmod, mod);
3002 CRIT("could not add module %s: %s\n",
3003 path, strerror(-err));
3004 kmod_module_unref(mod);
3005 goto cmdline_modules_failed;
3010 err = depmod_modules_build_array(&depmod);
3012 CRIT("could not build module array: %s\n",
3014 goto cmdline_modules_failed;
3017 depmod_modules_sort(&depmod);
3018 err = depmod_load(&depmod);
3020 goto cmdline_modules_failed;
3022 err = depmod_output(&depmod, out);
3025 depmod_shutdown(&depmod);
3027 return err >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
3029 cmdline_modules_failed:
3030 depmod_shutdown(&depmod);
3036 return EXIT_FAILURE;
3039 const struct kmod_cmd kmod_cmd_compat_depmod = {
3042 .help = "compat depmod command",