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