]> git.ipfire.org Git - thirdparty/kmod.git/blob - tools/depmod.c
depmod: prevent module dependency files corruption due to parallel invocation.
[thirdparty/kmod.git] / tools / depmod.c
1 /*
2 * kmod-depmod - calculate modules.dep using libkmod.
3 *
4 * Copyright (C) 2011-2013 ProFUSION embedded systems
5 *
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.
10 *
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.
15 *
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/>.
18 */
19
20 #include <assert.h>
21 #include <ctype.h>
22 #include <dirent.h>
23 #include <errno.h>
24 #include <getopt.h>
25 #include <limits.h>
26 #include <regex.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33 #include <sys/utsname.h>
34
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>
40
41 #include <libkmod/libkmod-internal.h>
42
43 #undef ERR
44 #undef DBG
45
46 #include "kmod.h"
47
48 #define DEFAULT_VERBOSE LOG_WARNING
49 static int verbose = DEFAULT_VERBOSE;
50
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 "/run/depmod.d",
55 SYSCONFDIR "/depmod.d",
56 "/lib/depmod.d",
57 NULL
58 };
59
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' },
80 { }
81 };
82
83 static void help(void)
84 {
85 printf("Usage:\n"
86 "\t%s -[aA] [options] [forced_version]\n"
87 "\n"
88 "If no arguments (except options) are given, \"depmod -a\" is assumed\n"
89 "\n"
90 "depmod will output a dependency list suitable for the modprobe utility.\n"
91 "\n"
92 "Options:\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"
103 "\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);
111 }
112
113 _printf_format_(1, 2)
114 static inline void _show(const char *fmt, ...)
115 {
116 va_list args;
117
118 if (verbose <= DEFAULT_VERBOSE)
119 return;
120
121 va_start(args, fmt);
122 vfprintf(stdout, fmt, args);
123 fflush(stdout);
124 va_end(args);
125 }
126 #define SHOW(...) _show(__VA_ARGS__)
127
128
129 /* binary index write *************************************************/
130 #include <arpa/inet.h>
131 /* BEGIN: code from module-init-tools/index.c just modified to compile here.
132 *
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>.
136 *
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.
141 *
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.
146 *
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/>.
149 */
150
151 /* see documentation in libkmod/libkmod-index.c */
152
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
158
159 struct index_value {
160 struct index_value *next;
161 unsigned int priority;
162 char value[0];
163 };
164
165 /* In-memory index (depmod only) */
166 struct index_node {
167 char *prefix; /* path compression */
168 struct index_value *values;
169 unsigned char first; /* range of child nodes */
170 unsigned char last;
171 struct index_node *children[INDEX_CHILDMAX]; /* indexed by character */
172 };
173
174
175 /* Format of node offsets within index file */
176 enum node_offset {
177 INDEX_NODE_FLAGS = 0xF0000000, /* Flags in high nibble */
178 INDEX_NODE_PREFIX = 0x80000000,
179 INDEX_NODE_VALUES = 0x40000000,
180 INDEX_NODE_CHILDS = 0x20000000,
181
182 INDEX_NODE_MASK = 0x0FFFFFFF, /* Offset value */
183 };
184
185 static struct index_node *index_create(void)
186 {
187 struct index_node *node;
188
189 node = NOFAIL(calloc(sizeof(struct index_node), 1));
190 node->prefix = NOFAIL(strdup(""));
191 node->first = INDEX_CHILDMAX;
192
193 return node;
194 }
195
196 static void index_values_free(struct index_value *values)
197 {
198 while (values) {
199 struct index_value *value = values;
200
201 values = value->next;
202 free(value);
203 }
204 }
205
206 static void index_destroy(struct index_node *node)
207 {
208 int c;
209
210 for (c = node->first; c <= node->last; c++) {
211 struct index_node *child = node->children[c];
212
213 if (child)
214 index_destroy(child);
215 }
216 index_values_free(node->values);
217 free(node->prefix);
218 free(node);
219 }
220
221 static void index__checkstring(const char *str)
222 {
223 int i;
224
225 for (i = 0; str[i]; i++) {
226 int ch = str[i];
227
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);
231 }
232 }
233
234 static int index_add_value(struct index_value **values,
235 const char *value, unsigned int priority)
236 {
237 struct index_value *v;
238 int duplicate = 0;
239 int len;
240
241 /* report the presence of duplicate values */
242 for (v = *values; v; v = v->next) {
243 if (streq(v->value, value))
244 duplicate = 1;
245 }
246
247 /* find position to insert value */
248 while (*values && (*values)->priority < priority)
249 values = &(*values)->next;
250
251 len = strlen(value);
252 v = NOFAIL(calloc(sizeof(struct index_value) + len + 1, 1));
253 v->next = *values;
254 v->priority = priority;
255 memcpy(v->value, value, len + 1);
256 *values = v;
257
258 return duplicate;
259 }
260
261 static int index_insert(struct index_node *node, const char *key,
262 const char *value, unsigned int priority)
263 {
264 int i = 0; /* index within str */
265 int ch;
266
267 index__checkstring(key);
268 index__checkstring(value);
269
270 while(1) {
271 int j; /* index within node->prefix */
272
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];
277
278 if (ch != key[i+j]) {
279 char *prefix = node->prefix;
280 struct index_node *n;
281
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]));
286
287 /* Parent has prefix[0..j], child at prefix[j] */
288 memset(node, 0, sizeof(struct index_node));
289 prefix[j] = '\0';
290 node->prefix = prefix;
291 node->first = ch;
292 node->last = ch;
293 node->children[ch] = n;
294
295 break;
296 }
297 }
298 /* j is now length of node->prefix */
299 i += j;
300
301 ch = key[i];
302 if(ch == '\0')
303 return index_add_value(&node->values, value, priority);
304
305 if (!node->children[ch]) {
306 struct index_node *child;
307
308 if (ch < node->first)
309 node->first = ch;
310 if (ch > node->last)
311 node->last = ch;
312 node->children[ch] = NOFAIL(calloc(sizeof(struct index_node), 1));
313
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);
318
319 return 0;
320 }
321
322 /* Descend into child node and continue */
323 node = node->children[ch];
324 i++;
325 }
326 }
327
328 static int index__haschildren(const struct index_node *node)
329 {
330 return node->first < INDEX_CHILDMAX;
331 }
332
333 /* Recursive post-order traversal
334
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.
339 */
340 static uint32_t index_write__node(const struct index_node *node, FILE *out)
341 {
342 uint32_t *child_offs = NULL;
343 int child_count = 0;
344 long offset;
345
346 if (!node)
347 return 0;
348
349 /* Write children and save their offsets */
350 if (index__haschildren(node)) {
351 const struct index_node *child;
352 int i;
353
354 child_count = node->last - node->first + 1;
355 child_offs = NOFAIL(malloc(child_count * sizeof(uint32_t)));
356
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));
360 }
361 }
362
363 /* Now write this node */
364 offset = ftell(out);
365
366 if (node->prefix[0]) {
367 fputs(node->prefix, out);
368 fputc('\0', out);
369 offset |= INDEX_NODE_PREFIX;
370 }
371
372 if (child_count) {
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;
377 }
378
379 free(child_offs);
380
381 if (node->values) {
382 const struct index_value *v;
383 unsigned int value_count;
384 uint32_t u;
385
386 value_count = 0;
387 for (v = node->values; v != NULL; v = v->next)
388 value_count++;
389 u = htonl(value_count);
390 fwrite(&u, sizeof(u), 1, out);
391
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);
396 fputc('\0', out);
397 }
398 offset |= INDEX_NODE_VALUES;
399 }
400
401 return offset;
402 }
403
404 static void index_write(const struct index_node *node, FILE *out)
405 {
406 long initial_offset, final_offset;
407 uint32_t u;
408
409 u = htonl(INDEX_MAGIC);
410 fwrite(&u, sizeof(u), 1, out);
411 u = htonl(INDEX_VERSION);
412 fwrite(&u, sizeof(u), 1, out);
413
414 /* Second word is reserved for the offset of the root node */
415 initial_offset = ftell(out);
416 assert(initial_offset >= 0);
417 u = 0;
418 fwrite(&u, sizeof(uint32_t), 1, out);
419
420 /* Dump trie */
421 u = htonl(index_write__node(node, out));
422
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);
429 }
430
431 /* END: code from module-init-tools/index.c just modified to compile here.
432 */
433
434 /* configuration parsing **********************************************/
435 struct cfg_override {
436 struct cfg_override *next;
437 size_t len;
438 char path[];
439 };
440
441 enum search_type {
442 SEARCH_PATH,
443 SEARCH_BUILTIN,
444 SEARCH_EXTERNAL
445 };
446
447 struct cfg_search {
448 struct cfg_search *next;
449 enum search_type type;
450 size_t len;
451 char path[];
452 };
453
454 struct cfg_external {
455 struct cfg_external *next;
456 size_t len;
457 char path[];
458 };
459
460 struct cfg {
461 const char *kversion;
462 char dirname[PATH_MAX];
463 size_t dirnamelen;
464 char sym_prefix;
465 uint8_t check_symvers;
466 uint8_t print_unknown;
467 uint8_t warn_dups;
468 struct cfg_override *overrides;
469 struct cfg_search *searches;
470 struct cfg_external *externals;
471 };
472
473 static enum search_type cfg_define_search_type(const char *path)
474 {
475 if (streq(path, CFG_BUILTIN_KEY))
476 return SEARCH_BUILTIN;
477 if (streq(path, CFG_EXTERNAL_KEY))
478 return SEARCH_EXTERNAL;
479 return SEARCH_PATH;
480 }
481
482 static int cfg_search_add(struct cfg *cfg, const char *path)
483 {
484 struct cfg_search *s;
485 size_t len;
486 enum search_type type;
487
488 type = cfg_define_search_type(path);
489
490 if (type != SEARCH_PATH)
491 len = 0;
492 else
493 len = strlen(path) + 1;
494
495 s = malloc(sizeof(struct cfg_search) + len);
496 if (s == NULL) {
497 ERR("search add: out of memory\n");
498 return -ENOMEM;
499 }
500 s->type = type;
501 if (type != SEARCH_PATH)
502 s->len = 0;
503 else {
504 s->len = len - 1;
505 memcpy(s->path, path, len);
506 }
507
508 DBG("search add: %s, search type=%hhu\n", path, type);
509
510 s->next = cfg->searches;
511 cfg->searches = s;
512 return 0;
513 }
514
515 static void cfg_search_free(struct cfg_search *s)
516 {
517 free(s);
518 }
519
520 static int cfg_override_add(struct cfg *cfg, const char *modname, const char *subdir)
521 {
522 struct cfg_override *o;
523 size_t modnamelen = strlen(modname);
524 size_t subdirlen = strlen(subdir);
525 size_t i;
526
527 o = malloc(sizeof(struct cfg_override) + subdirlen + 1
528 + modnamelen + 1);
529 if (o == NULL) {
530 ERR("override add: out of memory\n");
531 return -ENOMEM;
532 }
533 memcpy(o->path, subdir, subdirlen);
534 i = subdirlen;
535 o->path[i] = '/';
536 i++;
537
538 memcpy(o->path + i, modname, modnamelen);
539 i += modnamelen;
540 o->path[i] = '\0'; /* no extension, so we can match .ko/.ko.gz */
541
542 o->len = i;
543
544 DBG("override add: %s\n", o->path);
545
546 o->next = cfg->overrides;
547 cfg->overrides = o;
548 return 0;
549 }
550
551 static void cfg_override_free(struct cfg_override *o)
552 {
553 free(o);
554 }
555
556 static int cfg_external_add(struct cfg *cfg, const char *path)
557 {
558 struct cfg_external *ext;
559 size_t len = strlen(path);
560
561 ext = malloc(sizeof(struct cfg_external) + len + 1);
562 if (ext == NULL) {
563 ERR("external add: out of memory\n");
564 return -ENOMEM;
565 }
566
567 strcpy(ext->path, path);
568 ext->len = len;
569
570 DBG("external add: %s\n", ext->path);
571
572 ext->next = cfg->externals;
573 cfg->externals = ext;
574 return 0;
575 }
576
577 static void cfg_external_free(struct cfg_external *ext)
578 {
579 free(ext);
580 }
581
582 static int cfg_kernel_matches(const struct cfg *cfg, const char *pattern)
583 {
584 regex_t re;
585 int status;
586
587 /* old style */
588 if (streq(pattern, "*"))
589 return 1;
590
591 if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
592 return 0;
593
594 status = regexec(&re, cfg->kversion, 0, NULL, 0);
595 regfree(&re);
596
597 return status == 0;
598 }
599
600 static int cfg_file_parse(struct cfg *cfg, const char *filename)
601 {
602 char *line;
603 FILE *fp;
604 unsigned int linenum = 0;
605 int err;
606
607 fp = fopen(filename, "r");
608 if (fp == NULL) {
609 err = -errno;
610 ERR("file parse %s: %m\n", filename);
611 return err;
612 }
613
614 while ((line = freadline_wrapped(fp, &linenum)) != NULL) {
615 char *cmd, *saveptr;
616
617 if (line[0] == '\0' || line[0] == '#')
618 goto done_next;
619
620 cmd = strtok_r(line, "\t ", &saveptr);
621 if (cmd == NULL)
622 goto done_next;
623
624 if (streq(cmd, "search")) {
625 const char *sp;
626 while ((sp = strtok_r(NULL, "\t ", &saveptr)) != NULL) {
627 cfg_search_add(cfg, sp);
628 }
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);
633
634 if (modname == NULL || version == NULL ||
635 subdir == NULL)
636 goto syntax_error;
637
638 if (!cfg_kernel_matches(cfg, version)) {
639 INF("%s:%u: override kernel did not match %s\n",
640 filename, linenum, version);
641 goto done_next;
642 }
643
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);
648
649 if (version == NULL || dir == NULL)
650 goto syntax_error;
651
652 if (!cfg_kernel_matches(cfg, version)) {
653 INF("%s:%u: external directory did not match %s\n",
654 filename, linenum, version);
655 goto done_next;
656 }
657
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);
663 } else {
664 syntax_error:
665 ERR("%s:%u: ignoring bad line starting with '%s'\n",
666 filename, linenum, cmd);
667 }
668
669 done_next:
670 free(line);
671 }
672
673 fclose(fp);
674
675 return 0;
676 }
677
678 static int cfg_files_filter_out(DIR *d, const char *dir, const char *name)
679 {
680 size_t len = strlen(name);
681 struct stat st;
682
683 if (name[0] == '.')
684 return 1;
685
686 if (len < 6 || !streq(name + len - 5, ".conf")) {
687 INF("All cfg files need .conf: %s/%s\n", dir, name);
688 return 1;
689 }
690
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",
694 dir, name);
695 return 1;
696 }
697
698 return 0;
699 }
700
701 struct cfg_file {
702 size_t dirlen;
703 size_t namelen;
704 const char *name;
705 char path[];
706 };
707
708 static void cfg_file_free(struct cfg_file *f)
709 {
710 free(f);
711 }
712
713 static int cfg_files_insert_sorted(struct cfg_file ***p_files, size_t *p_n_files,
714 const char *dir, const char *name)
715 {
716 struct cfg_file **files, *f;
717 size_t i, n_files, namelen, dirlen;
718 void *tmp;
719
720 dirlen = strlen(dir);
721 if (name != NULL)
722 namelen = strlen(name);
723 else {
724 name = basename(dir);
725 namelen = strlen(name);
726 dirlen -= namelen + 1;
727 }
728
729 n_files = *p_n_files;
730 files = *p_files;
731 for (i = 0; i < n_files; i++) {
732 int cmp = strcmp(name, files[i]->name);
733 if (cmp == 0) {
734 DBG("Ignoring duplicate config file: %.*s/%s\n",
735 (int)dirlen, dir, name);
736 return -EEXIST;
737 } else if (cmp < 0)
738 break;
739 }
740
741 f = malloc(sizeof(struct cfg_file) + dirlen + namelen + 2);
742 if (f == NULL) {
743 ERR("files insert sorted: out of memory\n");
744 return -ENOMEM;
745 }
746
747 tmp = realloc(files, sizeof(struct cfg_file *) * (n_files + 1));
748 if (tmp == NULL) {
749 ERR("files insert sorted: out of memory\n");
750 free(f);
751 return -ENOMEM;
752 }
753 *p_files = files = tmp;
754
755 if (i < n_files) {
756 memmove(files + i + 1, files + i,
757 sizeof(struct cfg_file *) * (n_files - i));
758 }
759 files[i] = f;
760
761 f->dirlen = dirlen;
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';
768
769 *p_n_files = n_files + 1;
770 return 0;
771 }
772
773 /*
774 * Insert configuration files ignoring duplicates
775 */
776 static int cfg_files_list(struct cfg_file ***p_files, size_t *p_n_files,
777 const char *path)
778 {
779 struct dirent *dent;
780 DIR *d;
781 int err = 0;
782 struct stat st;
783
784 if (stat(path, &st) != 0) {
785 err = -errno;
786 DBG("could not stat '%s': %m\n", path);
787 return err;
788 }
789
790 if (!S_ISDIR(st.st_mode)) {
791 cfg_files_insert_sorted(p_files, p_n_files, path, NULL);
792 return 0;
793 }
794
795 d = opendir(path);
796 if (d == NULL) {
797 ERR("files list %s: %m\n", path);
798 return -EINVAL;
799 }
800
801 for (dent = readdir(d); dent != NULL; dent = readdir(d)) {
802 if (cfg_files_filter_out(d, path, dent->d_name))
803 continue;
804
805 cfg_files_insert_sorted(p_files, p_n_files, path, dent->d_name);
806 }
807
808 closedir(d);
809 DBG("parsed configuration files from %s\n", path);
810 return err;
811 }
812
813 static int cfg_load(struct cfg *cfg, const char * const *cfg_paths)
814 {
815 size_t i, n_files = 0;
816 struct cfg_file **files = NULL;
817
818 if (cfg_paths == NULL)
819 cfg_paths = default_cfg_paths;
820
821 for (i = 0; cfg_paths[i] != NULL; i++)
822 cfg_files_list(&files, &n_files, cfg_paths[i]);
823
824 for (i = 0; i < n_files; i++) {
825 struct cfg_file *f = files[i];
826 cfg_file_parse(cfg, f->path);
827 cfg_file_free(f);
828 }
829 free(files);
830
831 /* For backward compatibility add "updates" to the head of the search
832 * list here. But only if there was no "search" option specified.
833 */
834 if (cfg->searches == NULL)
835 cfg_search_add(cfg, "updates");
836
837 return 0;
838 }
839
840 static void cfg_free(struct cfg *cfg)
841 {
842 while (cfg->overrides) {
843 struct cfg_override *tmp = cfg->overrides;
844 cfg->overrides = cfg->overrides->next;
845 cfg_override_free(tmp);
846 }
847
848 while (cfg->searches) {
849 struct cfg_search *tmp = cfg->searches;
850 cfg->searches = cfg->searches->next;
851 cfg_search_free(tmp);
852 }
853
854 while (cfg->externals) {
855 struct cfg_external *tmp = cfg->externals;
856 cfg->externals = cfg->externals->next;
857 cfg_external_free(tmp);
858 }
859 }
860
861
862 /* depmod calculations ***********************************************/
863 struct vertex;
864 struct mod {
865 struct kmod_module *kmod;
866 char *path;
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 */
873 size_t modnamesz;
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 */
880 char modname[];
881 };
882
883 struct symbol {
884 struct mod *owner;
885 uint64_t crc;
886 char name[];
887 };
888
889 struct depmod {
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;
896 };
897
898 static void mod_free(struct mod *mod)
899 {
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);
906 free(mod->path);
907 free(mod);
908 }
909
910 static int mod_add_dependency(struct mod *mod, struct symbol *sym)
911 {
912 int err;
913
914 DBG("%s depends on %s %s\n", mod->path, sym->name,
915 sym->owner != NULL ? sym->owner->path : "(unknown)");
916
917 if (sym->owner == NULL)
918 return 0;
919
920 err = array_append_unique(&mod->deps, sym->owner);
921 if (err == -EEXIST)
922 return 0;
923 if (err < 0)
924 return err;
925
926 sym->owner->users++;
927 SHOW("%s needs \"%s\": %s\n", mod->path, sym->name, sym->owner->path);
928 return 0;
929 }
930
931 static void symbol_free(struct symbol *sym)
932 {
933 DBG("free %p sym=%s, owner=%p %s\n", sym, sym->name, sym->owner,
934 sym->owner != NULL ? sym->owner->path : "");
935 free(sym);
936 }
937
938 static int depmod_init(struct depmod *depmod, struct cfg *cfg,
939 struct kmod_ctx *ctx)
940 {
941 int err = 0;
942
943 depmod->cfg = cfg;
944 depmod->ctx = ctx;
945
946 array_init(&depmod->modules, 128);
947
948 depmod->modules_by_uncrelpath = hash_new(512, NULL);
949 if (depmod->modules_by_uncrelpath == NULL) {
950 err = -errno;
951 goto modules_by_uncrelpath_failed;
952 }
953
954 depmod->modules_by_name = hash_new(512, NULL);
955 if (depmod->modules_by_name == NULL) {
956 err = -errno;
957 goto modules_by_name_failed;
958 }
959
960 depmod->symbols = hash_new(2048, (void (*)(void *))symbol_free);
961 if (depmod->symbols == NULL) {
962 err = -errno;
963 goto symbols_failed;
964 }
965
966 return 0;
967
968 symbols_failed:
969 hash_free(depmod->modules_by_name);
970 modules_by_name_failed:
971 hash_free(depmod->modules_by_uncrelpath);
972 modules_by_uncrelpath_failed:
973 return err;
974 }
975
976 static void depmod_shutdown(struct depmod *depmod)
977 {
978 size_t i;
979
980 hash_free(depmod->symbols);
981
982 hash_free(depmod->modules_by_uncrelpath);
983
984 hash_free(depmod->modules_by_name);
985
986 for (i = 0; i < depmod->modules.count; i++)
987 mod_free(depmod->modules.array[i]);
988 array_free_array(&depmod->modules);
989
990 kmod_unref(depmod->ctx);
991 }
992
993 static int depmod_module_add(struct depmod *depmod, struct kmod_module *kmod)
994 {
995 const struct cfg *cfg = depmod->cfg;
996 const char *modname, *lastslash;
997 size_t modnamesz;
998 struct mod *mod;
999 int err;
1000
1001 modname = kmod_module_get_name(kmod);
1002 modnamesz = strlen(modname) + 1;
1003
1004 mod = calloc(1, sizeof(struct mod) + modnamesz);
1005 if (mod == NULL)
1006 return -ENOMEM;
1007 mod->kmod = kmod;
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;
1012
1013 array_init(&mod->deps, 4);
1014
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;
1021 else
1022 mod->relpath = NULL;
1023
1024 err = hash_add_unique(depmod->modules_by_name, mod->modname, mod);
1025 if (err < 0) {
1026 ERR("hash_add_unique %s: %s\n", mod->modname, strerror(-err));
1027 goto fail;
1028 }
1029
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);
1037 if (err < 0) {
1038 ERR("hash_add_unique %s: %s\n",
1039 mod->uncrelpath, strerror(-err));
1040 hash_del(depmod->modules_by_name, mod->modname);
1041 goto fail;
1042 }
1043 }
1044
1045 DBG("add %p kmod=%p, path=%s\n", mod, kmod, mod->path);
1046
1047 return 0;
1048
1049 fail:
1050 free(mod->uncrelpath);
1051 free(mod);
1052 return err;
1053 }
1054
1055 static int depmod_module_del(struct depmod *depmod, struct mod *mod)
1056 {
1057 DBG("del %p kmod=%p, path=%s\n", mod, mod->kmod, mod->path);
1058
1059 if (mod->uncrelpath != NULL)
1060 hash_del(depmod->modules_by_uncrelpath, mod->uncrelpath);
1061
1062 hash_del(depmod->modules_by_name, mod->modname);
1063
1064 mod_free(mod);
1065 return 0;
1066 }
1067
1068 static const char *search_to_string(const struct cfg_search *s)
1069 {
1070 switch(s->type) {
1071 case SEARCH_EXTERNAL:
1072 return "external";
1073 case SEARCH_BUILTIN:
1074 return "built-in";
1075 default:
1076 return s->path;
1077 }
1078 }
1079
1080 static bool depmod_is_path_starts_with(const char *path,
1081 size_t pathlen,
1082 const char *prefix,
1083 size_t prefix_len)
1084 {
1085 if (pathlen <= prefix_len)
1086 return false;
1087 if (path[prefix_len] != '/')
1088 return false;
1089 if (memcmp(path, prefix, prefix_len) != 0)
1090 return false;
1091
1092 return true;
1093 }
1094
1095 /* returns if existing module @mod is higher priority than newpath.
1096 * note this is the inverse of module-init-tools is_higher_priority()
1097 */
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)
1099 {
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;
1104
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
1107 * the latter */
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;
1116
1117 DBG("comparing priorities of %s and %s\n",
1118 oldpath, newpath);
1119
1120 if (strncmp(newpath, cfg->dirname, cfg->dirnamelen) == 0) {
1121 relnewpath = newpath + cfg->dirnamelen + 1;
1122 relnewlen = newlen - (cfg->dirnamelen + 1);
1123 }
1124 if (strncmp(oldpath, cfg->dirname, cfg->dirnamelen) == 0) {
1125 reloldpath = oldpath + cfg->dirnamelen + 1;
1126 reloldlen = oldlen - (cfg->dirnamelen + 1);
1127 }
1128
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)
1133 return 0;
1134 if (reloldlen == ov->len &&
1135 memcmp(ov->path, reloldpath, reloldlen) == 0)
1136 return 1;
1137 }
1138
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)
1142 bprio = i;
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,
1146 newlen,
1147 ext->path,
1148 ext->len))
1149 newprio = i;
1150 if (depmod_is_path_starts_with(oldpath,
1151 oldlen,
1152 ext->path,
1153 ext->len))
1154 oldprio = i;
1155 }
1156 } else if (relnewlen > se->len && relnewpath[se->len] == '/' &&
1157 memcmp(se->path, relnewpath, se->len) == 0)
1158 newprio = i;
1159 else if (reloldlen > se->len && reloldpath[se->len] == '/' &&
1160 memcmp(se->path, reloldpath, se->len) == 0)
1161 oldprio = i;
1162 }
1163
1164 if (newprio < 0)
1165 newprio = bprio;
1166 if (oldprio < 0)
1167 oldprio = bprio;
1168
1169 DBG("priorities: built-in: %d, old: %d, new: %d\n",
1170 bprio, oldprio, newprio);
1171
1172 return newprio <= oldprio;
1173 }
1174
1175 static int depmod_modules_search_file(struct depmod *depmod, size_t baselen, size_t namelen, const char *path)
1176 {
1177 struct kmod_module *kmod;
1178 struct mod *mod;
1179 const char *relpath;
1180 char modname[PATH_MAX];
1181 size_t modnamelen;
1182 int err;
1183
1184 if (!path_ends_with_kmod_ext(path + baselen, namelen))
1185 return 0;
1186
1187 if (path_to_modname(path, modname, &modnamelen) == NULL) {
1188 ERR("could not get modname from path %s\n", path);
1189 return -EINVAL;
1190 }
1191
1192 relpath = path + depmod->cfg->dirnamelen + 1;
1193 DBG("try %s (%s)\n", relpath, modname);
1194
1195 mod = hash_find(depmod->modules_by_name, modname);
1196 if (mod == NULL)
1197 goto add;
1198
1199 if (depmod_module_is_higher_priority(depmod, mod, baselen,
1200 namelen, modnamelen, path)) {
1201 DBG("Ignored lower priority: %s, higher: %s\n",
1202 path, mod->path);
1203 return 0;
1204 }
1205
1206 DBG("Replace lower priority %s with new module %s\n",
1207 mod->relpath, relpath);
1208 err = depmod_module_del(depmod, mod);
1209 if (err < 0) {
1210 ERR("could not del module %s: %s\n", mod->path, strerror(-err));
1211 return err;
1212 }
1213
1214 add:
1215 err = kmod_module_new_from_path(depmod->ctx, path, &kmod);
1216 if (err < 0) {
1217 ERR("could not create module %s: %s\n", path, strerror(-err));
1218 return err;
1219 }
1220
1221 err = depmod_module_add(depmod, kmod);
1222 if (err < 0) {
1223 ERR("could not add module %s: %s\n",
1224 path, strerror(-err));
1225 kmod_module_unref(kmod);
1226 return err;
1227 }
1228 return 0;
1229 }
1230
1231 static int depmod_modules_search_dir(struct depmod *depmod, DIR *d, size_t baselen, struct scratchbuf *s_path)
1232 {
1233 struct dirent *de;
1234 int err = 0, dfd = dirfd(d);
1235 char *path;
1236
1237 while ((de = readdir(d)) != NULL) {
1238 const char *name = de->d_name;
1239 size_t namelen;
1240 uint8_t is_dir;
1241
1242 if (name[0] == '.' && (name[1] == '\0' ||
1243 (name[1] == '.' && name[2] == '\0')))
1244 continue;
1245 if (streq(name, "build") || streq(name, "source"))
1246 continue;
1247 namelen = strlen(name);
1248 if (scratchbuf_alloc(s_path, baselen + namelen + 2) < 0) {
1249 err = -ENOMEM;
1250 ERR("No memory\n");
1251 continue;
1252 }
1253
1254 path = scratchbuf_str(s_path);
1255 memcpy(path + baselen, name, namelen + 1);
1256
1257 if (de->d_type == DT_REG)
1258 is_dir = 0;
1259 else if (de->d_type == DT_DIR)
1260 is_dir = 1;
1261 else {
1262 struct stat st;
1263 if (fstatat(dfd, name, &st, 0) < 0) {
1264 ERR("fstatat(%d, %s): %m\n", dfd, name);
1265 continue;
1266 } else if (S_ISREG(st.st_mode))
1267 is_dir = 0;
1268 else if (S_ISDIR(st.st_mode))
1269 is_dir = 1;
1270 else {
1271 ERR("unsupported file type %s: %o\n",
1272 path, st.st_mode & S_IFMT);
1273 continue;
1274 }
1275 }
1276
1277 if (is_dir) {
1278 int fd;
1279 DIR *subdir;
1280 fd = openat(dfd, name, O_RDONLY);
1281 if (fd < 0) {
1282 ERR("openat(%d, %s, O_RDONLY): %m\n",
1283 dfd, name);
1284 continue;
1285 }
1286 subdir = fdopendir(fd);
1287 if (subdir == NULL) {
1288 ERR("fdopendir(%d): %m\n", fd);
1289 close(fd);
1290 continue;
1291 }
1292 path[baselen + namelen] = '/';
1293 path[baselen + namelen + 1] = '\0';
1294 err = depmod_modules_search_dir(depmod, subdir,
1295 baselen + namelen + 1,
1296 s_path);
1297 closedir(subdir);
1298 } else {
1299 err = depmod_modules_search_file(depmod, baselen,
1300 namelen, path);
1301 }
1302
1303 if (err < 0) {
1304 path[baselen + namelen] = '\0';
1305 ERR("failed %s: %s\n", path, strerror(-err));
1306 err = 0; /* ignore errors */
1307 }
1308 }
1309 return err;
1310 }
1311
1312 static int depmod_modules_search_path(struct depmod *depmod,
1313 const char *path)
1314 {
1315 char buf[256];
1316 _cleanup_(scratchbuf_release) struct scratchbuf s_path_buf =
1317 SCRATCHBUF_INITIALIZER(buf);
1318 char *path_buf;
1319 DIR *d;
1320 size_t baselen;
1321 int err;
1322
1323 d = opendir(path);
1324 if (d == NULL) {
1325 err = -errno;
1326 ERR("could not open directory %s: %m\n", path);
1327 return err;
1328 }
1329
1330 baselen = strlen(path);
1331
1332 if (scratchbuf_alloc(&s_path_buf, baselen + 2) < 0) {
1333 err = -ENOMEM;
1334 goto out;
1335 }
1336 path_buf = scratchbuf_str(&s_path_buf);
1337
1338 memcpy(path_buf, path, baselen);
1339 path_buf[baselen] = '/';
1340 baselen++;
1341 path_buf[baselen] = '\0';
1342
1343 err = depmod_modules_search_dir(depmod, d, baselen, &s_path_buf);
1344 out:
1345 closedir(d);
1346 return err;
1347 }
1348
1349 static int depmod_modules_search(struct depmod *depmod)
1350 {
1351 int err;
1352 struct cfg_external *ext;
1353
1354 err = depmod_modules_search_path(depmod, depmod->cfg->dirname);
1355 if (err < 0)
1356 return err;
1357
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 */
1362 continue;
1363 }
1364
1365 return 0;
1366 }
1367
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;
1372 }
1373
1374 static int depmod_modules_build_array(struct depmod *depmod)
1375 {
1376 struct hash_iter module_iter;
1377 const void *v;
1378 int err;
1379
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);
1385 if (err < 0)
1386 return err;
1387 }
1388
1389 return 0;
1390 }
1391
1392 static void depmod_modules_sort(struct depmod *depmod)
1393 {
1394 char order_file[PATH_MAX], line[PATH_MAX];
1395 FILE *fp;
1396 unsigned idx = 0, total = 0;
1397
1398 snprintf(order_file, sizeof(order_file), "%s/modules.order",
1399 depmod->cfg->dirname);
1400 fp = fopen(order_file, "r");
1401 if (fp == NULL) {
1402 WRN("could not open %s: %m\n", order_file);
1403 return;
1404 }
1405
1406 while (fgets(line, sizeof(line), fp) != NULL) {
1407 size_t len = strlen(line);
1408 idx++;
1409 if (len == 0)
1410 continue;
1411 if (line[len - 1] != '\n') {
1412 ERR("%s:%u corrupted line misses '\\n'\n",
1413 order_file, idx);
1414 goto corrupted;
1415 }
1416 }
1417 total = idx + 1;
1418 idx = 0;
1419 fseek(fp, 0, SEEK_SET);
1420 while (fgets(line, sizeof(line), fp) != NULL) {
1421 size_t len = strlen(line);
1422 struct mod *mod;
1423
1424 idx++;
1425 if (len == 0)
1426 continue;
1427 line[len - 1] = '\0';
1428
1429 mod = hash_find(depmod->modules_by_uncrelpath, line);
1430 if (mod == NULL)
1431 continue;
1432 mod->sort_idx = idx - total;
1433 }
1434
1435 array_sort(&depmod->modules, mod_cmp);
1436 for (idx = 0; idx < depmod->modules.count; idx++) {
1437 struct mod *m = depmod->modules.array[idx];
1438 m->idx = idx;
1439 }
1440
1441 corrupted:
1442 fclose(fp);
1443 }
1444
1445 static int depmod_symbol_add(struct depmod *depmod, const char *name,
1446 bool prefix_skipped, uint64_t crc,
1447 const struct mod *owner)
1448 {
1449 size_t namelen;
1450 int err;
1451 struct symbol *sym;
1452
1453 if (!prefix_skipped && (name[0] == depmod->cfg->sym_prefix))
1454 name++;
1455
1456 namelen = strlen(name) + 1;
1457 sym = malloc(sizeof(struct symbol) + namelen);
1458 if (sym == NULL)
1459 return -ENOMEM;
1460
1461 sym->owner = (struct mod *)owner;
1462 sym->crc = crc;
1463 memcpy(sym->name, name, namelen);
1464
1465 err = hash_add(depmod->symbols, sym->name, sym);
1466 if (err < 0) {
1467 free(sym);
1468 return err;
1469 }
1470
1471 DBG("add %p sym=%s, owner=%p %s\n", sym, sym->name, owner,
1472 owner != NULL ? owner->path : "");
1473
1474 return 0;
1475 }
1476
1477 static struct symbol *depmod_symbol_find(const struct depmod *depmod,
1478 const char *name)
1479 {
1480 if (name[0] == '.') /* PPC64 needs this: .foo == foo */
1481 name++;
1482 if (name[0] == depmod->cfg->sym_prefix)
1483 name++;
1484 return hash_find(depmod->symbols, name);
1485 }
1486
1487 static int depmod_load_modules(struct depmod *depmod)
1488 {
1489 struct mod **itr, **itr_end;
1490
1491 DBG("load symbols (%zd modules)\n", depmod->modules.count);
1492
1493 itr = (struct mod **)depmod->modules.array;
1494 itr_end = itr + depmod->modules.count;
1495 for (; itr < itr_end; itr++) {
1496 struct mod *mod = *itr;
1497 struct kmod_list *l, *list = NULL;
1498 int err = kmod_module_get_symbols(mod->kmod, &list);
1499 if (err < 0) {
1500 if (err == -ENOENT)
1501 DBG("ignoring %s: no symbols\n", mod->path);
1502 else
1503 ERR("failed to load symbols from %s: %s\n",
1504 mod->path, strerror(-err));
1505 goto load_info;
1506 }
1507 kmod_list_foreach(l, list) {
1508 const char *name = kmod_module_symbol_get_symbol(l);
1509 uint64_t crc = kmod_module_symbol_get_crc(l);
1510 depmod_symbol_add(depmod, name, false, crc, mod);
1511 }
1512 kmod_module_symbols_free_list(list);
1513
1514 load_info:
1515 kmod_module_get_info(mod->kmod, &mod->info_list);
1516 kmod_module_get_dependency_symbols(mod->kmod,
1517 &mod->dep_sym_list);
1518 kmod_module_unref(mod->kmod);
1519 mod->kmod = NULL;
1520 }
1521
1522 DBG("loaded symbols (%zd modules, %u symbols)\n",
1523 depmod->modules.count, hash_get_count(depmod->symbols));
1524
1525 return 0;
1526 }
1527
1528 static int depmod_load_module_dependencies(struct depmod *depmod, struct mod *mod)
1529 {
1530 const struct cfg *cfg = depmod->cfg;
1531 struct kmod_list *l;
1532
1533 DBG("do dependencies of %s\n", mod->path);
1534 kmod_list_foreach(l, mod->dep_sym_list) {
1535 const char *name = kmod_module_dependency_symbol_get_symbol(l);
1536 uint64_t crc = kmod_module_dependency_symbol_get_crc(l);
1537 int bindtype = kmod_module_dependency_symbol_get_bind(l);
1538 struct symbol *sym = depmod_symbol_find(depmod, name);
1539 uint8_t is_weak = bindtype == KMOD_SYMBOL_WEAK;
1540
1541 if (sym == NULL) {
1542 DBG("%s needs (%c) unknown symbol %s\n",
1543 mod->path, bindtype, name);
1544 if (cfg->print_unknown && !is_weak)
1545 WRN("%s needs unknown symbol %s\n",
1546 mod->path, name);
1547 continue;
1548 }
1549
1550 if (cfg->check_symvers && sym->crc != crc && !is_weak) {
1551 DBG("symbol %s (%#"PRIx64") module %s (%#"PRIx64")\n",
1552 sym->name, sym->crc, mod->path, crc);
1553 if (cfg->print_unknown)
1554 WRN("%s disagrees about version of symbol %s\n",
1555 mod->path, name);
1556 }
1557
1558 mod_add_dependency(mod, sym);
1559 }
1560
1561 return 0;
1562 }
1563
1564 static int depmod_load_dependencies(struct depmod *depmod)
1565 {
1566 struct mod **itr, **itr_end;
1567
1568 DBG("load dependencies (%zd modules, %u symbols)\n",
1569 depmod->modules.count, hash_get_count(depmod->symbols));
1570
1571 itr = (struct mod **)depmod->modules.array;
1572 itr_end = itr + depmod->modules.count;
1573 for (; itr < itr_end; itr++) {
1574 struct mod *mod = *itr;
1575
1576 if (mod->dep_sym_list == NULL) {
1577 DBG("ignoring %s: no dependency symbols\n", mod->path);
1578 continue;
1579 }
1580
1581 depmod_load_module_dependencies(depmod, mod);
1582 }
1583
1584 DBG("loaded dependencies (%zd modules, %u symbols)\n",
1585 depmod->modules.count, hash_get_count(depmod->symbols));
1586
1587 return 0;
1588 }
1589
1590 static int dep_cmp(const void *pa, const void *pb)
1591 {
1592 const struct mod *a = *(const struct mod **)pa;
1593 const struct mod *b = *(const struct mod **)pb;
1594 return a->dep_sort_idx - b->dep_sort_idx;
1595 }
1596
1597 static void depmod_sort_dependencies(struct depmod *depmod)
1598 {
1599 struct mod **itr, **itr_end;
1600 itr = (struct mod **)depmod->modules.array;
1601 itr_end = itr + depmod->modules.count;
1602 for (; itr < itr_end; itr++) {
1603 struct mod *m = *itr;
1604 if (m->deps.count > 1)
1605 array_sort(&m->deps, dep_cmp);
1606 }
1607 }
1608
1609 struct vertex {
1610 struct vertex *parent;
1611 struct mod *mod;
1612 };
1613
1614 static struct vertex *vertex_new(struct mod *mod, struct vertex *parent)
1615 {
1616 struct vertex *v;
1617
1618 v = malloc(sizeof(*v));
1619 if (v == NULL)
1620 return NULL;
1621
1622 v->parent = parent;
1623 v->mod = mod;
1624 return v;
1625 }
1626
1627 static void depmod_list_remove_data(struct kmod_list **list, void *data)
1628 {
1629 struct kmod_list *l;
1630
1631 l = kmod_list_remove_data(*list, data);
1632 *list = l;
1633 }
1634
1635 static int depmod_report_one_cycle(struct depmod *depmod,
1636 struct vertex *vertex,
1637 struct kmod_list **roots,
1638 struct hash *loop_set)
1639 {
1640 const char sep[] = " -> ";
1641 size_t sz;
1642 char *buf;
1643 struct array reverse;
1644 int i;
1645 int n;
1646 struct vertex *v;
1647 int rc;
1648
1649 array_init(&reverse, 3);
1650
1651 sz = 0;
1652 for (v = vertex->parent, n = 0;
1653 v != NULL;
1654 v = v->parent, n++) {
1655
1656 sz += v->mod->modnamesz - 1;
1657 array_append(&reverse, v);
1658 rc = hash_add(loop_set, v->mod->modname, NULL);
1659 if (rc != 0)
1660 return rc;
1661 /* the hash will be freed where created */
1662 }
1663 sz += vertex->mod->modnamesz - 1;
1664
1665 buf = malloc(sz + n * strlen(sep) + 1);
1666
1667 sz = 0;
1668 for (i = reverse.count - 1; i >= 0; i--) {
1669 size_t len;
1670
1671 v = reverse.array[i];
1672
1673 len = v->mod->modnamesz - 1;
1674 memcpy(buf + sz, v->mod->modname, len);
1675 sz += len;
1676 strcpy(buf + sz, sep);
1677 sz += strlen(sep);
1678
1679 depmod_list_remove_data(roots, v->mod);
1680 }
1681 strcpy(buf + sz, vertex->mod->modname);
1682 ERR("Cycle detected: %s\n", buf);
1683
1684 free(buf);
1685 array_free_array(&reverse);
1686
1687 return 0;
1688 }
1689
1690 static int depmod_report_cycles_from_root(struct depmod *depmod,
1691 struct mod *root_mod,
1692 struct kmod_list **roots,
1693 void **stack,
1694 size_t stack_size,
1695 struct hash *loop_set)
1696 {
1697 struct kmod_list *free_list = NULL; /* struct vertex */
1698 struct kmod_list *l;
1699 struct vertex *root;
1700 struct vertex *vertex;
1701 struct vertex *v;
1702 struct mod *m;
1703 struct mod **itr, **itr_end;
1704 size_t is;
1705 int ret = -ENOMEM;
1706
1707 root = vertex_new(root_mod, NULL);
1708 if (root == NULL) {
1709 ERR("No memory to report cycles\n");
1710 goto out;
1711 }
1712
1713 l = kmod_list_append(free_list, root);
1714 if (l == NULL) {
1715 ERR("No memory to report cycles\n");
1716 goto out;
1717 }
1718 free_list = l;
1719
1720 is = 0;
1721 stack[is++] = (void *)root;
1722
1723 while (is > 0) {
1724 vertex = stack[--is];
1725 m = vertex->mod;
1726 /*
1727 * because of the topological sort we can start only
1728 * from part of a loop or from a branch after a loop
1729 */
1730 if (m->visited && m == root->mod) {
1731 int rc;
1732 rc = depmod_report_one_cycle(depmod, vertex,
1733 roots, loop_set);
1734 if (rc != 0) {
1735 ret = rc;
1736 goto out;
1737 }
1738 continue;
1739 }
1740
1741 m->visited = true;
1742 if (m->deps.count == 0) {
1743 /*
1744 * boundary condition: if there is more than one
1745 * single node branch (not a loop), it is
1746 * recognized as a loop by the code above:
1747 * m->visited because more then one,
1748 * m == root->mod since it is a single node.
1749 * So, prevent deeping into the branch second
1750 * time.
1751 */
1752 depmod_list_remove_data(roots, m);
1753
1754 continue;
1755 }
1756
1757 itr = (struct mod **) m->deps.array;
1758 itr_end = itr + m->deps.count;
1759 for (; itr < itr_end; itr++) {
1760 struct mod *dep = *itr;
1761 v = vertex_new(dep, vertex);
1762 if (v == NULL) {
1763 ERR("No memory to report cycles\n");
1764 goto out;
1765 }
1766 assert(is < stack_size);
1767 stack[is++] = v;
1768
1769 l = kmod_list_append(free_list, v);
1770 if (l == NULL) {
1771 ERR("No memory to report cycles\n");
1772 goto out;
1773 }
1774 free_list = l;
1775
1776 }
1777 }
1778 ret = 0;
1779
1780 out:
1781 while (free_list) {
1782 v = free_list->data;
1783 l = kmod_list_remove(free_list);
1784 free_list = l;
1785 free(v);
1786 }
1787
1788 return ret;
1789 }
1790
1791 static void depmod_report_cycles(struct depmod *depmod, uint16_t n_mods,
1792 uint16_t *users)
1793 {
1794 int num_cyclic = 0;
1795 struct kmod_list *roots = NULL; /* struct mod */
1796 struct kmod_list *l;
1797 size_t n_r; /* local n_roots */
1798 int i;
1799 int err;
1800 _cleanup_free_ void **stack = NULL;
1801 struct mod *m;
1802 struct mod *root;
1803 struct hash *loop_set;
1804
1805 for (i = 0, n_r = 0; i < n_mods; i++) {
1806 if (users[i] <= 0)
1807 continue;
1808 m = depmod->modules.array[i];
1809 l = kmod_list_append(roots, m);
1810 if (l == NULL) {
1811 ERR("No memory to report cycles\n");
1812 goto out_list;
1813 }
1814 roots = l;
1815 n_r++;
1816 }
1817
1818 stack = malloc(n_r * sizeof(void *));
1819 if (stack == NULL) {
1820 ERR("No memory to report cycles\n");
1821 goto out_list;
1822 }
1823
1824 loop_set = hash_new(16, NULL);
1825 if (loop_set == NULL) {
1826 ERR("No memory to report cycles\n");
1827 goto out_list;
1828 }
1829
1830 while (roots != NULL) {
1831 root = roots->data;
1832 l = kmod_list_remove(roots);
1833 roots = l;
1834 err = depmod_report_cycles_from_root(depmod,
1835 root,
1836 &roots,
1837 stack, n_r, loop_set);
1838 if (err < 0)
1839 goto out_hash;
1840 }
1841
1842 num_cyclic = hash_get_count(loop_set);
1843 ERR("Found %d modules in dependency cycles!\n", num_cyclic);
1844
1845 out_hash:
1846 hash_free(loop_set);
1847 out_list:
1848 while (roots != NULL) {
1849 /* no need to free data, come from outside */
1850 roots = kmod_list_remove(roots);
1851 }
1852 }
1853
1854 static int depmod_calculate_dependencies(struct depmod *depmod)
1855 {
1856 const struct mod **itrm;
1857 uint16_t *users, *roots, *sorted;
1858 uint16_t i, n_roots = 0, n_sorted = 0, n_mods = depmod->modules.count;
1859 int ret = 0;
1860
1861 users = malloc(sizeof(uint16_t) * n_mods * 3);
1862 if (users == NULL)
1863 return -ENOMEM;
1864 roots = users + n_mods;
1865 sorted = roots + n_mods;
1866
1867 DBG("calculate dependencies and ordering (%hu modules)\n", n_mods);
1868
1869 assert(depmod->modules.count < UINT16_MAX);
1870
1871 /* populate modules users (how many modules uses it) */
1872 itrm = (const struct mod **)depmod->modules.array;
1873 for (i = 0; i < n_mods; i++, itrm++) {
1874 const struct mod *m = *itrm;
1875 users[i] = m->users;
1876 if (users[i] == 0) {
1877 roots[n_roots] = i;
1878 n_roots++;
1879 }
1880 }
1881
1882 /* topological sort (outputs modules without users first) */
1883 while (n_roots > 0) {
1884 const struct mod **itr_dst, **itr_dst_end;
1885 struct mod *src;
1886 uint16_t src_idx = roots[--n_roots];
1887
1888 src = depmod->modules.array[src_idx];
1889 src->dep_sort_idx = n_sorted;
1890 sorted[n_sorted] = src_idx;
1891 n_sorted++;
1892
1893 itr_dst = (const struct mod **)src->deps.array;
1894 itr_dst_end = itr_dst + src->deps.count;
1895 for (; itr_dst < itr_dst_end; itr_dst++) {
1896 const struct mod *dst = *itr_dst;
1897 uint16_t dst_idx = dst->idx;
1898 assert(users[dst_idx] > 0);
1899 users[dst_idx]--;
1900 if (users[dst_idx] == 0) {
1901 roots[n_roots] = dst_idx;
1902 n_roots++;
1903 }
1904 }
1905 }
1906
1907 if (n_sorted < n_mods) {
1908 depmod_report_cycles(depmod, n_mods, users);
1909 ret = -EINVAL;
1910 goto exit;
1911 }
1912
1913 depmod_sort_dependencies(depmod);
1914
1915 DBG("calculated dependencies and ordering (%hu modules)\n", n_mods);
1916
1917 exit:
1918 free(users);
1919 return ret;
1920 }
1921
1922 static int depmod_load(struct depmod *depmod)
1923 {
1924 int err;
1925
1926 err = depmod_load_modules(depmod);
1927 if (err < 0)
1928 return err;
1929
1930 err = depmod_load_dependencies(depmod);
1931 if (err < 0)
1932 return err;
1933
1934 err = depmod_calculate_dependencies(depmod);
1935 if (err < 0)
1936 return err;
1937
1938 return 0;
1939 }
1940
1941 static size_t mod_count_all_dependencies(const struct mod *mod)
1942 {
1943 size_t i, count = 0;
1944 for (i = 0; i < mod->deps.count; i++) {
1945 const struct mod *d = mod->deps.array[i];
1946 count += 1 + mod_count_all_dependencies(d);
1947 }
1948 return count;
1949 }
1950
1951 static int mod_fill_all_unique_dependencies(const struct mod *mod, const struct mod **deps, size_t n_deps, size_t *last)
1952 {
1953 size_t i;
1954 int err = 0;
1955 for (i = 0; i < mod->deps.count; i++) {
1956 const struct mod *d = mod->deps.array[i];
1957 size_t j;
1958 uint8_t exists = 0;
1959
1960 for (j = 0; j < *last; j++) {
1961 if (deps[j] == d) {
1962 exists = 1;
1963 break;
1964 }
1965 }
1966
1967 if (exists)
1968 continue;
1969
1970 if (*last >= n_deps)
1971 return -ENOSPC;
1972 deps[*last] = d;
1973 (*last)++;
1974 err = mod_fill_all_unique_dependencies(d, deps, n_deps, last);
1975 if (err < 0)
1976 break;
1977 }
1978 return err;
1979 }
1980
1981 static const struct mod **mod_get_all_sorted_dependencies(const struct mod *mod, size_t *n_deps)
1982 {
1983 const struct mod **deps;
1984 size_t last = 0;
1985
1986 *n_deps = mod_count_all_dependencies(mod);
1987 if (*n_deps == 0)
1988 return NULL;
1989
1990 deps = malloc(sizeof(struct mod *) * (*n_deps));
1991 if (deps == NULL)
1992 return NULL;
1993
1994 if (mod_fill_all_unique_dependencies(mod, deps, *n_deps, &last) < 0) {
1995 free(deps);
1996 return NULL;
1997 }
1998
1999 qsort(deps, last, sizeof(struct mod *), dep_cmp);
2000 *n_deps = last;
2001 return deps;
2002 }
2003
2004 static inline const char *mod_get_compressed_path(const struct mod *mod)
2005 {
2006 if (mod->relpath != NULL)
2007 return mod->relpath;
2008 return mod->path;
2009 }
2010
2011 static int output_deps(struct depmod *depmod, FILE *out)
2012 {
2013 size_t i;
2014
2015 for (i = 0; i < depmod->modules.count; i++) {
2016 const struct mod **deps, *mod = depmod->modules.array[i];
2017 const char *p = mod_get_compressed_path(mod);
2018 size_t j, n_deps;
2019
2020 fprintf(out, "%s:", p);
2021
2022 if (mod->deps.count == 0)
2023 goto end;
2024
2025 deps = mod_get_all_sorted_dependencies(mod, &n_deps);
2026 if (deps == NULL) {
2027 ERR("could not get all sorted dependencies of %s\n", p);
2028 goto end;
2029 }
2030
2031 for (j = 0; j < n_deps; j++) {
2032 const struct mod *d = deps[j];
2033 fprintf(out, " %s", mod_get_compressed_path(d));
2034 }
2035 free(deps);
2036 end:
2037 putc('\n', out);
2038 }
2039
2040 return 0;
2041 }
2042
2043 static int output_deps_bin(struct depmod *depmod, FILE *out)
2044 {
2045 struct index_node *idx;
2046 size_t i;
2047
2048 if (out == stdout)
2049 return 0;
2050
2051 idx = index_create();
2052 if (idx == NULL)
2053 return -ENOMEM;
2054
2055 for (i = 0; i < depmod->modules.count; i++) {
2056 const struct mod **deps, *mod = depmod->modules.array[i];
2057 const char *p = mod_get_compressed_path(mod);
2058 char *line;
2059 size_t j, n_deps, linepos, linelen, slen;
2060 int duplicate;
2061
2062 deps = mod_get_all_sorted_dependencies(mod, &n_deps);
2063 if (deps == NULL && n_deps > 0) {
2064 ERR("could not get all sorted dependencies of %s\n", p);
2065 continue;
2066 }
2067
2068 linelen = strlen(p) + 1;
2069 for (j = 0; j < n_deps; j++) {
2070 const struct mod *d = deps[j];
2071 linelen += 1 + strlen(mod_get_compressed_path(d));
2072 }
2073
2074 line = malloc(linelen + 1);
2075 if (line == NULL) {
2076 free(deps);
2077 ERR("modules.deps.bin: out of memory\n");
2078 continue;
2079 }
2080
2081 linepos = 0;
2082 slen = strlen(p);
2083 memcpy(line + linepos, p, slen);
2084 linepos += slen;
2085 line[linepos] = ':';
2086 linepos++;
2087
2088 for (j = 0; j < n_deps; j++) {
2089 const struct mod *d = deps[j];
2090 const char *dp;
2091
2092 line[linepos] = ' ';
2093 linepos++;
2094
2095 dp = mod_get_compressed_path(d);
2096 slen = strlen(dp);
2097 memcpy(line + linepos, dp, slen);
2098 linepos += slen;
2099 }
2100 line[linepos] = '\0';
2101
2102 duplicate = index_insert(idx, mod->modname, line, mod->idx);
2103 if (duplicate && depmod->cfg->warn_dups)
2104 WRN("duplicate module deps:\n%s\n", line);
2105 free(line);
2106 free(deps);
2107 }
2108
2109 index_write(idx, out);
2110 index_destroy(idx);
2111
2112 return 0;
2113 }
2114
2115 static int output_aliases(struct depmod *depmod, FILE *out)
2116 {
2117 size_t i;
2118
2119 fputs("# Aliases extracted from modules themselves.\n", out);
2120
2121 for (i = 0; i < depmod->modules.count; i++) {
2122 const struct mod *mod = depmod->modules.array[i];
2123 struct kmod_list *l;
2124
2125 kmod_list_foreach(l, mod->info_list) {
2126 const char *key = kmod_module_info_get_key(l);
2127 const char *value = kmod_module_info_get_value(l);
2128
2129 if (!streq(key, "alias"))
2130 continue;
2131
2132 fprintf(out, "alias %s %s\n", value, mod->modname);
2133 }
2134 }
2135
2136 return 0;
2137 }
2138
2139 static int output_aliases_bin(struct depmod *depmod, FILE *out)
2140 {
2141 struct index_node *idx;
2142 size_t i;
2143
2144 if (out == stdout)
2145 return 0;
2146
2147 idx = index_create();
2148 if (idx == NULL)
2149 return -ENOMEM;
2150
2151 for (i = 0; i < depmod->modules.count; i++) {
2152 const struct mod *mod = depmod->modules.array[i];
2153 struct kmod_list *l;
2154
2155 kmod_list_foreach(l, mod->info_list) {
2156 const char *key = kmod_module_info_get_key(l);
2157 const char *value = kmod_module_info_get_value(l);
2158 char buf[PATH_MAX];
2159 const char *alias;
2160 int duplicate;
2161
2162 if (!streq(key, "alias"))
2163 continue;
2164
2165 if (alias_normalize(value, buf, NULL) < 0) {
2166 WRN("Unmatched bracket in %s\n", value);
2167 continue;
2168 }
2169 alias = buf;
2170
2171 duplicate = index_insert(idx, alias, mod->modname,
2172 mod->idx);
2173 if (duplicate && depmod->cfg->warn_dups)
2174 WRN("duplicate module alias:\n%s %s\n",
2175 alias, mod->modname);
2176 }
2177 }
2178
2179 index_write(idx, out);
2180 index_destroy(idx);
2181
2182 return 0;
2183 }
2184
2185 static int output_softdeps(struct depmod *depmod, FILE *out)
2186 {
2187 size_t i;
2188
2189 fputs("# Soft dependencies extracted from modules themselves.\n", out);
2190
2191 for (i = 0; i < depmod->modules.count; i++) {
2192 const struct mod *mod = depmod->modules.array[i];
2193 struct kmod_list *l;
2194
2195 kmod_list_foreach(l, mod->info_list) {
2196 const char *key = kmod_module_info_get_key(l);
2197 const char *value = kmod_module_info_get_value(l);
2198
2199 if (!streq(key, "softdep"))
2200 continue;
2201
2202 fprintf(out, "softdep %s %s\n", mod->modname, value);
2203 }
2204 }
2205
2206 return 0;
2207 }
2208
2209 static int output_symbols(struct depmod *depmod, FILE *out)
2210 {
2211 struct hash_iter iter;
2212 const void *v;
2213
2214 fputs("# Aliases for symbols, used by symbol_request().\n", out);
2215
2216 hash_iter_init(depmod->symbols, &iter);
2217
2218 while (hash_iter_next(&iter, NULL, &v)) {
2219 const struct symbol *sym = v;
2220 if (sym->owner == NULL)
2221 continue;
2222
2223 fprintf(out, "alias symbol:%s %s\n",
2224 sym->name, sym->owner->modname);
2225 }
2226
2227 return 0;
2228 }
2229
2230 static int output_symbols_bin(struct depmod *depmod, FILE *out)
2231 {
2232 struct index_node *idx;
2233 char alias[1024];
2234 _cleanup_(scratchbuf_release) struct scratchbuf salias =
2235 SCRATCHBUF_INITIALIZER(alias);
2236 size_t baselen = sizeof("symbol:") - 1;
2237 struct hash_iter iter;
2238 const void *v;
2239 int ret = 0;
2240
2241 if (out == stdout)
2242 return 0;
2243
2244 idx = index_create();
2245 if (idx == NULL)
2246 return -ENOMEM;
2247
2248 memcpy(alias, "symbol:", baselen);
2249
2250 hash_iter_init(depmod->symbols, &iter);
2251
2252 while (hash_iter_next(&iter, NULL, &v)) {
2253 int duplicate;
2254 const struct symbol *sym = v;
2255 size_t len;
2256
2257 if (sym->owner == NULL)
2258 continue;
2259
2260 len = strlen(sym->name);
2261
2262 if (scratchbuf_alloc(&salias, baselen + len + 1) < 0) {
2263 ret = -ENOMEM;
2264 goto err_scratchbuf;
2265 }
2266 memcpy(scratchbuf_str(&salias) + baselen, sym->name, len + 1);
2267 duplicate = index_insert(idx, alias, sym->owner->modname,
2268 sym->owner->idx);
2269
2270 if (duplicate && depmod->cfg->warn_dups)
2271 WRN("duplicate module syms:\n%s %s\n",
2272 alias, sym->owner->modname);
2273 }
2274
2275 index_write(idx, out);
2276
2277 err_scratchbuf:
2278 index_destroy(idx);
2279
2280 if (ret < 0)
2281 ERR("output symbols: %s\n", strerror(-ret));
2282
2283 return ret;
2284 }
2285
2286 static int output_builtin_bin(struct depmod *depmod, FILE *out)
2287 {
2288 FILE *in;
2289 struct index_node *idx;
2290 char infile[PATH_MAX], line[PATH_MAX], modname[PATH_MAX];
2291
2292 if (out == stdout)
2293 return 0;
2294
2295 snprintf(infile, sizeof(infile), "%s/modules.builtin",
2296 depmod->cfg->dirname);
2297 in = fopen(infile, "r");
2298 if (in == NULL) {
2299 WRN("could not open %s: %m\n", infile);
2300 return 0;
2301 }
2302
2303 idx = index_create();
2304 if (idx == NULL) {
2305 fclose(in);
2306 return -ENOMEM;
2307 }
2308
2309 while (fgets(line, sizeof(line), in) != NULL) {
2310 if (!isalpha(line[0])) {
2311 ERR("Invalid modules.builtin line: %s\n", line);
2312 continue;
2313 }
2314
2315 path_to_modname(line, modname, NULL);
2316 index_insert(idx, modname, "", 0);
2317 }
2318
2319 index_write(idx, out);
2320 index_destroy(idx);
2321 fclose(in);
2322
2323 return 0;
2324 }
2325
2326 static int output_devname(struct depmod *depmod, FILE *out)
2327 {
2328 size_t i;
2329 bool empty = true;
2330
2331 for (i = 0; i < depmod->modules.count; i++) {
2332 const struct mod *mod = depmod->modules.array[i];
2333 struct kmod_list *l;
2334 const char *devname = NULL;
2335 char type = '\0';
2336 unsigned int major = 0, minor = 0;
2337
2338 kmod_list_foreach(l, mod->info_list) {
2339 const char *key = kmod_module_info_get_key(l);
2340 const char *value = kmod_module_info_get_value(l);
2341 unsigned int maj, min;
2342
2343 if (!streq(key, "alias"))
2344 continue;
2345
2346 if (strstartswith(value, "devname:"))
2347 devname = value + sizeof("devname:") - 1;
2348 else if (sscanf(value, "char-major-%u-%u",
2349 &maj, &min) == 2) {
2350 type = 'c';
2351 major = maj;
2352 minor = min;
2353 } else if (sscanf(value, "block-major-%u-%u",
2354 &maj, &min) == 2) {
2355 type = 'b';
2356 major = maj;
2357 minor = min;
2358 }
2359
2360 if (type != '\0' && devname != NULL)
2361 break;
2362 }
2363
2364 if (devname != NULL) {
2365 if (type != '\0') {
2366 if (empty) {
2367 fputs("# Device nodes to trigger on-demand module loading.\n",
2368 out);
2369 empty = false;
2370 }
2371 fprintf(out, "%s %s %c%u:%u\n", mod->modname,
2372 devname, type, major, minor);
2373 } else
2374 ERR("Module '%s' has devname (%s) but "
2375 "lacks major and minor information. "
2376 "Ignoring.\n", mod->modname, devname);
2377 }
2378 }
2379
2380 return 0;
2381 }
2382
2383 static int depmod_output(struct depmod *depmod, FILE *out)
2384 {
2385 static const struct depfile {
2386 const char *name;
2387 int (*cb)(struct depmod *depmod, FILE *out);
2388 } *itr, depfiles[] = {
2389 { "modules.dep", output_deps },
2390 { "modules.dep.bin", output_deps_bin },
2391 { "modules.alias", output_aliases },
2392 { "modules.alias.bin", output_aliases_bin },
2393 { "modules.softdep", output_softdeps },
2394 { "modules.symbols", output_symbols },
2395 { "modules.symbols.bin", output_symbols_bin },
2396 { "modules.builtin.bin", output_builtin_bin },
2397 { "modules.devname", output_devname },
2398 { }
2399 };
2400 const char *dname = depmod->cfg->dirname;
2401 int dfd, err = 0;
2402 struct timeval tv;
2403
2404 gettimeofday(&tv, NULL);
2405
2406 if (out != NULL)
2407 dfd = -1;
2408 else {
2409 dfd = open(dname, O_RDONLY);
2410 if (dfd < 0) {
2411 err = -errno;
2412 CRIT("could not open directory %s: %m\n", dname);
2413 return err;
2414 }
2415 }
2416
2417 for (itr = depfiles; itr->name != NULL; itr++) {
2418 FILE *fp = out;
2419 char tmp[NAME_MAX] = "";
2420 int r, ferr;
2421
2422 if (fp == NULL) {
2423 int flags = O_CREAT | O_EXCL | O_WRONLY;
2424 int mode = 0644;
2425 int fd;
2426
2427 snprintf(tmp, sizeof(tmp), "%s.%i.%li.%li", itr->name, getpid(),
2428 tv.tv_usec, tv.tv_sec);
2429 fd = openat(dfd, tmp, flags, mode);
2430 if (fd < 0) {
2431 ERR("openat(%s, %s, %o, %o): %m\n",
2432 dname, tmp, flags, mode);
2433 continue;
2434 }
2435 fp = fdopen(fd, "wb");
2436 if (fp == NULL) {
2437 ERR("fdopen(%d=%s/%s): %m\n", fd, dname, tmp);
2438 close(fd);
2439 continue;
2440 }
2441 }
2442
2443 r = itr->cb(depmod, fp);
2444 if (fp == out)
2445 continue;
2446
2447 ferr = ferror(fp) | fclose(fp);
2448
2449 if (r < 0) {
2450 if (unlinkat(dfd, tmp, 0) != 0)
2451 ERR("unlinkat(%s, %s): %m\n", dname, tmp);
2452
2453 ERR("Could not write index '%s': %s\n", itr->name,
2454 strerror(-r));
2455 err = -errno;
2456 break;
2457 }
2458
2459 if (renameat(dfd, tmp, dfd, itr->name) != 0) {
2460 err = -errno;
2461 CRIT("renameat(%s, %s, %s, %s): %m\n",
2462 dname, tmp, dname, itr->name);
2463 break;
2464 }
2465
2466 if (ferr) {
2467 err = -ENOSPC;
2468 ERR("Could not create index '%s'. Output is truncated: %s\n",
2469 itr->name, strerror(-err));
2470 break;
2471 }
2472 }
2473
2474 if (dfd >= 0)
2475 close(dfd);
2476
2477 return err;
2478 }
2479
2480 static void depmod_add_fake_syms(struct depmod *depmod)
2481 {
2482 /* __this_module is magic inserted by kernel loader. */
2483 depmod_symbol_add(depmod, "__this_module", true, 0, NULL);
2484 /* On S390, this is faked up too */
2485 depmod_symbol_add(depmod, "_GLOBAL_OFFSET_TABLE_", true, 0, NULL);
2486 /* On PowerPC64 ABIv2, .TOC. is more or less _GLOBAL_OFFSET_TABLE_ */
2487 if (!depmod_symbol_find(depmod, "TOC."))
2488 depmod_symbol_add(depmod, "TOC.", true, 0, NULL);
2489 }
2490
2491 static int depmod_load_symvers(struct depmod *depmod, const char *filename)
2492 {
2493 char line[10240];
2494 FILE *fp;
2495 unsigned int linenum = 0;
2496
2497 fp = fopen(filename, "r");
2498 if (fp == NULL) {
2499 int err = -errno;
2500 DBG("load symvers: %s: %m\n", filename);
2501 return err;
2502 }
2503 DBG("load symvers: %s\n", filename);
2504
2505 /* eg. "0xb352177e\tfind_first_bit\tvmlinux\tEXPORT_SYMBOL" */
2506 while (fgets(line, sizeof(line), fp) != NULL) {
2507 const char *ver, *sym, *where;
2508 char *verend;
2509 uint64_t crc;
2510
2511 linenum++;
2512
2513 ver = strtok(line, " \t");
2514 sym = strtok(NULL, " \t");
2515 where = strtok(NULL, " \t");
2516 if (!ver || !sym || !where)
2517 continue;
2518
2519 if (!streq(where, "vmlinux"))
2520 continue;
2521
2522 crc = strtoull(ver, &verend, 16);
2523 if (verend[0] != '\0') {
2524 ERR("%s:%u Invalid symbol version %s: %m\n",
2525 filename, linenum, ver);
2526 continue;
2527 }
2528
2529 depmod_symbol_add(depmod, sym, false, crc, NULL);
2530 }
2531 depmod_add_fake_syms(depmod);
2532
2533 DBG("loaded symvers: %s\n", filename);
2534
2535 fclose(fp);
2536 return 0;
2537 }
2538
2539 static int depmod_load_system_map(struct depmod *depmod, const char *filename)
2540 {
2541 const char ksymstr[] = "__ksymtab_";
2542 const size_t ksymstr_len = sizeof(ksymstr) - 1;
2543 char line[10240];
2544 FILE *fp;
2545 unsigned int linenum = 0;
2546
2547 fp = fopen(filename, "r");
2548 if (fp == NULL) {
2549 int err = -errno;
2550 DBG("load System.map: %s: %m\n", filename);
2551 return err;
2552 }
2553 DBG("load System.map: %s\n", filename);
2554
2555 /* eg. c0294200 R __ksymtab_devfs_alloc_devnum */
2556 while (fgets(line, sizeof(line), fp) != NULL) {
2557 char *p, *end;
2558
2559 linenum++;
2560
2561 p = strchr(line, ' ');
2562 if (p == NULL)
2563 goto invalid_syntax;
2564 p++;
2565 p = strchr(p, ' ');
2566 if (p == NULL)
2567 goto invalid_syntax;
2568 p++;
2569
2570 /* skip prefix */
2571 if (p[0] == depmod->cfg->sym_prefix)
2572 p++;
2573
2574 /* Covers gpl-only and normal symbols. */
2575 if (strncmp(p, ksymstr, ksymstr_len) != 0)
2576 continue;
2577
2578 end = strchr(p, '\n');
2579 if (end != NULL)
2580 *end = '\0';
2581
2582 depmod_symbol_add(depmod, p + ksymstr_len, true, 0, NULL);
2583 continue;
2584
2585 invalid_syntax:
2586 ERR("%s:%u: invalid line: %s\n", filename, linenum, line);
2587 }
2588 depmod_add_fake_syms(depmod);
2589
2590 DBG("loaded System.map: %s\n", filename);
2591
2592 fclose(fp);
2593 return 0;
2594 }
2595
2596
2597 static int depfile_up_to_date_dir(DIR *d, time_t mtime, size_t baselen, char *path)
2598 {
2599 struct dirent *de;
2600 int err = 1, dfd = dirfd(d);
2601
2602 while ((de = readdir(d)) != NULL) {
2603 const char *name = de->d_name;
2604 size_t namelen;
2605 struct stat st;
2606
2607 if (name[0] == '.' && (name[1] == '\0' ||
2608 (name[1] == '.' && name[2] == '\0')))
2609 continue;
2610 if (streq(name, "build") || streq(name, "source"))
2611 continue;
2612 namelen = strlen(name);
2613 if (baselen + namelen + 2 >= PATH_MAX) {
2614 path[baselen] = '\0';
2615 ERR("path is too long %s%s\n", path, name);
2616 continue;
2617 }
2618
2619 if (fstatat(dfd, name, &st, 0) < 0) {
2620 ERR("fstatat(%d, %s): %m\n", dfd, name);
2621 continue;
2622 }
2623
2624 if (S_ISDIR(st.st_mode)) {
2625 int fd;
2626 DIR *subdir;
2627 memcpy(path + baselen, name, namelen + 1);
2628 if (baselen + namelen + 2 + NAME_MAX >= PATH_MAX) {
2629 ERR("directory path is too long %s\n", path);
2630 continue;
2631 }
2632 fd = openat(dfd, name, O_RDONLY);
2633 if (fd < 0) {
2634 ERR("openat(%d, %s, O_RDONLY): %m\n",
2635 dfd, name);
2636 continue;
2637 }
2638 subdir = fdopendir(fd);
2639 if (subdir == NULL) {
2640 ERR("fdopendir(%d): %m\n", fd);
2641 close(fd);
2642 continue;
2643 }
2644 path[baselen + namelen] = '/';
2645 path[baselen + namelen + 1] = '\0';
2646 err = depfile_up_to_date_dir(subdir, mtime,
2647 baselen + namelen + 1,
2648 path);
2649 closedir(subdir);
2650 } else if (S_ISREG(st.st_mode)) {
2651 if (!path_ends_with_kmod_ext(name, namelen))
2652 continue;
2653
2654 memcpy(path + baselen, name, namelen + 1);
2655 err = st.st_mtime <= mtime;
2656 if (err == 0) {
2657 DBG("%s %"PRIu64" is newer than %"PRIu64"\n",
2658 path, (uint64_t)st.st_mtime,
2659 (uint64_t)mtime);
2660 }
2661 } else {
2662 ERR("unsupported file type %s: %o\n",
2663 path, st.st_mode & S_IFMT);
2664 continue;
2665 }
2666
2667 if (err == 0)
2668 break; /* outdated! */
2669 else if (err < 0) {
2670 path[baselen + namelen] = '\0';
2671 ERR("failed %s: %s\n", path, strerror(-err));
2672 err = 1; /* ignore errors */
2673 }
2674 }
2675
2676 return err;
2677 }
2678
2679 /* uptodate: 1, outdated: 0, errors < 0 */
2680 static int depfile_up_to_date(const char *dirname)
2681 {
2682 char path[PATH_MAX];
2683 DIR *d = opendir(dirname);
2684 struct stat st;
2685 size_t baselen;
2686 int err;
2687 if (d == NULL) {
2688 err = -errno;
2689 ERR("could not open directory %s: %m\n", dirname);
2690 return err;
2691 }
2692
2693 if (fstatat(dirfd(d), "modules.dep", &st, 0) != 0) {
2694 err = -errno;
2695 ERR("could not fstatat(%s, modules.dep): %m\n", dirname);
2696 closedir(d);
2697 return err;
2698 }
2699
2700 baselen = strlen(dirname);
2701 memcpy(path, dirname, baselen);
2702 path[baselen] = '/';
2703 baselen++;
2704 path[baselen] = '\0';
2705
2706 err = depfile_up_to_date_dir(d, st.st_mtime, baselen, path);
2707 closedir(d);
2708 return err;
2709 }
2710
2711 static int is_version_number(const char *version)
2712 {
2713 unsigned int d1, d2;
2714 return (sscanf(version, "%u.%u", &d1, &d2) == 2);
2715 }
2716
2717 static int do_depmod(int argc, char *argv[])
2718 {
2719 FILE *out = NULL;
2720 int err = 0, all = 0, maybe_all = 0, n_config_paths = 0;
2721 _cleanup_free_ char *root = NULL;
2722 _cleanup_free_ const char **config_paths = NULL;
2723 const char *system_map = NULL;
2724 const char *module_symvers = NULL;
2725 const char *null_kmod_config = NULL;
2726 struct utsname un;
2727 struct kmod_ctx *ctx = NULL;
2728 struct cfg cfg;
2729 struct depmod depmod;
2730
2731 memset(&cfg, 0, sizeof(cfg));
2732 memset(&depmod, 0, sizeof(depmod));
2733
2734 for (;;) {
2735 int c, idx = 0;
2736 c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx);
2737 if (c == -1)
2738 break;
2739 switch (c) {
2740 case 'a':
2741 all = 1;
2742 break;
2743 case 'A':
2744 maybe_all = 1;
2745 break;
2746 case 'b':
2747 if (root)
2748 free(root);
2749 root = path_make_absolute_cwd(optarg);
2750 break;
2751 case 'C': {
2752 size_t bytes = sizeof(char *) * (n_config_paths + 2);
2753 void *tmp = realloc(config_paths, bytes);
2754 if (!tmp) {
2755 fputs("Error: out-of-memory\n", stderr);
2756 goto cmdline_failed;
2757 }
2758 config_paths = tmp;
2759 config_paths[n_config_paths] = optarg;
2760 n_config_paths++;
2761 config_paths[n_config_paths] = NULL;
2762 break;
2763 }
2764 case 'E':
2765 module_symvers = optarg;
2766 cfg.check_symvers = 1;
2767 break;
2768 case 'F':
2769 system_map = optarg;
2770 break;
2771 case 'e':
2772 cfg.print_unknown = 1;
2773 break;
2774 case 'v':
2775 verbose++;
2776 break;
2777 case 'n':
2778 out = stdout;
2779 break;
2780 case 'P':
2781 if (optarg[1] != '\0') {
2782 CRIT("-P only takes a single char\n");
2783 goto cmdline_failed;
2784 }
2785 cfg.sym_prefix = optarg[0];
2786 break;
2787 case 'w':
2788 cfg.warn_dups = 1;
2789 break;
2790 case 'u':
2791 case 'q':
2792 case 'r':
2793 case 'm':
2794 if (idx > 0)
2795 WRN("Ignored deprecated option --%s\n",
2796 cmdopts[idx].name);
2797 else
2798 WRN("Ignored deprecated option -%c\n", c);
2799
2800 break;
2801 case 'h':
2802 help();
2803 return EXIT_SUCCESS;
2804 case 'V':
2805 puts(PACKAGE " version " VERSION);
2806 puts(KMOD_FEATURES);
2807 return EXIT_SUCCESS;
2808 case '?':
2809 goto cmdline_failed;
2810 default:
2811 ERR("unexpected getopt_long() value '%c'.\n", c);
2812 goto cmdline_failed;
2813 }
2814 }
2815
2816 if (optind < argc) {
2817 if (!is_version_number(argv[optind])) {
2818 ERR("Bad version passed %s\n", argv[optind]);
2819 goto cmdline_failed;
2820 }
2821 cfg.kversion = argv[optind];
2822 optind++;
2823 } else {
2824 if (uname(&un) < 0) {
2825 CRIT("uname() failed: %s\n", strerror(errno));
2826 goto cmdline_failed;
2827 }
2828 cfg.kversion = un.release;
2829 }
2830
2831 cfg.dirnamelen = snprintf(cfg.dirname, PATH_MAX,
2832 "%s/lib/modules/%s",
2833 root == NULL ? "" : root, cfg.kversion);
2834
2835 if (optind == argc)
2836 all = 1;
2837
2838 if (maybe_all) {
2839 if (out == stdout)
2840 goto done;
2841 /* ignore up-to-date errors (< 0) */
2842 if (depfile_up_to_date(cfg.dirname) == 1)
2843 goto done;
2844 all = 1;
2845 }
2846
2847 ctx = kmod_new(cfg.dirname, &null_kmod_config);
2848 if (ctx == NULL) {
2849 CRIT("kmod_new(\"%s\", {NULL}) failed: %m\n", cfg.dirname);
2850 goto cmdline_failed;
2851 }
2852
2853 log_setup_kmod_log(ctx, verbose);
2854
2855 err = depmod_init(&depmod, &cfg, ctx);
2856 if (err < 0) {
2857 CRIT("depmod_init: %s\n", strerror(-err));
2858 goto depmod_init_failed;
2859 }
2860 ctx = NULL; /* owned by depmod */
2861
2862 if (module_symvers != NULL) {
2863 err = depmod_load_symvers(&depmod, module_symvers);
2864 if (err < 0) {
2865 CRIT("could not load %s: %s\n", module_symvers,
2866 strerror(-err));
2867 goto cmdline_failed;
2868 }
2869 } else if (system_map != NULL) {
2870 err = depmod_load_system_map(&depmod, system_map);
2871 if (err < 0) {
2872 CRIT("could not load %s: %s\n", system_map,
2873 strerror(-err));
2874 goto cmdline_failed;
2875 }
2876 } else if (cfg.print_unknown) {
2877 WRN("-e needs -E or -F\n");
2878 cfg.print_unknown = 0;
2879 }
2880
2881 if (all) {
2882 err = cfg_load(&cfg, config_paths);
2883 if (err < 0) {
2884 CRIT("could not load configuration files\n");
2885 goto cmdline_modules_failed;
2886 }
2887 err = depmod_modules_search(&depmod);
2888 if (err < 0) {
2889 CRIT("could not search modules: %s\n", strerror(-err));
2890 goto cmdline_modules_failed;
2891 }
2892 } else {
2893 int i;
2894
2895 for (i = optind; i < argc; i++) {
2896 const char *path = argv[i];
2897 struct kmod_module *mod;
2898
2899 if (path[0] != '/') {
2900 CRIT("%s: not absolute path.\n", path);
2901 goto cmdline_modules_failed;
2902 }
2903
2904 err = kmod_module_new_from_path(depmod.ctx, path, &mod);
2905 if (err < 0) {
2906 CRIT("could not create module %s: %s\n",
2907 path, strerror(-err));
2908 goto cmdline_modules_failed;
2909 }
2910
2911 err = depmod_module_add(&depmod, mod);
2912 if (err < 0) {
2913 CRIT("could not add module %s: %s\n",
2914 path, strerror(-err));
2915 kmod_module_unref(mod);
2916 goto cmdline_modules_failed;
2917 }
2918 }
2919 }
2920
2921 err = depmod_modules_build_array(&depmod);
2922 if (err < 0) {
2923 CRIT("could not build module array: %s\n",
2924 strerror(-err));
2925 goto cmdline_modules_failed;
2926 }
2927
2928 depmod_modules_sort(&depmod);
2929 err = depmod_load(&depmod);
2930 if (err < 0)
2931 goto cmdline_modules_failed;
2932
2933 err = depmod_output(&depmod, out);
2934
2935 done:
2936 depmod_shutdown(&depmod);
2937 cfg_free(&cfg);
2938 return err >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
2939
2940 cmdline_modules_failed:
2941 depmod_shutdown(&depmod);
2942 depmod_init_failed:
2943 if (ctx != NULL)
2944 kmod_unref(ctx);
2945 cmdline_failed:
2946 cfg_free(&cfg);
2947 return EXIT_FAILURE;
2948 }
2949
2950 const struct kmod_cmd kmod_cmd_compat_depmod = {
2951 .name = "depmod",
2952 .cmd = do_depmod,
2953 .help = "compat depmod command",
2954 };