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