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