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