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