xref: /freebsd/stand/common/module.c (revision b0fefb25c558179e9f9c7f0d375c6a03fb567eb9)
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 /*
31  * file/module function dispatcher, support, etc.
32  */
33 
34 #include <stand.h>
35 #include <string.h>
36 #include <sys/param.h>
37 #include <sys/linker.h>
38 #include <sys/module.h>
39 #include <sys/queue.h>
40 #include <sys/stdint.h>
41 
42 #include "bootstrap.h"
43 
44 #define	MDIR_REMOVED	0x0001
45 #define	MDIR_NOHINTS	0x0002
46 
47 struct moduledir {
48 	char	*d_path;	/* path of modules directory */
49 	u_char	*d_hints;	/* content of linker.hints file */
50 	int	d_hintsz;	/* size of hints data */
51 	int	d_flags;
52 	STAILQ_ENTRY(moduledir) d_link;
53 };
54 
55 static int			file_load(char *filename, vm_offset_t dest, struct preloaded_file **result);
56 static int			file_load_dependencies(struct preloaded_file *base_mod);
57 static char *			file_search(const char *name, char **extlist);
58 static struct kernel_module *	file_findmodule(struct preloaded_file *fp, char *modname, struct mod_depend *verinfo);
59 static int			file_havepath(const char *name);
60 static char			*mod_searchmodule(char *name, struct mod_depend *verinfo);
61 static void			file_insert_tail(struct preloaded_file *mp);
62 struct file_metadata*		metadata_next(struct file_metadata *base_mp, int type);
63 static void			moduledir_readhints(struct moduledir *mdp);
64 static void			moduledir_rebuild(void);
65 
66 /* load address should be tweaked by first module loaded (kernel) */
67 static vm_offset_t	loadaddr = 0;
68 
69 #if defined(LOADER_FDT_SUPPORT)
70 static const char	*default_searchpath =
71     "/boot/kernel;/boot/modules;/boot/dtb";
72 #else
73 static const char	*default_searchpath ="/boot/kernel;/boot/modules";
74 #endif
75 
76 static STAILQ_HEAD(, moduledir) moduledir_list = STAILQ_HEAD_INITIALIZER(moduledir_list);
77 
78 struct preloaded_file *preloaded_files = NULL;
79 
80 static char *kld_ext_list[] = {
81     ".ko",
82     "",
83     ".debug",
84     NULL
85 };
86 
87 
88 /*
89  * load an object, either a disk file or code module.
90  *
91  * To load a file, the syntax is:
92  *
93  * load -t <type> <path>
94  *
95  * code modules are loaded as:
96  *
97  * load <path> <options>
98  */
99 
100 COMMAND_SET(load, "load", "load a kernel or module", command_load);
101 
102 static int
103 command_load(int argc, char *argv[])
104 {
105 	struct preloaded_file *fp;
106 	char	*typestr;
107 	char	*prefix;
108 	char	*skip;
109 	int		dflag, dofile, dokld, ch, error;
110 
111 	dflag = dokld = dofile = 0;
112 	optind = 1;
113 	optreset = 1;
114 	typestr = NULL;
115 	if (argc == 1) {
116 		command_errmsg = "no filename specified";
117 		return (CMD_CRIT);
118 	}
119 	prefix = skip = NULL;
120 	while ((ch = getopt(argc, argv, "dkp:s:t:")) != -1) {
121 		switch(ch) {
122 		case 'd':
123 			dflag++;
124 			break;
125 		case 'k':
126 			dokld = 1;
127 			break;
128 		case 'p':
129 			prefix = optarg;
130 			break;
131 		case 's':
132 			skip = optarg;
133 			break;
134 		case 't':
135 			typestr = optarg;
136 			dofile = 1;
137 			break;
138 		case '?':
139 		default:
140 			/* getopt has already reported an error */
141 			return (CMD_OK);
142 		}
143 	}
144 	argv += (optind - 1);
145 	argc -= (optind - 1);
146 
147 	/*
148 	 * Request to load a raw file?
149 	 */
150 	if (dofile) {
151 		if ((argc != 2) || (typestr == NULL) || (*typestr == 0)) {
152 			command_errmsg = "invalid load type";
153 			return (CMD_CRIT);
154 		}
155 
156 #ifdef LOADER_VERIEXEC
157 		if (strncmp(typestr, "manifest", 8) == 0) {
158 			if (dflag > 0)
159 				ve_debug_set(dflag);
160 			return (load_manifest(argv[1], prefix, skip, NULL));
161 		}
162 #ifdef LOADER_VERIEXEC_PASS_MANIFEST
163 		if (strncmp(typestr, "pass_manifest", 13) == 0) {
164 			if (dflag > 0)
165 				ve_debug_set(dflag);
166 		    return (pass_manifest(argv[1], prefix));
167 		}
168 #endif
169 #endif
170 
171 		fp = file_findfile(argv[1], typestr);
172 		if (fp) {
173 			snprintf(command_errbuf, sizeof(command_errbuf),
174 			  "warning: file '%s' already loaded", argv[1]);
175 			return (CMD_WARN);
176 		}
177 
178 		if (file_loadraw(argv[1], typestr, 1) != NULL)
179 			return (CMD_OK);
180 
181 		/* Failing to load mfs_root is never going to end well! */
182 		if (strcmp("mfs_root", typestr) == 0)
183 			return (CMD_FATAL);
184 
185 		return (CMD_ERROR);
186 	}
187 	/*
188 	 * Do we have explicit KLD load ?
189 	 */
190 	if (dokld || file_havepath(argv[1])) {
191 		error = mod_loadkld(argv[1], argc - 2, argv + 2);
192 		if (error == EEXIST) {
193 			snprintf(command_errbuf, sizeof(command_errbuf),
194 			  "warning: KLD '%s' already loaded", argv[1]);
195 			return (CMD_WARN);
196 		}
197 
198 		return (error == 0 ? CMD_OK : CMD_CRIT);
199 	}
200 	/*
201 	 * Looks like a request for a module.
202 	 */
203 	error = mod_load(argv[1], NULL, argc - 2, argv + 2);
204 	if (error == EEXIST) {
205 		snprintf(command_errbuf, sizeof(command_errbuf),
206 		  "warning: module '%s' already loaded", argv[1]);
207 		return (CMD_WARN);
208 	}
209 
210 	return (error == 0 ? CMD_OK : CMD_CRIT);
211 }
212 
213 #ifdef LOADER_GELI_SUPPORT
214 COMMAND_SET(load_geli, "load_geli", "load a geli key", command_load_geli);
215 
216 static int
217 command_load_geli(int argc, char *argv[])
218 {
219 	char	typestr[80];
220 	char	*cp;
221 	int		ch, num;
222 
223 	if (argc < 3) {
224 		command_errmsg = "usage is [-n key#] <prov> <file>";
225 		return(CMD_ERROR);
226 	}
227 
228 	num = 0;
229 	optind = 1;
230 	optreset = 1;
231 	while ((ch = getopt(argc, argv, "n:")) != -1) {
232 		switch(ch) {
233 		case 'n':
234 			num = strtol(optarg, &cp, 0);
235 			if (cp == optarg) {
236 				snprintf(command_errbuf, sizeof(command_errbuf),
237 				  "bad key index '%s'", optarg);
238 				return(CMD_ERROR);
239 			}
240 			break;
241 		case '?':
242 		default:
243 			/* getopt has already reported an error */
244 			return(CMD_OK);
245 		}
246 	}
247 	argv += (optind - 1);
248 	argc -= (optind - 1);
249 	sprintf(typestr, "%s:geli_keyfile%d", argv[1], num);
250 	return (file_loadraw(argv[2], typestr, 1) ? CMD_OK : CMD_ERROR);
251 }
252 #endif
253 
254 void
255 unload(void)
256 {
257 	struct preloaded_file *fp;
258 
259 	while (preloaded_files != NULL) {
260 		fp = preloaded_files;
261 		preloaded_files = preloaded_files->f_next;
262 		file_discard(fp);
263 	}
264 	loadaddr = 0;
265 	unsetenv("kernelname");
266 }
267 
268 COMMAND_SET(unload, "unload", "unload all modules", command_unload);
269 
270 static int
271 command_unload(int argc, char *argv[])
272 {
273 	unload();
274 	return(CMD_OK);
275 }
276 
277 COMMAND_SET(lsmod, "lsmod", "list loaded modules", command_lsmod);
278 
279 static int
280 command_lsmod(int argc, char *argv[])
281 {
282 	struct preloaded_file	*fp;
283 	struct kernel_module	*mp;
284 	struct file_metadata	*md;
285 	char			lbuf[80];
286 	int				ch, verbose, ret = 0;
287 
288 	verbose = 0;
289 	optind = 1;
290 	optreset = 1;
291 	while ((ch = getopt(argc, argv, "v")) != -1) {
292 		switch(ch) {
293 		case 'v':
294 			verbose = 1;
295 			break;
296 		case '?':
297 		default:
298 			/* getopt has already reported an error */
299 			return(CMD_OK);
300 		}
301 	}
302 
303 	pager_open();
304 	for (fp = preloaded_files; fp; fp = fp->f_next) {
305 		snprintf(lbuf, sizeof(lbuf), " %p: ", (void *) fp->f_addr);
306 		pager_output(lbuf);
307 		pager_output(fp->f_name);
308 		snprintf(lbuf, sizeof(lbuf), " (%s, 0x%lx)\n", fp->f_type,
309 		  (long)fp->f_size);
310 		if (pager_output(lbuf))
311 			break;
312 		if (fp->f_args != NULL) {
313 			pager_output("    args: ");
314 			pager_output(fp->f_args);
315 			if (pager_output("\n"))
316 				break;
317 		}
318 		if (fp->f_modules) {
319 			pager_output("  modules: ");
320 			for (mp = fp->f_modules; mp; mp = mp->m_next) {
321 				snprintf(lbuf, sizeof(lbuf), "%s.%d ", mp->m_name,
322 				  mp->m_version);
323 				pager_output(lbuf);
324 			}
325 			if (pager_output("\n"))
326 				break;
327 		}
328 		if (verbose) {
329 			/* XXX could add some formatting smarts here to display some better */
330 			for (md = fp->f_metadata; md != NULL; md = md->md_next) {
331 				snprintf(lbuf, sizeof(lbuf), "      0x%04x, 0x%lx\n",
332 				  md->md_type, (long) md->md_size);
333 				if (pager_output(lbuf))
334 					break;
335 			}
336 		}
337 		if (ret)
338 			break;
339 	}
340 	pager_close();
341 	return(CMD_OK);
342 }
343 
344 /*
345  * File level interface, functions file_*
346  */
347 int
348 file_load(char *filename, vm_offset_t dest, struct preloaded_file **result)
349 {
350 	static int last_file_format = 0;
351 	struct preloaded_file *fp;
352 	int error;
353 	int i;
354 
355 	if (archsw.arch_loadaddr != NULL)
356 		dest = archsw.arch_loadaddr(LOAD_RAW, filename, dest);
357 
358 	error = EFTYPE;
359 	for (i = last_file_format, fp = NULL;
360 	     file_formats[i] && fp == NULL; i++) {
361 		error = (file_formats[i]->l_load)(filename, dest, &fp);
362 		if (error == 0) {
363 			fp->f_loader = last_file_format = i; /* remember the loader */
364 			*result = fp;
365 			break;
366 		} else if (last_file_format == i && i != 0) {
367 			/* Restart from the beginning */
368 			i = -1;
369 			last_file_format = 0;
370 			fp = NULL;
371 			continue;
372 		}
373 		if (error == EFTYPE)
374 			continue;		/* Unknown to this handler? */
375 		if (error) {
376 			snprintf(command_errbuf, sizeof(command_errbuf),
377 			  "can't load file '%s': %s", filename, strerror(error));
378 			break;
379 		}
380 	}
381 	return (error);
382 }
383 
384 static int
385 file_load_dependencies(struct preloaded_file *base_file)
386 {
387 	struct file_metadata *md;
388 	struct preloaded_file *fp;
389 	struct mod_depend *verinfo;
390 	struct kernel_module *mp;
391 	char *dmodname;
392 	int error;
393 
394 	md = file_findmetadata(base_file, MODINFOMD_DEPLIST);
395 	if (md == NULL)
396 		return (0);
397 	error = 0;
398 	do {
399 		verinfo = (struct mod_depend*)md->md_data;
400 		dmodname = (char *)(verinfo + 1);
401 		if (file_findmodule(NULL, dmodname, verinfo) == NULL) {
402 			printf("loading required module '%s'\n", dmodname);
403 			error = mod_load(dmodname, verinfo, 0, NULL);
404 			if (error)
405 				break;
406 			/*
407 			 * If module loaded via kld name which isn't listed
408 			 * in the linker.hints file, we should check if it have
409 			 * required version.
410 			 */
411 			mp = file_findmodule(NULL, dmodname, verinfo);
412 			if (mp == NULL) {
413 				snprintf(command_errbuf, sizeof(command_errbuf),
414 				  "module '%s' exists but with wrong version", dmodname);
415 				error = ENOENT;
416 				break;
417 			}
418 		}
419 		md = metadata_next(md, MODINFOMD_DEPLIST);
420 	} while (md);
421 	if (!error)
422 		return (0);
423 	/* Load failed; discard everything */
424 	while (base_file != NULL) {
425 		fp = base_file;
426 		base_file = base_file->f_next;
427 		file_discard(fp);
428 	}
429 	return (error);
430 }
431 
432 /*
433  * We've been asked to load (fname) as (type), so just suck it in,
434  * no arguments or anything.
435  */
436 struct preloaded_file *
437 file_loadraw(const char *fname, char *type, int insert)
438 {
439 	struct preloaded_file	*fp;
440 	char			*name;
441 	int				fd, got;
442 	vm_offset_t			laddr;
443 
444 	/* We can't load first */
445 	if ((file_findfile(NULL, NULL)) == NULL) {
446 		command_errmsg = "can't load file before kernel";
447 		return(NULL);
448 	}
449 
450 	/* locate the file on the load path */
451 	name = file_search(fname, NULL);
452 	if (name == NULL) {
453 		snprintf(command_errbuf, sizeof(command_errbuf),
454 		  "can't find '%s'", fname);
455 		return(NULL);
456 	}
457 
458 	if ((fd = open(name, O_RDONLY)) < 0) {
459 		snprintf(command_errbuf, sizeof(command_errbuf),
460 		  "can't open '%s': %s", name, strerror(errno));
461 		free(name);
462 		return(NULL);
463 	}
464 
465 #ifdef LOADER_VERIEXEC
466 	if (verify_file(fd, name, 0, VE_MUST) < 0) {
467 		sprintf(command_errbuf, "can't verify '%s'", name);
468 		free(name);
469 		close(fd);
470 		return(NULL);
471 	}
472 #endif
473 
474 	if (archsw.arch_loadaddr != NULL)
475 		loadaddr = archsw.arch_loadaddr(LOAD_RAW, name, loadaddr);
476 
477 	printf("%s ", name);
478 
479 	laddr = loadaddr;
480 	for (;;) {
481 		/* read in 4k chunks; size is not really important */
482 		got = archsw.arch_readin(fd, laddr, 4096);
483 		if (got == 0)				/* end of file */
484 			break;
485 		if (got < 0) {				/* error */
486 			snprintf(command_errbuf, sizeof(command_errbuf),
487 			  "error reading '%s': %s", name, strerror(errno));
488 			free(name);
489 			close(fd);
490 			return(NULL);
491 		}
492 		laddr += got;
493 	}
494 
495 	printf("size=%#jx\n", (uintmax_t)(laddr - loadaddr));
496 
497 	/* Looks OK so far; create & populate control structure */
498 	fp = file_alloc();
499 	fp->f_name = strdup(name);
500 	fp->f_type = strdup(type);
501 	fp->f_args = NULL;
502 	fp->f_metadata = NULL;
503 	fp->f_loader = -1;
504 	fp->f_addr = loadaddr;
505 	fp->f_size = laddr - loadaddr;
506 
507 	/* recognise space consumption */
508 	loadaddr = laddr;
509 
510 	/* Add to the list of loaded files */
511 	if (insert != 0)
512 		file_insert_tail(fp);
513 	close(fd);
514 	return(fp);
515 }
516 
517 /*
518  * Load the module (name), pass it (argc),(argv), add container file
519  * to the list of loaded files.
520  * If module is already loaded just assign new argc/argv.
521  */
522 int
523 mod_load(char *modname, struct mod_depend *verinfo, int argc, char *argv[])
524 {
525 	struct kernel_module	*mp;
526 	int				err;
527 	char			*filename;
528 
529 	if (file_havepath(modname)) {
530 		printf("Warning: mod_load() called instead of mod_loadkld() for module '%s'\n", modname);
531 		return (mod_loadkld(modname, argc, argv));
532 	}
533 	/* see if module is already loaded */
534 	mp = file_findmodule(NULL, modname, verinfo);
535 	if (mp) {
536 #ifdef moduleargs
537 		if (mp->m_args)
538 			free(mp->m_args);
539 		mp->m_args = unargv(argc, argv);
540 #endif
541 		snprintf(command_errbuf, sizeof(command_errbuf),
542 		  "warning: module '%s' already loaded", mp->m_name);
543 		return (0);
544 	}
545 	/* locate file with the module on the search path */
546 	filename = mod_searchmodule(modname, verinfo);
547 	if (filename == NULL) {
548 		snprintf(command_errbuf, sizeof(command_errbuf),
549 		  "can't find '%s'", modname);
550 		return (ENOENT);
551 	}
552 	err = mod_loadkld(filename, argc, argv);
553 	return (err);
554 }
555 
556 /*
557  * Load specified KLD. If path is omitted, then try to locate it via
558  * search path.
559  */
560 int
561 mod_loadkld(const char *kldname, int argc, char *argv[])
562 {
563 	struct preloaded_file	*fp, *last_file;
564 	int				err;
565 	char			*filename;
566 
567 	/*
568 	 * Get fully qualified KLD name
569 	 */
570 	filename = file_search(kldname, kld_ext_list);
571 	if (filename == NULL) {
572 		snprintf(command_errbuf, sizeof(command_errbuf),
573 		  "can't find '%s'", kldname);
574 		return (ENOENT);
575 	}
576 	/*
577 	 * Check if KLD already loaded
578 	 */
579 	fp = file_findfile(filename, NULL);
580 	if (fp) {
581 		snprintf(command_errbuf, sizeof(command_errbuf),
582 		  "warning: KLD '%s' already loaded", filename);
583 		free(filename);
584 		return (0);
585 	}
586 	for (last_file = preloaded_files;
587 	     last_file != NULL && last_file->f_next != NULL;
588 	     last_file = last_file->f_next)
589 		;
590 
591 	do {
592 		err = file_load(filename, loadaddr, &fp);
593 		if (err)
594 			break;
595 		fp->f_args = unargv(argc, argv);
596 		loadaddr = fp->f_addr + fp->f_size;
597 		file_insert_tail(fp);		/* Add to the list of loaded files */
598 		if (file_load_dependencies(fp) != 0) {
599 			err = ENOENT;
600 			last_file->f_next = NULL;
601 			loadaddr = last_file->f_addr + last_file->f_size;
602 			fp = NULL;
603 			break;
604 		}
605 	} while(0);
606 	if (err == EFTYPE) {
607 		snprintf(command_errbuf, sizeof(command_errbuf),
608 		  "don't know how to load module '%s'", filename);
609 	}
610 	if (err && fp)
611 		file_discard(fp);
612 	free(filename);
613 	return (err);
614 }
615 
616 /*
617  * Find a file matching (name) and (type).
618  * NULL may be passed as a wildcard to either.
619  */
620 struct preloaded_file *
621 file_findfile(const char *name, const char *type)
622 {
623 	struct preloaded_file *fp;
624 
625 	for (fp = preloaded_files; fp != NULL; fp = fp->f_next) {
626 		if (((name == NULL) || !strcmp(name, fp->f_name)) &&
627 		  ((type == NULL) || !strcmp(type, fp->f_type)))
628 			break;
629 	}
630 	return (fp);
631 }
632 
633 /*
634  * Find a module matching (name) inside of given file.
635  * NULL may be passed as a wildcard.
636  */
637 struct kernel_module *
638 file_findmodule(struct preloaded_file *fp, char *modname,
639 	struct mod_depend *verinfo)
640 {
641 	struct kernel_module *mp, *best;
642 	int bestver, mver;
643 
644 	if (fp == NULL) {
645 		for (fp = preloaded_files; fp; fp = fp->f_next) {
646 			mp = file_findmodule(fp, modname, verinfo);
647 			if (mp)
648 				return (mp);
649 		}
650 		return (NULL);
651 	}
652 	best = NULL;
653 	bestver = 0;
654 	for (mp = fp->f_modules; mp; mp = mp->m_next) {
655 		if (strcmp(modname, mp->m_name) == 0) {
656 			if (verinfo == NULL)
657 				return (mp);
658 			mver = mp->m_version;
659 			if (mver == verinfo->md_ver_preferred)
660 				return (mp);
661 			if (mver >= verinfo->md_ver_minimum &&
662 			  mver <= verinfo->md_ver_maximum &&
663 			  mver > bestver) {
664 				best = mp;
665 				bestver = mver;
666 			}
667 		}
668 	}
669 	return (best);
670 }
671 /*
672  * Make a copy of (size) bytes of data from (p), and associate them as
673  * metadata of (type) to the module (mp).
674  */
675 void
676 file_addmetadata(struct preloaded_file *fp, int type, size_t size, void *p)
677 {
678 	struct file_metadata	*md;
679 
680 	md = malloc(sizeof(struct file_metadata) - sizeof(md->md_data) + size);
681 	md->md_size = size;
682 	md->md_type = type;
683 	bcopy(p, md->md_data, size);
684 	md->md_next = fp->f_metadata;
685 	fp->f_metadata = md;
686 }
687 
688 /*
689  * Find a metadata object of (type) associated with the file (fp)
690  */
691 struct file_metadata *
692 file_findmetadata(struct preloaded_file *fp, int type)
693 {
694 	struct file_metadata *md;
695 
696 	for (md = fp->f_metadata; md != NULL; md = md->md_next)
697 		if (md->md_type == type)
698 			break;
699 	return(md);
700 }
701 
702 /*
703  * Remove all metadata from the file.
704  */
705 void
706 file_removemetadata(struct preloaded_file *fp)
707 {
708 	struct file_metadata *md, *next;
709 
710 	for (md = fp->f_metadata; md != NULL; md = next)
711 	{
712 		next = md->md_next;
713 		free(md);
714 	}
715 	fp->f_metadata = NULL;
716 }
717 
718 struct file_metadata *
719 metadata_next(struct file_metadata *md, int type)
720 {
721 
722 	if (md == NULL)
723 		return (NULL);
724 	while((md = md->md_next) != NULL)
725 		if (md->md_type == type)
726 			break;
727 	return (md);
728 }
729 
730 static char *emptyextlist[] = { "", NULL };
731 
732 /*
733  * Check if the given file is in place and return full path to it.
734  */
735 static char *
736 file_lookup(const char *path, const char *name, int namelen, char **extlist)
737 {
738 	struct stat	st;
739 	char	*result, *cp, **cpp;
740 	int		pathlen, extlen, len;
741 
742 	pathlen = strlen(path);
743 	extlen = 0;
744 	if (extlist == NULL)
745 		extlist = emptyextlist;
746 	for (cpp = extlist; *cpp; cpp++) {
747 		len = strlen(*cpp);
748 		if (len > extlen)
749 			extlen = len;
750 	}
751 	result = malloc(pathlen + namelen + extlen + 2);
752 	if (result == NULL)
753 		return (NULL);
754 	bcopy(path, result, pathlen);
755 	if (pathlen > 0 && result[pathlen - 1] != '/')
756 		result[pathlen++] = '/';
757 	cp = result + pathlen;
758 	bcopy(name, cp, namelen);
759 	cp += namelen;
760 	for (cpp = extlist; *cpp; cpp++) {
761 		strcpy(cp, *cpp);
762 		if (stat(result, &st) == 0 && S_ISREG(st.st_mode))
763 			return result;
764 	}
765 	free(result);
766 	return NULL;
767 }
768 
769 /*
770  * Check if file name have any qualifiers
771  */
772 static int
773 file_havepath(const char *name)
774 {
775 	const char		*cp;
776 
777 	archsw.arch_getdev(NULL, name, &cp);
778 	return (cp != name || strchr(name, '/') != NULL);
779 }
780 
781 /*
782  * Attempt to find the file (name) on the module searchpath.
783  * If (name) is qualified in any way, we simply check it and
784  * return it or NULL.  If it is not qualified, then we attempt
785  * to construct a path using entries in the environment variable
786  * module_path.
787  *
788  * The path we return a pointer to need never be freed, as we manage
789  * it internally.
790  */
791 static char *
792 file_search(const char *name, char **extlist)
793 {
794 	struct moduledir	*mdp;
795 	struct stat		sb;
796 	char		*result;
797 	int			namelen;
798 
799 	/* Don't look for nothing */
800 	if (name == NULL)
801 		return(NULL);
802 
803 	if (*name == 0)
804 		return(strdup(name));
805 
806 	if (file_havepath(name)) {
807 		/* Qualified, so just see if it exists */
808 		if (stat(name, &sb) == 0)
809 			return(strdup(name));
810 		return(NULL);
811 	}
812 	moduledir_rebuild();
813 	result = NULL;
814 	namelen = strlen(name);
815 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
816 		result = file_lookup(mdp->d_path, name, namelen, extlist);
817 		if (result)
818 			break;
819 	}
820 	return(result);
821 }
822 
823 #define	INT_ALIGN(base, ptr)	ptr = \
824 	(base) + roundup2((ptr) - (base), sizeof(int))
825 
826 static char *
827 mod_search_hints(struct moduledir *mdp, const char *modname,
828 	struct mod_depend *verinfo)
829 {
830 	u_char	*cp, *recptr, *bufend, *best;
831 	char	*result;
832 	int		*intp, bestver, blen, clen, found, ival, modnamelen, reclen;
833 
834 	moduledir_readhints(mdp);
835 	modnamelen = strlen(modname);
836 	found = 0;
837 	result = NULL;
838 	bestver = 0;
839 	if (mdp->d_hints == NULL)
840 		goto bad;
841 	recptr = mdp->d_hints;
842 	bufend = recptr + mdp->d_hintsz;
843 	clen = blen = 0;
844 	best = cp = NULL;
845 	while (recptr < bufend && !found) {
846 		intp = (int*)recptr;
847 		reclen = *intp++;
848 		ival = *intp++;
849 		cp = (u_char*)intp;
850 		switch (ival) {
851 		case MDT_VERSION:
852 			clen = *cp++;
853 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
854 				break;
855 			cp += clen;
856 			INT_ALIGN(mdp->d_hints, cp);
857 			ival = *(int*)cp;
858 			cp += sizeof(int);
859 			clen = *cp++;
860 			if (verinfo == NULL || ival == verinfo->md_ver_preferred) {
861 				found = 1;
862 				break;
863 			}
864 			if (ival >= verinfo->md_ver_minimum &&
865 			  ival <= verinfo->md_ver_maximum &&
866 			  ival > bestver) {
867 				bestver = ival;
868 				best = cp;
869 				blen = clen;
870 			}
871 			break;
872 		default:
873 			break;
874 		}
875 		recptr += reclen + sizeof(int);
876 	}
877 	/*
878 	 * Finally check if KLD is in the place
879 	 */
880 	if (found)
881 		result = file_lookup(mdp->d_path, (const char *)cp, clen, NULL);
882 	else if (best)
883 		result = file_lookup(mdp->d_path, (const char *)best, blen, NULL);
884 bad:
885 	/*
886 	 * If nothing found or hints is absent - fallback to the old way
887 	 * by using "kldname[.ko]" as module name.
888 	 */
889 	if (!found && !bestver && result == NULL)
890 		result = file_lookup(mdp->d_path, modname, modnamelen, kld_ext_list);
891 	return result;
892 }
893 
894 /*
895  * Attempt to locate the file containing the module (name)
896  */
897 static char *
898 mod_searchmodule(char *name, struct mod_depend *verinfo)
899 {
900 	struct	moduledir *mdp;
901 	char	*result;
902 
903 	moduledir_rebuild();
904 	/*
905 	 * Now we ready to lookup module in the given directories
906 	 */
907 	result = NULL;
908 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
909 		result = mod_search_hints(mdp, name, verinfo);
910 		if (result)
911 			break;
912 	}
913 
914 	return(result);
915 }
916 
917 int
918 file_addmodule(struct preloaded_file *fp, char *modname, int version,
919 	struct kernel_module **newmp)
920 {
921 	struct kernel_module *mp;
922 	struct mod_depend mdepend;
923 
924 	bzero(&mdepend, sizeof(mdepend));
925 	mdepend.md_ver_preferred = version;
926 	mp = file_findmodule(fp, modname, &mdepend);
927 	if (mp)
928 		return (EEXIST);
929 	mp = malloc(sizeof(struct kernel_module));
930 	if (mp == NULL)
931 		return (ENOMEM);
932 	bzero(mp, sizeof(struct kernel_module));
933 	mp->m_name = strdup(modname);
934 	mp->m_version = version;
935 	mp->m_fp = fp;
936 	mp->m_next = fp->f_modules;
937 	fp->f_modules = mp;
938 	if (newmp)
939 		*newmp = mp;
940 	return (0);
941 }
942 
943 /*
944  * Throw a file away
945  */
946 void
947 file_discard(struct preloaded_file *fp)
948 {
949 	struct file_metadata	*md, *md1;
950 	struct kernel_module	*mp, *mp1;
951 	if (fp == NULL)
952 		return;
953 	md = fp->f_metadata;
954 	while (md) {
955 		md1 = md;
956 		md = md->md_next;
957 		free(md1);
958 	}
959 	mp = fp->f_modules;
960 	while (mp) {
961 		if (mp->m_name)
962 			free(mp->m_name);
963 		mp1 = mp;
964 		mp = mp->m_next;
965 		free(mp1);
966 	}
967 	if (fp->f_name != NULL)
968 		free(fp->f_name);
969 	if (fp->f_type != NULL)
970 		free(fp->f_type);
971 	if (fp->f_args != NULL)
972 		free(fp->f_args);
973 	free(fp);
974 }
975 
976 /*
977  * Allocate a new file; must be used instead of malloc()
978  * to ensure safe initialisation.
979  */
980 struct preloaded_file *
981 file_alloc(void)
982 {
983 	struct preloaded_file	*fp;
984 
985 	if ((fp = malloc(sizeof(struct preloaded_file))) != NULL) {
986 		bzero(fp, sizeof(struct preloaded_file));
987 	}
988 	return (fp);
989 }
990 
991 /*
992  * Add a module to the chain
993  */
994 static void
995 file_insert_tail(struct preloaded_file *fp)
996 {
997 	struct preloaded_file	*cm;
998 
999 	/* Append to list of loaded file */
1000 	fp->f_next = NULL;
1001 	if (preloaded_files == NULL) {
1002 		preloaded_files = fp;
1003 	} else {
1004 		for (cm = preloaded_files; cm->f_next != NULL; cm = cm->f_next)
1005 			;
1006 		cm->f_next = fp;
1007 	}
1008 }
1009 
1010 static char *
1011 moduledir_fullpath(struct moduledir *mdp, const char *fname)
1012 {
1013 	char *cp;
1014 
1015 	cp = malloc(strlen(mdp->d_path) + strlen(fname) + 2);
1016 	if (cp == NULL)
1017 		return NULL;
1018 	strcpy(cp, mdp->d_path);
1019 	strcat(cp, "/");
1020 	strcat(cp, fname);
1021 	return (cp);
1022 }
1023 
1024 /*
1025  * Read linker.hints file into memory performing some sanity checks.
1026  */
1027 static void
1028 moduledir_readhints(struct moduledir *mdp)
1029 {
1030 	struct stat	st;
1031 	char	*path;
1032 	int		fd, size, version;
1033 
1034 	if (mdp->d_hints != NULL || (mdp->d_flags & MDIR_NOHINTS))
1035 		return;
1036 	path = moduledir_fullpath(mdp, "linker.hints");
1037 	if (stat(path, &st) != 0 ||
1038 	  st.st_size < (ssize_t)(sizeof(version) + sizeof(int)) ||
1039 	  st.st_size > LINKER_HINTS_MAX || (fd = open(path, O_RDONLY)) < 0) {
1040 		free(path);
1041 		mdp->d_flags |= MDIR_NOHINTS;
1042 		return;
1043 	}
1044 	free(path);
1045 	size = read(fd, &version, sizeof(version));
1046 	if (size != sizeof(version) || version != LINKER_HINTS_VERSION)
1047 		goto bad;
1048 	size = st.st_size - size;
1049 	mdp->d_hints = malloc(size);
1050 	if (mdp->d_hints == NULL)
1051 		goto bad;
1052 	if (read(fd, mdp->d_hints, size) != size)
1053 		goto bad;
1054 	mdp->d_hintsz = size;
1055 	close(fd);
1056 	return;
1057 bad:
1058 	close(fd);
1059 	if (mdp->d_hints) {
1060 		free(mdp->d_hints);
1061 		mdp->d_hints = NULL;
1062 	}
1063 	mdp->d_flags |= MDIR_NOHINTS;
1064 	return;
1065 }
1066 
1067 /*
1068  * Extract directories from the ';' separated list, remove duplicates.
1069  */
1070 static void
1071 moduledir_rebuild(void)
1072 {
1073 	struct	moduledir *mdp, *mtmp;
1074 	const char	*path, *cp, *ep;
1075 	size_t	cplen;
1076 
1077 	path = getenv("module_path");
1078 	if (path == NULL)
1079 		path = default_searchpath;
1080 	/*
1081 	 * Rebuild list of module directories if it changed
1082 	 */
1083 	STAILQ_FOREACH(mdp, &moduledir_list, d_link)
1084 		mdp->d_flags |= MDIR_REMOVED;
1085 
1086 	for (ep = path; *ep != 0;  ep++) {
1087 		cp = ep;
1088 		for (; *ep != 0 && *ep != ';'; ep++)
1089 			;
1090 		/*
1091 		 * Ignore trailing slashes
1092 		 */
1093 		for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/'; cplen--)
1094 			;
1095 		STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1096 			if (strlen(mdp->d_path) != cplen ||	bcmp(cp, mdp->d_path, cplen) != 0)
1097 				continue;
1098 			mdp->d_flags &= ~MDIR_REMOVED;
1099 			break;
1100 		}
1101 		if (mdp == NULL) {
1102 			mdp = malloc(sizeof(*mdp) + cplen + 1);
1103 			if (mdp == NULL)
1104 				return;
1105 			mdp->d_path = (char*)(mdp + 1);
1106 			bcopy(cp, mdp->d_path, cplen);
1107 			mdp->d_path[cplen] = 0;
1108 			mdp->d_hints = NULL;
1109 			mdp->d_flags = 0;
1110 			STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
1111 		}
1112 		if (*ep == 0)
1113 			break;
1114 	}
1115 	/*
1116 	 * Delete unused directories if any
1117 	 */
1118 	mdp = STAILQ_FIRST(&moduledir_list);
1119 	while (mdp) {
1120 		if ((mdp->d_flags & MDIR_REMOVED) == 0) {
1121 			mdp = STAILQ_NEXT(mdp, d_link);
1122 		} else {
1123 			if (mdp->d_hints)
1124 				free(mdp->d_hints);
1125 			mtmp = mdp;
1126 			mdp = STAILQ_NEXT(mdp, d_link);
1127 			STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
1128 			free(mtmp);
1129 		}
1130 	}
1131 	return;
1132 }
1133