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