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