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